-
-
Notifications
You must be signed in to change notification settings - Fork 793
Expand file tree
/
Copy pathresource.py
More file actions
1624 lines (1362 loc) · 58.4 KB
/
Copy pathresource.py
File metadata and controls
1624 lines (1362 loc) · 58.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright (c) 2018 nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/scancode-toolkit/
# The ScanCode software is licensed under the Apache License version 2.0.
# Data generated with ScanCode require an acknowledgment.
# ScanCode is a trademark of nexB Inc.
#
# You may not use this software except in compliance with the License.
# You may obtain a copy of the License at: http://apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
#
# When you publish or redistribute any data created with ScanCode or any ScanCode
# derivative work, you must accompany this data with the following acknowledgment:
#
# Generated with ScanCode and provided on an "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, either express or implied. No content created from
# ScanCode should be considered or used as legal advice. Consult an Attorney
# for any legal advice.
# ScanCode is a free software code scanning tool from nexB Inc. and others.
# Visit https://github.com/nexB/scancode-toolkit/ for support and download.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from collections import deque
from collections import OrderedDict
from functools import partial
import io
import json
import os
from os import walk as os_walk
from os.path import abspath
from os.path import exists
from os.path import expanduser
from os.path import join
from os.path import normpath
import posixpath
import traceback
import sys
import attr
from intbitset import intbitset
try:
from scancode_config import scancode_temp_dir as temp_dir
except ImportError:
# alway have something there.
import tempfile
temp_dir = tempfile.mkdtemp(prefix='scancode-resource-cache')
from commoncode.datautils import List
from commoncode.datautils import Mapping
from commoncode.datautils import String
from commoncode.filetype import is_file as filetype_is_file
from commoncode.filetype import is_special
from commoncode.fileutils import POSIX_PATH_SEP
from commoncode.fileutils import WIN_PATH_SEP
from commoncode.fileutils import as_posixpath
from commoncode.fileutils import create_dir
from commoncode.fileutils import delete
from commoncode.fileutils import file_base_name
from commoncode.fileutils import file_name
from commoncode.fileutils import fsdecode
from commoncode.fileutils import fsencode
from commoncode.fileutils import parent_directory
from commoncode.fileutils import splitext_name
from commoncode import ignore
from commoncode.system import on_linux
# Python 2 and 3 support
try:
# Python 2
unicode
str_orig = str
bytes = str # NOQA
str = unicode # NOQA
except NameError:
# Python 3
unicode = str # NOQA
"""
This module provides Codebase and Resource objects as an abstraction for files
and directories used throughout ScanCode. ScanCode deals with a lot of these as
they are the basic unit of processing.
A Codebase is a tree of Resource. A Resource represents a file or directory and
holds essential file information as attributes. At runtime, scan data is added
as attributes to a Resource. Resource are kept in memory or saved on disk.
This module handles all the details of walking files, path handling and caching.
"""
# Tracing flags
TRACE = False
TRACE_DEEP = False
def logger_debug(*args):
pass
if TRACE or TRACE_DEEP:
import logging
logger = logging.getLogger(__name__)
# logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
logging.basicConfig(stream=sys.stdout)
logger.setLevel(logging.DEBUG)
def logger_debug(*args):
return logger.debug(
' '.join(isinstance(a, unicode) and a or repr(a) for a in args))
class ResourceNotInCache(Exception):
pass
class UnknownResource(Exception):
pass
@attr.s(slots=True)
class Header(object):
"""
Represent a codebase header. Each tool that transforms the codebase
should create a Header and append it to the codebase log_entries list.
"""
tool_name = String(help='Name of the tool used such as scancode-toolkit.')
tool_version = String(default='', help='Tool version used such as v1.2.3.')
options = Mapping(help='Mapping of key/values describing the options used with this tool.')
notice = String(default='', help='Notice text for this tool.')
start_timestamp = String(help='Start timestamp for this header.')
end_timestamp = String(help='End timestamp for this header.')
message = String(help='Message text.')
errors = List(help='List of error messages.')
extra_data = Mapping(help='Mapping of extra key/values for this tool.')
def to_dict(self):
return attr.asdict(self, dict_factory=OrderedDict)
@classmethod
def from_dict(cls, **kwargs):
"""
Return a Header object deserialized from a `kwargs` mapping of
key/values. Unknown attributes are ignored.
"""
known_attributes = set([
'tool_name',
'tool_version',
'options',
'notice',
'start_timestamp',
'end_timestamp',
'message',
'errors',
'extra_data',
])
# pop unknowns
for kwarg in list(kwargs.keys()):
if kwarg not in known_attributes:
kwargs.pop(kwarg)
return cls(**kwargs)
class Codebase(object):
"""
Represent a codebase being scanned. A Codebase is a tree of Resources.
"""
# we do not really need slots but this is a way to ensure we have tight
# control on object attributes
__slots__ = (
'original_location',
'full_root',
'strip_root',
'location',
'has_single_resource',
'resource_attributes',
'resource_class',
'resource_ids',
'root',
'is_file',
'temp_dir',
'resources',
'max_in_memory',
'all_in_memory',
'all_on_disk',
'cache_dir',
'headers',
'current_header',
'codebase_attributes',
'attributes',
'counters',
'timings',
'errors',
)
def __init__(self, location,
resource_attributes=None,
codebase_attributes=None,
full_root=False, strip_root=False,
temp_dir=temp_dir,
max_in_memory=10000):
"""
Initialize a new codebase rooted at the `location` existing file or
directory.
`resource_attributes` is an ordered mapping of attr Resource attributes
such as plugin-provided attributes: these will be added to a Resource
sub-class crafted for this codebase.
`codebase_attributes` is an ordered mapping of attr Codebase attributes
such as plugin-provided attributes: these will be added to a
CodebaseAttributes sub-class crafted for this codebase.
`strip_root` and `full_root`: boolean flags: these control the values
of the path attribute of the codebase Resources. These are mutually
exclusive.
If `strip_root` is True, strip the first `path` segment of a Resource
unless the codebase contains a single root Resource.
If `full_root` is True the path is an an absolute path.
`temp_dir` is the base temporary directory to use to cache resources on
disk and other temporary files.
`max_in_memory` is the maximum number of Resource instances to keep in
memory. Beyond this number, Resource are saved on disk instead. -1 means
no memory is used and 0 means unlimited memory is used.
"""
self.original_location = location
self.full_root = full_root
self.strip_root = strip_root
# Resource sub-class to use: Configured with attributes in _populate
self.resource_class = Resource
self.resource_attributes = resource_attributes or OrderedDict()
self.codebase_attributes = codebase_attributes or OrderedDict()
# setup location
########################################################################
if on_linux:
location = fsencode(location)
else:
location = fsdecode(location)
location = abspath(normpath(expanduser(location)))
location = location.rstrip(POSIX_PATH_SEP).rstrip(WIN_PATH_SEP)
# TODO: we should also accept to create "virtual" codebase without a
# backing filesystem location
assert exists(location)
# FIXME: what if is_special(location)???
self.location = location
self.is_file = filetype_is_file(location)
# True if this codebase root is a file or an empty directory.
self.has_single_resource = bool(self.is_file or not os.listdir(location))
# Set up caching, summary, timing, and error info
self._setup_essentials(temp_dir, max_in_memory)
# finally walk the location and populate
########################################################################
self._populate()
def _setup_essentials(self, temp_dir=temp_dir, max_in_memory=10000):
"""
Set the remaining Codebase attributes
`temp_dir` is the base temporary directory to use to cache resources on
disk and other temporary files.
`max_in_memory` is the maximum number of Resource instances to keep in
memory. Beyond this number, Resource are saved on disk instead. -1 means
no memory is used and 0 means unlimited memory is used.
"""
# setup Resources
########################################################################
# root resource, never cached on disk
self.root = None
# set index of existing resource ids ints, initially allocated with
# 10000 positions (this will grow as needed)
self.resource_ids = intbitset(10000)
# setup caching
########################################################################
# dir used for caching and other temp files
self.temp_dir = temp_dir
# maximmum number of Resource objects kept in memory cached in this
# Codebase. When the number of in-memory Resources exceed this number,
# the next Resource instances are saved to disk instead and re-loaded
# from disk when used/needed.
self.max_in_memory = max_in_memory
# map of {rid: resource} for resources that are kept in memory
self.resources = {}
# use only memory
self.all_in_memory = max_in_memory == 0
# use only disk
self.all_on_disk = max_in_memory == -1
# dir where the on-disk cache is stored
self.cache_dir = None
if not self.all_in_memory:
# this is unique to this codebase instance
self.cache_dir = get_codebase_cache_dir(temp_dir=temp_dir)
# setup extra and misc attributes
########################################################################
# stores a list of Header records for this codebase
self.headers = []
self.current_header = None
# mapping of scan counters at the codebase level such
# as the number of files and directories, etc
self.counters = OrderedDict()
# mapping of timings for scan stage as {stage: time in seconds as float}
# This is populated automatically.
self.timings = OrderedDict()
# list of error strings from collecting the codebase details (such as
# unreadable file, etc).
self.errors = []
def _get_next_rid(self):
"""
Return the next available resource id.
"""
return len(self.resource_ids)
def _get_resource_cache_location(self, rid, create=False):
"""
Return the location where to get/put a Resource in the cache given a
Resource `rid`. Create the directories if requested.
"""
if not self.cache_dir:
return
resid = (b'%08x'if on_linux else '%08x') % rid
cache_sub_dir, cache_file_name = resid[-2:], resid
parent = join(self.cache_dir, cache_sub_dir)
if create and not exists(parent):
create_dir(parent)
return join(parent, cache_file_name)
# TODO: add populate progress manager!!!
def _populate(self):
"""
Populate this codebase with Resource objects.
Population is done by walking its `location` topdown, breadth-first,
first creating first file then directory Resources both sorted in case-
insensitive name order.
Special files, links and VCS files are ignored.
"""
# Codebase attributes to use. Configured with plugin attributes if present.
cbac = get_codebase_attributes_class(self.codebase_attributes)
self.attributes = cbac()
# Resource sub-class to use. Configured with plugin attributes if present
self.resource_class = attr.make_class(
name=b'ScannedResource',
attrs=self.resource_attributes or {},
slots=True,
# frozen=True,
bases=(Resource,))
def err(_error):
"""os.walk error handler"""
self.errors.append(
('ERROR: cannot populate codebase: %(_error)r\n' % _error)
+traceback.format_exc())
def skip_ignored(_loc):
"""Always ignore VCS and some special filetypes."""
ignored = partial(ignore.is_ignored, ignores=ignore.ignores_VCS)
if TRACE_DEEP:
logger_debug()
logger_debug('Codebase.populate: walk: ignored loc:', _loc,
'ignored:', ignored(_loc),
'is_special:', is_special(_loc))
return is_special(_loc) or ignored(_loc)
def create_resources(_seq, _top, _parent, _is_file):
"""Create Resources of parent from a seq of files or directories."""
_seq.sort(key=lambda p: (p.lower(), p))
for name in _seq:
location = join(_top, name)
if skip_ignored(location):
continue
res = self._create_resource(name, parent=_parent, is_file=_is_file)
if not _is_file:
# on the plain, bare FS, files cannot be parents
parent_by_loc[location] = res
if TRACE: logger_debug('Codebase.populate:', res)
root = self._create_root_resource()
if TRACE: logger_debug('Codebase.populate: root:', root)
if self.has_single_resource:
# there is nothing else to do for a single file or a single
# childless directory
return
# track resources parents by location during construction.
# NOTE: this cannot exhaust memory on a large codebase, because we do
# not keep parents already walked and we walk topdown.
parent_by_loc = {root.location: root}
# walk proper
for top, dirs, files in os_walk(root.location, topdown=True, onerror=err):
if skip_ignored(top):
continue
# the parent reference is needed only once in a top-down walk, hence
# the pop
parent = parent_by_loc.pop(top)
create_resources(files, top, parent, _is_file=True)
create_resources(dirs, top, parent, _is_file=False)
def _create_root_resource(self):
"""
Create and return the root Resource of this codebase.
"""
# we cannot recreate a root if it exists!!
if self.root:
raise TypeError('Root resource already exists and cannot be recreated')
location = self.location
name = file_name(location)
# do not strip root for codebase with a single Resource.
if self.strip_root:
if self.has_single_resource:
path = fsdecode(name)
else:
# NOTE: this may seem weird but the root path will be an empty
# string for a codebase root with strip_root=True if not
# single_resource
path = ''
else:
path = get_path(location, location, full_root=self.full_root,
strip_root=self.strip_root)
if TRACE:
logger_debug(' Codebase._create_root_resource:', path)
logger_debug()
root = self.resource_class(name=name, location=location, path=path,
rid=0, pid=None, is_file=self.is_file)
self.resource_ids.add(0)
self.resources[0] = root
self.root = root
return root
def _create_resource(self, name, parent, is_file=False, path=None, resource_data=None):
"""
Create and return a new Resource in this codebase with `name` as a child
of the `parent` Resource.
`name` is always in native OS-preferred encoding (e.g. byte on Linux,
unicode elsewhere).
"""
if parent is None:
raise TypeError('Cannot create resource without parent.')
rid = self._get_next_rid()
if self._use_disk_cache_for_resource(rid):
cache_location = self._get_resource_cache_location(rid, create=True)
else:
cache_location = None
# If the codebase is virtual, then there is no location
parent_location = parent.location
if parent_location:
location = join(parent_location, name)
else:
location = None
# If the codebase is virtual, we provide the path
if not path:
path = posixpath.join(parent.path, fsdecode(name))
if TRACE:
logger_debug(' Codebase._create_resource: parent.path:', parent.path, 'path:', path)
resource_data = resource_data or {}
if resource_data:
resource_data = remove_properties_and_basics(resource_data)
child = self.resource_class(
name=name,
location=location,
path=path,
cache_location=cache_location,
rid=rid,
pid=parent.rid,
is_file=is_file,
**resource_data
)
self.resource_ids.add(rid)
parent.children_rids.append(rid)
# TODO: fixme, this is not great to save also the parent :|
self.save_resource(parent)
self.save_resource(child)
return child
def get_or_create_current_header(self):
"""
Return the current Header. Create it if it does not exists and store
it in the headers.
"""
if not self.current_header:
self.current_header = Header()
self.headers.append(self.current_header)
return self.current_header
def get_files_count(self):
"""
Return the final files counts for the codebase.
"""
return self.counters.get('final:files_count', 0)
def add_files_count_to_current_header(self):
"""
Add the final files counts for the codebase to the current header.
Return the files_count.
"""
files_count = self.get_files_count()
current_header = self.get_or_create_current_header()
current_header.extra_data['files_count'] = files_count
return files_count
def get_headers(self):
"""
Return a serialized headers composed only of native Python objects
suitable for use in outputs.
"""
return [le.to_dict() for le in (self.headers or [])]
def exists(self, resource):
"""
Return True if the Resource with `rid` exists in the codebase.
"""
return resource.rid in self.resource_ids
def _use_disk_cache_for_resource(self, rid):
"""
Return True if Resource `rid` should be cached on-disk or False if it
should be cached in-memory.
"""
if TRACE:
msg = [' Codebase._use_disk_cache_for_resource:, rid:', rid, 'mode:']
if rid == 0:
msg.append('root')
elif self.all_on_disk:
msg.append('all_on_disk')
elif self.all_in_memory:
msg.append('all_in_memory')
else:
msg.extend(['mixed:', 'self.max_in_memory:', self.max_in_memory])
if rid < self.max_in_memory:
msg.append('from memory')
else:
msg.append('from disk')
logger_debug(*msg)
if rid == 0:
return False
elif self.all_on_disk:
return True
elif self.all_in_memory:
return False
# mixed case where some are in memory and some on disk
elif rid < self.max_in_memory:
return False
else:
return True
def _exists_in_memory(self, rid):
"""
Return True if Resource `rid` exists in the codebase memory cache.
"""
return rid in self.resources
def _exists_on_disk(self, rid):
"""
Return True if Resource `rid` exists in the codebase disk cache.
"""
cache_location = self._get_resource_cache_location(rid)
if cache_location:
return exists(cache_location)
def get_resource(self, rid):
"""
Return the Resource with `rid` or None if it does not exists.
"""
if TRACE:
msg = [' Codebase.get_resource:', 'rid:', rid]
if rid == 0:
msg.append('root')
elif not rid or rid not in self.resource_ids:
msg.append('not in resources!')
elif self._use_disk_cache_for_resource(rid):
msg.extend(['from disk', 'exists:', self._exists_on_disk(rid)])
else:
msg.extend(['from memory', 'exists:', self._exists_in_memory(rid)])
logger_debug(*msg)
if rid == 0:
res = attr.evolve(self.root)
elif self._use_disk_cache_for_resource(rid):
res = self._load_resource(rid)
elif not rid or rid not in self.resource_ids:
res = None
else:
res = self.resources.get(rid)
res = attr.evolve(res)
if TRACE:
logger_debug(' Resource:', res)
return res
def save_resource(self, resource):
"""
Save the `resource` Resource to cache (in memory or disk).
"""
if TRACE:
msg = [' Codebase.save_resource:', resource]
rid = resource.rid
if resource.is_root:
msg.append('root')
elif rid not in self.resource_ids:
msg.append('missing resource')
elif self._use_disk_cache_for_resource(rid):
msg.extend(['to disk:', 'exists:', self._exists_on_disk(rid)])
else:
msg.extend(['to memory:', 'exists:', self._exists_in_memory(rid)])
logger_debug(*msg)
if not resource:
return
rid = resource.rid
if rid not in self.resource_ids:
raise UnknownResource('Not part of codebase: %(resource)r' % locals())
if resource.is_root:
# this can possibly damage things badly
self.root = resource
if self._use_disk_cache_for_resource(rid):
self._dump_resource(resource)
else:
self.resources[rid] = resource
def _dump_resource(self, resource):
"""
Dump a Resource to the disk cache.
"""
cache_location = resource.cache_location
if not cache_location:
raise TypeError('Resource cannot be dumped to disk and is used only'
'in memory: %(resource)r' % resource)
# TODO: consider messagepack or protobuf for compact/faster processing?
with open(cache_location , 'wb') as cached:
cached.write(json.dumps(resource.serialize(), check_circular=False))
# TODO: consider adding a small LRU cache in front of this for perf?
def _load_resource(self, rid):
"""
Return a Resource with `rid` loaded from the disk cache.
"""
cache_location = self._get_resource_cache_location(rid, create=False)
if TRACE:
logger_debug(' Codebase._load_resource: exists:', exists(cache_location), 'cache_location:', cache_location)
if not exists(cache_location):
raise ResourceNotInCache(
'Failed to load Resource: %(rid)d from %(cache_location)r' % locals())
# TODO: consider messagepack or protobuf for compact/faster processing
try:
with open(cache_location, 'rb') as cached:
data = json.load(cached, object_pairs_hook=OrderedDict, encoding='utf-8')
return self.resource_class(**data)
except Exception:
with open(cache_location, 'rb') as cached:
cached_data = cached.read()
msg = ('ERROR: failed to load resource from cached location: {cache_location} with content:\n\n'.format(**locals())
+repr(cached_data)
+'\n\n'
+traceback.format_exc())
raise Exception(msg)
def _remove_resource(self, resource):
"""
Remove the `resource` Resource object from the resource tree.
Does not remove children.
"""
if resource.is_root:
raise TypeError('Cannot remove the root resource from '
'codebase:', repr(resource))
rid = resource.rid
# remove from index.
self.resource_ids.discard(rid)
# remove from in-memory cache. The disk cache is cleared on exit.
self.resources.pop(rid, None)
if TRACE:
logger_debug('Codebase._remove_resource:', resource)
def remove_resource(self, resource):
"""
Remove the `resource` Resource object and all its children from the
resource tree. Return a set of removed Resource ids.
"""
if TRACE:
logger_debug('Codebase.remove_resource')
logger_debug(' resource', resource)
if resource.is_root:
raise TypeError('Cannot remove the root resource from '
'codebase:', repr(resource))
removed_rids = set()
# remove all descendants bottom up to avoid out-of-order access to
# removed resources
for descendant in resource.walk(self, topdown=False):
self._remove_resource(descendant)
removed_rids.add(descendant.rid)
# remove resource from parent
parent = resource.parent(self)
if TRACE: logger_debug(' parent', parent)
parent.children_rids.remove(resource.rid)
parent.save(self)
# remove resource proper
self._remove_resource(resource)
removed_rids.add(resource.rid)
return removed_rids
def walk(self, topdown=True, skip_root=False):
"""
Yield all resources for this Codebase walking its resource tree.
Walk the tree top-down, depth-first if `topdown` is True, otherwise walk
bottom-up.
Each level is sorted by children sort order (e.g. without-children, then
with-children and each group by case-insensitive name)
If `skip_root` is True, the root resource is not returned unless this is
a codebase with a single resource.
"""
root = self.root
# include root if no children (e.g. codebase with a single resource)
if skip_root and not root.has_children():
skip_root = False
root = attr.evolve(root)
if topdown and not skip_root:
yield root
for res in root.walk(self, topdown):
yield res
if not topdown and not skip_root:
yield root
def get_resource_from_path(self, path, absolute=False):
"""
Return a Resource that matches the path or or None. If `absolute` is
True, treat the path as an absolute location. Otherwise as relative to
the root (and including it).
"""
for res in self.walk():
if absolute:
if path == res.location:
return res
else:
if path == res.path:
return res
def walk_filtered(self, topdown=True, skip_root=False):
"""
Walk this Codebase as with walk() but does not return Resources with
`is_filtered` flag set to True.
"""
for resource in self.walk(topdown, skip_root):
if resource.is_filtered:
continue
yield resource
def compute_counts(self, skip_root=False, skip_filtered=False):
"""
Compute and update the counts of every resource.
Return a tuple of top level counters (files_count, dirs_count,
size_count) for this codebase.
The counts are computed differently based on these falsg:
- If `skip_root` is True, the root resource is not included in counts.
- If `skip_filtered` is True, resources with `is_filtered` set to True
are not included in counts.
"""
self.update_counts(skip_filtered=skip_filtered)
root = self.root
files_count = root.files_count
dirs_count = root.dirs_count
size_count = root.size_count
if (skip_root and not root.is_file) or (skip_filtered and root.is_filtered):
return files_count, dirs_count, size_count
if root.is_file:
files_count += 1
else:
dirs_count += 1
size_count += root.size
return files_count, dirs_count, size_count
def update_counts(self, skip_filtered=False):
"""
Update files_count, dirs_count and size_count attributes of each
Resource in this codebase based on the current state.
If `skip_filtered` is True, resources with `is_filtered` set to True are
not included in counts.
"""
# note: we walk bottom up to update things in the proper order
# and the walk MUST NOT skip filtered, only the compute
for resource in self.walk(topdown=False):
try:
resource._compute_children_counts(self, skip_filtered)
except Exception:
path = resource.path
msg = ('ERROR: cannot compute children counts for: {path}:\n'.format(**locals())
+traceback.format_exc())
raise Exception(msg)
def clear(self):
"""
Purge the codebase cache(s).
"""
delete(self.cache_dir)
def lowest_common_parent(self):
"""
Return a Resource that is the lowest common parent of all the files of
this codebase, skipping empty root directory segments.
Return None is this codebase contains a single resource.
"""
if self.has_single_resource:
return self.root
for res in self.walk(topdown=True):
if not res.is_file:
kids = res.children(self)
if len(kids) == 1 and not kids[0].is_file:
# this is an empty dir with a single dir child
# we shall continue the descent walk
continue
else:
# the dir starts to branch: we have our root
break
else:
# we are in a case that should never happen
return self.root
return res
def to_native_path(path):
"""
Return `path` using the preferred OS encoding (bytes on Linux,
Unicode elsewhere) given a unicode or bytes path string.
"""
if not path:
return path
if on_linux:
return fsencode(path)
else:
return fsdecode(path)
def to_decoded_posix_path(path):
"""
Return `path` as a Unicode POSIX path given a unicode or bytes path string.
"""
return fsdecode(as_posixpath(path))
@attr.attributes(slots=True)
class Resource(object):
"""
A resource represent a file or directory with essential "file information"
and the scanned data details.
A Resource is a tree that models the fileystem tree structure.
In order to support lightweight and smaller objects that can be serialized
and deserialized (such as pickled in multiprocessing) without pulling in a
whole object tree, a Resource does not store its related objects directly:
the Codebase it belongs to, its parent Resource and its Resource children
objects are stored only as integer ids. Querying the Resource relationships
and walking the Resources tree requires to lookup the corresponding object
by id in the codebase object.
"""
# the file or directory name in the OS preferred representation (either
# bytes on Linux and Unicode elsewhere)
name = attr.attrib(converter=to_native_path, repr=False)
# the file or directory absolute location in the OS preferred representation
# (either bytes on Linux and Unicode elsewhere) using the OS native path
# separators.
location = attr.attrib(converter=to_native_path, repr=False)
# the file or directory POSIX path decoded as unicode using the filesystem
# encoding. This is the path that will be reported in output and can be
# either one of these:
# - if the codebase was created with strip_root==True, this is a path
# relative to the root, stripped from its root segment unless the codebase
# contains a single file.
# - if the codebase was created with full_root==True, this is an absolute
# path
path = attr.attrib(converter=to_decoded_posix_path)
# resource id as an integer
# the root of a Resource tree has a pid==0 by convention
rid = attr.ib()
# parent resource id of this resource as an integer
# the root of a Resource tree has a pid==None by convention
pid = attr.ib()
# location of the file where this resource can be chached on disk in the OS
# preferred representation (either bytes on Linux and Unicode elsewhere)
cache_location = attr.attrib(default=None, converter=to_native_path, repr=False)
# True for file, False for directory
is_file = attr.ib(default=False)
# True if this Resource should be filtered out, e.g. skipped from the
# returned list of resources
is_filtered = attr.ib(default=False)
# a list of rids
children_rids = attr.ib(default=attr.Factory(list), repr=TRACE)
# external data to serialize
size = attr.ib(default=0, type=int, repr=TRACE)
# These attributes are re/computed for directories and files with children
# they represent are the for the full descendants of a Resource
size_count = attr.ib(default=0, type=int, repr=False)
files_count = attr.ib(default=0, type=int, repr=False)
dirs_count = attr.ib(default=0, type=int, repr=False)
# list of scan error strings
scan_errors = attr.ib(default=attr.Factory(list), repr=False)
# Duration in seconds as float to run all scans for this resource
scan_time = attr.ib(default=0, repr=False)
# mapping of timings for each scan as {scan_key: duration in seconds as a float}
scan_timings = attr.ib(default=attr.Factory(OrderedDict), repr=False)
# stores a mapping of extra data for this Resource this data is
# never returned in a to_dict() and not meant to be saved in the
# final scan results. Instead it can be used to store extra data
# attributes that may be useful during a scan processing but are not
# usefuol afterwards. Be careful when using this not to override
# keys/valoues that may have been created by some other plugin or
# process