-
-
Notifications
You must be signed in to change notification settings - Fork 552
/
cli.py
1595 lines (1316 loc) · 60.8 KB
/
cli.py
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
import logging
# Import first because this import has monkey-patching side effects
from scancode.pool import get_pool
# Import early because of the side effects
import scancode_config
from collections import defaultdict
from collections import OrderedDict
from functools import partial
from commoncode.system import on_windows
# Python 2 and 3 support
try:
# Python 2
import itertools.imap as map # NOQA
except ImportError:
# Python 3
pass
import os
import sys
from time import sleep
from time import time
import traceback
# this exception is not available on posix
try:
WindowsError # NOQA
except NameError:
class WindowsError(Exception):
pass
import click # NOQA
click.disable_unicode_literals_warning = True
from six import string_types
# import early
from scancode_config import __version__ as scancode_version
from commoncode import compat
from commoncode.fileutils import as_posixpath
from commoncode.fileutils import PATH_TYPE
from commoncode.fileutils import POSIX_PATH_SEP
from commoncode.timeutils import time2tstamp
from commoncode.system import py2
from commoncode.system import on_linux
from plugincode import PluginManager
# these are important to register plugin managers
from plugincode import pre_scan
from plugincode import scan
from plugincode import post_scan
from plugincode import output_filter
from plugincode import output
from scancode import ScancodeError
from scancode import ScancodeCliUsageError
from scancode import CORE_GROUP
from scancode import DOC_GROUP
from scancode import MISC_GROUP
from scancode import OTHER_SCAN_GROUP
from scancode import OUTPUT_GROUP
from scancode import OUTPUT_FILTER_GROUP
from scancode import OUTPUT_CONTROL_GROUP
from scancode import POST_SCAN_GROUP
from scancode import PRE_SCAN_GROUP
from scancode import SCAN_GROUP
from scancode import SCAN_OPTIONS_GROUP
from scancode import CommandLineOption
from scancode import notice
from scancode import print_about
from scancode import Scanner
from scancode import validate_option_dependencies
from scancode.help import epilog_text
from scancode.help import examples_text
from scancode.interrupt import DEFAULT_TIMEOUT
from scancode.interrupt import fake_interruptible
from scancode.interrupt import interruptible
from scancode.resource import Codebase
from scancode.resource import VirtualCodebase
from scancode.utils import BaseCommand
from scancode.utils import path_progress_message
from scancode.utils import progressmanager
# 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(stream=sys.stdout)
logger.setLevel(logging.DEBUG)
def logger_debug(*args):
return logger.debug(' '.join(isinstance(a, string_types)
and a or repr(a) for a in args))
echo_stderr = partial(click.secho, err=True)
def print_examples(ctx, param, value):
if not value or ctx.resilient_parsing:
return
click.echo(examples_text)
ctx.exit()
def print_version(ctx, param, value):
if not value or ctx.resilient_parsing:
return
click.echo('ScanCode version ' + scancode_version)
ctx.exit()
class ScanCommand(BaseCommand):
"""
A command class that is aware of ScanCode options that provides enhanced
help where each option is grouped by group.
"""
short_usage_help = '''
Try 'scancode --help' for help on options and arguments.'''
def __init__(self, name, context_settings=None, callback=None, params=None,
help=None, # NOQA
epilog=None, short_help=None,
options_metavar='[OPTIONS]', add_help_option=True,
plugin_options=()):
"""
Create a new ScanCommand using the `plugin_options` list of
CommandLineOption instances.
"""
super(ScanCommand, self).__init__(name, context_settings, callback,
params, help, epilog, short_help, options_metavar, add_help_option)
# this makes the options "known" to the command
self.params.extend(plugin_options)
def format_options(self, ctx, formatter):
"""
Overridden from click.Command to write all options into the formatter in
help_groups they belong to. If a group is not specified, add the option
to MISC_GROUP group.
"""
# this mapping defines the CLI help presentation order
help_groups = OrderedDict([
(SCAN_GROUP, []),
(OTHER_SCAN_GROUP, []),
(SCAN_OPTIONS_GROUP, []),
(OUTPUT_GROUP, []),
(OUTPUT_FILTER_GROUP, []),
(OUTPUT_CONTROL_GROUP, []),
(PRE_SCAN_GROUP, []),
(POST_SCAN_GROUP, []),
(CORE_GROUP, []),
(MISC_GROUP, []),
(DOC_GROUP, []),
])
for param in self.get_params(ctx):
# Get the list of option's name and help text
help_record = param.get_help_record(ctx)
if not help_record:
continue
# organize options by group
help_group = getattr(param, 'help_group', MISC_GROUP)
sort_order = getattr(param, 'sort_order', 100)
help_groups[help_group].append((sort_order, help_record))
with formatter.section('Options'):
for group, help_records in help_groups.items():
if not help_records:
continue
with formatter.section(group):
sorted_records = [help_record for _, help_record in sorted(help_records)]
formatter.write_dl(sorted_records)
try:
# IMPORTANT: this discovers, loads and validates all available plugins
plugin_classes, plugin_options = PluginManager.load_plugins()
except ImportError as e:
echo_stderr('========================================================================')
echo_stderr('ERROR: Unable to import ScanCode plugins.'.upper())
echo_stderr('Check your installation configuration (setup.py) or re-install/re-configure ScanCode.')
echo_stderr('The following plugin(s) are referenced and cannot be loaded/imported:')
echo_stderr(str(e), color='red')
echo_stderr('========================================================================')
raise e
def print_plugins(ctx, param, value):
if not value or ctx.resilient_parsing:
return
for plugin_cls in sorted(plugin_classes, key=lambda pc: (pc.stage, pc.name)):
click.echo('--------------------------------------------')
click.echo('Plugin: scancode_{self.stage}:{self.name}'.format(self=plugin_cls), nl=False)
click.echo(' class: {self.__module__}:{self.__name__}'.format(self=plugin_cls))
codebase_attributes = ', '.join(plugin_cls.codebase_attributes)
click.echo(' codebase_attributes: {}'.format(codebase_attributes))
resource_attributes = ', '.join(plugin_cls.resource_attributes)
click.echo(' resource_attributes: {}'.format(resource_attributes))
click.echo(' sort_order: {self.sort_order}'.format(self=plugin_cls))
required_plugins = ', '.join(plugin_cls.required_plugins)
click.echo(' required_plugins: {}'.format(required_plugins))
click.echo(' options:')
for option in plugin_cls.options:
name = option.name
opts = ', '.join(option.opts)
help_group = option.help_group
help_txt = option.help # noqa
click.echo(' help_group: {help_group!s}, name: {name!s}: {opts}\n help: {help_txt!s}'.format(**locals()))
click.echo(' doc: {self.__doc__}'.format(self=plugin_cls))
click.echo('')
ctx.exit()
def print_options(ctx, param, value):
if not value or ctx.resilient_parsing:
return
values = ctx.params
click.echo('Options:')
for name, val in sorted(values.items()):
click.echo(' {name}: {val}'.format(**locals()))
click.echo('')
ctx.exit()
@click.command(name='scancode',
epilog=epilog_text,
cls=ScanCommand,
plugin_options=plugin_options)
@click.pass_context
@click.argument('input',
metavar='<OUTPUT FORMAT OPTION(s)> <input>...', nargs=-1,
# ensure that the input path is bytes on Linux, unicode elsewhere
type=click.Path(exists=True, readable=True, path_type=PATH_TYPE))
@click.option('--strip-root',
is_flag=True,
conflicting_options=['full_root'],
help='Strip the root directory segment of all paths. The default is to '
'always include the last directory segment of the scanned path such '
'that all paths have a common root directory.',
help_group=OUTPUT_CONTROL_GROUP, cls=CommandLineOption)
@click.option('--full-root',
is_flag=True,
conflicting_options=['strip_root'],
help='Report full, absolute paths.',
help_group=OUTPUT_CONTROL_GROUP, cls=CommandLineOption)
@click.option('-n', '--processes',
type=int, default=1,
metavar='INT',
help='Set the number of parallel processes to use. '
'Disable parallel processing if 0. Also disable threading if -1. [default: 1]',
help_group=CORE_GROUP, sort_order=10, cls=CommandLineOption)
@click.option('--timeout',
type=float, default=DEFAULT_TIMEOUT,
metavar='<secs>',
help='Stop an unfinished file scan after a timeout in seconds. '
'[default: %d seconds]' % DEFAULT_TIMEOUT,
help_group=CORE_GROUP, sort_order=10, cls=CommandLineOption)
@click.option('--quiet',
is_flag=True,
conflicting_options=['verbose'],
help='Do not print summary or progress.',
help_group=CORE_GROUP, sort_order=20, cls=CommandLineOption)
@click.option('--verbose',
is_flag=True,
conflicting_options=['quiet'],
help='Print progress as file-by-file path instead of a progress bar. '
'Print verbose scan counters.',
help_group=CORE_GROUP, sort_order=20, cls=CommandLineOption)
@click.option('--from-json',
is_flag=True,
multiple=True,
help='Load codebase from an existing JSON scan',
help_group=CORE_GROUP, sort_order=25, cls=CommandLineOption)
@click.option('--timing',
is_flag=True,
hidden=True,
help='Collect scan timing for each scan/scanned file.',
help_group=CORE_GROUP, sort_order=250, cls=CommandLineOption)
@click.option('--max-in-memory',
type=int, default=10000,
show_default=True,
help=
'Maximum number of files and directories scan details kept in memory '
'during a scan. Additional files and directories scan details above this '
'number are cached on-disk rather than in memory. '
'Use 0 to use unlimited memory and disable on-disk caching. '
'Use -1 to use only on-disk caching.',
help_group=CORE_GROUP, sort_order=300, cls=CommandLineOption)
@click.help_option('-h', '--help',
help_group=DOC_GROUP, sort_order=10, cls=CommandLineOption)
@click.option('--about',
is_flag=True, is_eager=True, expose_value=False,
callback=print_about,
help='Show information about ScanCode and licensing and exit.',
help_group=DOC_GROUP, sort_order=20, cls=CommandLineOption)
@click.option('--version',
is_flag=True, is_eager=True, expose_value=False,
callback=print_version,
help='Show the version and exit.',
help_group=DOC_GROUP, sort_order=20, cls=CommandLineOption)
@click.option('--examples',
is_flag=True, is_eager=True, expose_value=False,
callback=print_examples,
help=('Show command examples and exit.'),
help_group=DOC_GROUP, sort_order=50, cls=CommandLineOption)
@click.option('--plugins',
is_flag=True, is_eager=True, expose_value=False,
callback=print_plugins,
help='Show the list of available ScanCode plugins and exit.',
help_group=DOC_GROUP, cls=CommandLineOption)
@click.option('--test-mode',
is_flag=True, default=False,
# not yet supported in Click 6.7 but added in CommandLineOption
hidden=True,
help='Run ScanCode in a special "test mode". Only for testing.',
help_group=MISC_GROUP, sort_order=1000, cls=CommandLineOption)
@click.option('--test-slow-mode',
is_flag=True, default=False,
# not yet supported in Click 6.7 but added in CommandLineOption
hidden=True,
help='Run ScanCode in a special "test slow mode" to ensure that --email scan needs at least one second to complete. Only for testing.',
help_group=MISC_GROUP, sort_order=1000, cls=CommandLineOption)
@click.option('--test-error-mode',
is_flag=True, default=False,
# not yet supported in Click 6.7 but added in CommandLineOption
hidden=True,
help='Run ScanCode in a special "test error mode" to trigger errors with the --email scan. Only for testing.',
help_group=MISC_GROUP, sort_order=1000, cls=CommandLineOption)
@click.option('--print-options',
is_flag=True,
expose_value=False,
callback=print_options,
help='Show the list of selected options and exit.',
help_group=DOC_GROUP, cls=CommandLineOption)
@click.option('--keep-temp-files',
is_flag=True, default=False,
help='Keep temporary files and show the directory where temporary files '
'are stored. (By default temporary files are deleted when a scan is '
'completed.)',
hidden=True,
help_group=MISC_GROUP, sort_order=1000, cls=CommandLineOption)
def scancode(ctx, input, # NOQA
strip_root, full_root,
processes, timeout,
quiet, verbose,
from_json,
timing,
max_in_memory,
test_mode,
test_slow_mode,
test_error_mode,
keep_temp_files,
echo_func=echo_stderr,
*args, **kwargs):
"""scan the <input> file or directory for license, origin and packages and save results to FILE(s) using one or more output format option.
Error and progress are printed to stderr.
"""
# notes: the above docstring of this function is used in the CLI help Here is
# it's actual docstring:
"""
This function is the main ScanCode CLI entry point.
Return a return code of 0 on success or a positive integer on error from
running all the scanning "stages" with the `input` file or
directory.
The scanning stages are:
- `inventory`: collect the codebase inventory resources tree for the
`input`. This is a built-in stage that does not accept plugins.
- `setup`: as part of the plugins system, each plugin is loaded and
its `setup` method is called if it is enabled.
- `pre-scan`: each enabled pre-scan plugin `process_codebase(codebase)`
method is called to update/transforme the whole codebase.
- `scan`: the codebase is walked and each enabled scan plugin
`get_scanner()` scanner function is called once for each codebase
resource receiving the `resource.location` as an argument.
- `post-scan`: each enabled post-scan plugin `process_codebase(codebase)`
method is called to update/transform the whole codebase.
- `output_filter`: the `process_resource` method of each enabled
output_filter plugin is called on each resource to determine if the
resource should be kept or not in the output stage.
- `output`: each enabled output plugin `process_codebase(codebase)`
method is called to create an output for the codebase filtered resources.
Beside `input`, the other arguments are:
- `strip_root` and `full_root`: boolean flags: In the outputs, strip the
first path segment of a file if `strip_root` is True unless the `input` is
a single file. If `full_root` is True report the path as an absolute path.
These options are mutually exclusive.
- `processes`: int: run the scan using up to this number of processes in
parallel. If 0, disable the multiprocessing machinery. if -1 also
disable the multithreading machinery.
- `timeout`: float: intterup the scan of a file if it does not finish within
`timeout` seconds. This applied to each file and scan individually (e.g.
if the license scan is interrupted they other scans may complete, each
withing the timeout)
- `quiet` and `verbose`: boolean flags: Do not display any message if
`quiet` is True. Otherwise, display extra verbose messages if `quiet` is
False and `verbose` is True. These two options are mutually exclusive.
- `timing`: boolean flag: collect per-scan and per-file scan timings if
True.
Other **kwargs are passed down to plugins as CommandOption indirectly
through Click context machinery.
"""
# configure a null root handler ONLY when used as a command line
# otherwise no root handler is set
logging.getLogger().addHandler(logging.NullHandler())
success = False
try:
# Validate CLI UI options dependencies and other CLI-specific inits
if TRACE_DEEP:
logger_debug('scancode: ctx.params:')
for co in sorted(ctx.params.items()):
logger_debug(' scancode: ctx.params:', co)
validate_option_dependencies(ctx)
pretty_params = get_pretty_params(ctx, generic_paths=test_mode)
# run proper
success, _results = run_scan(
input=input,
from_json=from_json,
strip_root=strip_root, full_root=full_root,
processes=processes, timeout=timeout,
quiet=quiet, verbose=verbose,
timing=timing, max_in_memory=max_in_memory,
test_mode=test_mode,
test_slow_mode=test_slow_mode,
test_error_mode=test_error_mode,
keep_temp_files=keep_temp_files,
pretty_params=pretty_params,
# results are saved to file, no need to get them back in a cli context
return_results=False,
echo_func=echo_stderr,
*args, **kwargs)
# check for updates
from scancode.outdated import check_scancode_version
outdated = check_scancode_version()
if not quiet and outdated:
echo_stderr(outdated, fg='yellow')
except click.UsageError as e:
# this will exit
raise e
except ScancodeError as se:
# this will exit
raise click.BadParameter(str(se))
rc = 0 if success else 1
ctx.exit(rc)
def run_scan(
input, # NOQA
from_json=None,
strip_root=False,
full_root=False,
max_in_memory=10000,
processes=1,
timeout=120,
quiet=True,
verbose=False,
echo_func=None,
timing=False,
keep_temp_files=False,
return_results=True,
test_mode=False,
test_slow_mode=False,
test_error_mode=False,
pretty_params=None,
*args, **kwargs):
"""
Run a scan on `input` path (or a list of input paths) and return a tuple of
(success, results) where success is a boolean and results is a list of
"files" items using the same data structure as the "files" in the JSON scan
results but as native Python. Raise Exceptions (e.g. ScancodeError) on
error. See scancode() for arguments details.
"""
if not echo_func:
def echo_func(*_args, **_kwargs):
pass
if not input:
msg = 'At least one input path is required.'
raise ScancodeError(msg)
if not isinstance(input, (list, tuple)):
# nothing else todo
if on_linux and py2:
assert isinstance(input, bytes)
else:
assert isinstance(input, compat.unicode)
elif len(input) == 1:
# we received a single input path, so we treat this as a single path
input = input[0] # NOQA
# This is the case where we have a list of inputs, but the list of inputs are not from the
# `from_json` option. If the `from_json` option is available and we have a list of inputs
# from it, we can pass `input` just fine when we create a VirtualCodebase, otherwise we have to
# process `input` below.
elif not from_json:
# we received a several input paths: we can handle this IFF they share
# a common root directory and none is an absolute path
if any(os.path.isabs(p) for p in input):
msg = ('Invalid inputs: all input paths must be relative.')
raise ScancodeError(msg)
# find the common prefix directory (note that this is a pre string operation
# hence it may return non-existing paths
common_prefix = os.path.commonprefix(input)
if not common_prefix:
# we have no common prefix, but all relative. therefore the
# parent/root is the current ddirectory
common_prefix = PATH_TYPE('.')
elif not os.path.isdir(common_prefix):
msg = 'Invalid inputs: all input paths must share a common parent directory.'
raise ScancodeError(msg)
# and we craft a list of synthetic --include path pattern options from
# the input list of paths
included_paths = [as_posixpath(path).rstrip(POSIX_PATH_SEP) for path in input]
# FIXME: this is a hack as this "include" is from an external plugin!!!1
include = list(kwargs.get('include', []) or [])
include.extend(included_paths)
kwargs['include'] = include
# ... and use the common prefix as our new input
input = common_prefix # NOQA
# build mappings of all kwargs to pass down to plugins
standard_kwargs = dict(
input=input,
strip_root=strip_root,
full_root=full_root,
processes=processes,
timeout=timeout,
quiet=quiet,
verbose=verbose,
from_json=from_json,
timing=timing,
max_in_memory=max_in_memory,
test_mode=test_mode,
test_slow_mode=test_slow_mode,
test_error_mode=test_error_mode,
)
kwargs.update(standard_kwargs)
success = True
results = None
codebase = None
processing_start = time()
start_timestamp = time2tstamp()
if not quiet:
if not processes:
echo_func('Disabling multi-processing for debugging.', fg='yellow')
elif processes == -1:
echo_func('Disabling multi-processing '
'and multi-threading for debugging.', fg='yellow')
try:
########################################################################
# Find and create known plugin instances and collect the enabled
########################################################################
enabled_plugins_by_stage = OrderedDict()
all_enabled_plugins_by_qname = {}
non_enabled_plugins_by_qname = {}
for stage, manager in PluginManager.managers.items():
enabled_plugins_by_stage[stage] = stage_plugins = []
for plugin_cls in manager.plugin_classes:
try:
name = plugin_cls.name
qname = plugin_cls.qname()
plugin = plugin_cls(**kwargs)
is_enabled = False
try:
is_enabled = plugin.is_enabled(**kwargs)
except TypeError as te:
if not 'takes exactly' in str(te):
raise te
if is_enabled:
stage_plugins.append(plugin)
all_enabled_plugins_by_qname[qname] = plugin
else:
non_enabled_plugins_by_qname[qname] = plugin
except:
msg = 'Failed to load plugin: %(qname)s:' % locals()
raise ScancodeError(msg + '\n' + traceback.format_exc())
# NOTE: these are list of plugin instances, not classes!
pre_scan_plugins = enabled_plugins_by_stage[pre_scan.stage]
scanner_plugins = enabled_plugins_by_stage[scan.stage]
post_scan_plugins = enabled_plugins_by_stage[post_scan.stage]
output_filter_plugins = enabled_plugins_by_stage[output_filter.stage]
output_plugins = enabled_plugins_by_stage[output.stage]
if from_json and scanner_plugins:
msg = ('Data loaded from JSON: no scan options can be selected.')
raise ScancodeCliUsageError(msg)
if not output_plugins and not return_results:
msg = ('Missing output option(s): at least one output '
'option is required to save scan results.')
raise ScancodeCliUsageError(msg)
########################################################################
# Get required and enabled plugins instance so we can run their setup
########################################################################
plugins_to_setup = []
requestors_by_missing_qname = defaultdict(set)
if TRACE_DEEP:
logger_debug('scancode: all_enabled_plugins_by_qname:', all_enabled_plugins_by_qname)
logger_debug('scancode: non_enabled_plugins_by_qname:', non_enabled_plugins_by_qname)
for qname, enabled_plugin in all_enabled_plugins_by_qname.items():
for required_qname in enabled_plugin.required_plugins or []:
if required_qname in all_enabled_plugins_by_qname:
# there is nothing to do since we have it already as enabled
pass
elif required_qname in non_enabled_plugins_by_qname:
plugins_to_setup.append(non_enabled_plugins_by_qname[required_qname])
else:
# we have a required but not loaded plugin
requestors_by_missing_qname[required_qname].add(qname)
if requestors_by_missing_qname:
msg = 'Some required plugins are missing from available plugins:\n'
for qn, requestors in requestors_by_missing_qname.items():
rqs = ', '.join(sorted(requestors))
msg += ' Plugin: {qn} is required by plugins: {rqs}.\n'.format(**locals())
raise ScancodeError(msg)
if TRACE_DEEP:
logger_debug('scancode: plugins_to_setup: from required:', plugins_to_setup)
plugins_to_setup.extend(all_enabled_plugins_by_qname.values())
if TRACE_DEEP:
logger_debug('scancode: plugins_to_setup: includng enabled:', plugins_to_setup)
########################################################################
# Setup enabled and required plugins
########################################################################
setup_timings = OrderedDict()
plugins_setup_start = time()
if not quiet and not verbose:
echo_func('Setup plugins...', fg='green')
# TODO: add progress indicator
for plugin in plugins_to_setup:
plugin_setup_start = time()
stage = plugin.stage
name = plugin.name
if verbose:
echo_func(' Setup plugin: %(stage)s:%(name)s...' % locals(),
fg='green')
try:
plugin.setup(**kwargs)
except:
msg = 'ERROR: failed to setup plugin: %(stage)s:%(name)s:' % locals()
raise ScancodeError(msg + '\n' + traceback.format_exc())
timing_key = 'setup_%(stage)s:%(name)s' % locals()
setup_timings[timing_key] = time() - plugin_setup_start
setup_timings['setup'] = time() - plugins_setup_start
########################################################################
# Collect Resource attributes requested for this scan
########################################################################
# Craft a new Resource class with the attributes contributed by plugins
sortable_resource_attributes = []
# mapping of {"plugin stage:name": [list of attribute keys]}
# also available as a kwarg entry for plugin
kwargs['resource_attributes_by_plugin'] = resource_attributes_by_plugin = {}
for stage, stage_plugins in enabled_plugins_by_stage.items():
for plugin in stage_plugins:
name = plugin.name
try:
sortable_resource_attributes.append(
(plugin.sort_order, name, plugin.resource_attributes,)
)
resource_attributes_by_plugin[plugin.qname()] = plugin.resource_attributes.keys()
except:
msg = ('ERROR: failed to collect resource_attributes for plugin: '
'%(stage)s:%(name)s:' % locals())
raise ScancodeError(msg + '\n' + traceback.format_exc())
resource_attributes = OrderedDict()
for _, name, attribs in sorted(sortable_resource_attributes):
resource_attributes.update(attribs)
# FIXME: workaround for https://github.com/python-attrs/attrs/issues/339
# we reset the _CountingAttribute internal ".counter" to a proper value
# that matches our ordering
for order, attrib in enumerate(resource_attributes.values(), 100):
attrib.counter = order
if TRACE_DEEP:
logger_debug('scancode:resource_attributes')
for a in resource_attributes.items():
logger_debug(a)
########################################################################
# Collect Codebase attributes requested for this run
########################################################################
sortable_codebase_attributes = []
# mapping of {"plugin stage:name": [list of attribute keys]}
# also available as a kwarg entry for plugin
kwargs['codebase_attributes_by_plugin'] = codebase_attributes_by_plugin = {}
for stage, stage_plugins in enabled_plugins_by_stage.items():
for plugin in stage_plugins:
name = plugin.name
try:
sortable_codebase_attributes.append(
(plugin.sort_order, name, plugin.codebase_attributes,)
)
codebase_attributes_by_plugin[plugin.qname()] = plugin.codebase_attributes.keys()
except:
msg = ('ERROR: failed to collect codebase_attributes for plugin: '
'%(stage)s:%(name)s:' % locals())
raise ScancodeError(msg + '\n' + traceback.format_exc())
codebase_attributes = OrderedDict()
for _, name, attribs in sorted(sortable_codebase_attributes):
codebase_attributes.update(attribs)
# FIXME: workaround for https://github.com/python-attrs/attrs/issues/339
# we reset the _CountingAttribute internal ".counter" to a proper value
# that matches our ordering
for order, attrib in enumerate(codebase_attributes.values(), 100):
attrib.counter = order
if TRACE_DEEP:
logger_debug('scancode:codebase_attributes')
for a in codebase_attributes.items():
logger_debug(a)
########################################################################
# Collect codebase inventory
########################################################################
inventory_start = time()
if not quiet:
echo_func('Collect file inventory...', fg='green')
if from_json:
codebase_class = VirtualCodebase
codebase_load_error_msg = 'ERROR: failed to load codebase from scan file at: %(input)r'
else:
codebase_class = Codebase
codebase_load_error_msg = 'ERROR: failed to collect codebase at: %(input)r'
# TODO: add progress indicator
# Note: inventory timing collection is built in Codebase initialization
# TODO: this should also collect the basic size/dates
try:
codebase = codebase_class(
location=input,
resource_attributes=resource_attributes,
codebase_attributes=codebase_attributes,
full_root=full_root,
strip_root=strip_root,
max_in_memory=max_in_memory
)
except:
msg = 'ERROR: failed to collect codebase at: %(input)r' % locals()
raise ScancodeError(msg + '\n' + traceback.format_exc())
# update headers
cle = codebase.get_or_create_current_header()
cle.start_timestamp = start_timestamp
cle.tool_name = 'scancode-toolkit'
cle.tool_version = scancode_version
cle.notice = notice
cle.options = pretty_params or {}
# TODO: this is weird: may be the timings should NOT be stored on the
# codebase, since they exist in abstract of it??
codebase.timings.update(setup_timings)
codebase.timings['inventory'] = time() - inventory_start
files_count, dirs_count, size_count = codebase.compute_counts()
codebase.counters['initial:files_count'] = files_count
codebase.counters['initial:dirs_count'] = dirs_count
codebase.counters['initial:size_count'] = size_count
########################################################################
# Run prescans
########################################################################
# TODO: add progress indicator
pre_scan_success = run_codebase_plugins(
stage='pre-scan', plugins=pre_scan_plugins, codebase=codebase,
stage_msg='Run %(stage)ss...',
plugin_msg=' Run %(stage)s: %(name)s...',
quiet=quiet, verbose=verbose, kwargs=kwargs, echo_func=echo_func,
)
success = success and pre_scan_success
########################################################################
# 6. run scans.
########################################################################
scan_success = run_scanners(
stage='scan', plugins=scanner_plugins, codebase=codebase,
processes=processes, timeout=timeout, timing=timeout,
quiet=quiet, verbose=verbose, kwargs=kwargs, echo_func=echo_func,
)
success = success and scan_success
########################################################################
# 7. run postscans
########################################################################
# TODO: add progress indicator
post_scan_success = run_codebase_plugins(
stage='post-scan', plugins=post_scan_plugins, codebase=codebase,
stage_msg='Run %(stage)ss...', plugin_msg=' Run %(stage)s: %(name)s...',
quiet=quiet, verbose=verbose, kwargs=kwargs, echo_func=echo_func,
)
success = success and post_scan_success
########################################################################
# 8. apply output filters
########################################################################
# TODO: add progress indicator
output_filter_success = run_codebase_plugins(
stage='output-filter', plugins=output_filter_plugins, codebase=codebase,
stage_msg='Apply %(stage)ss...', plugin_msg=' Apply %(stage)s: %(name)s...',
quiet=quiet, verbose=verbose, kwargs=kwargs, echo_func=echo_func,
)
success = success and output_filter_success
########################################################################
# 9. save outputs
########################################################################
counts = codebase.compute_counts(skip_root=strip_root, skip_filtered=True)
files_count, dirs_count, size_count = counts
codebase.counters['final:files_count'] = files_count
codebase.counters['final:dirs_count'] = dirs_count
codebase.counters['final:size_count'] = size_count
cle.end_timestamp = time2tstamp()
# collect these once as they are use in the headers and in the displayed summary
errors = collect_errors(codebase, verbose)
cle.errors = errors
# when called from Python we can only get results back and not have
# any output plugin
if output_plugins:
# TODO: add progress indicator
output_success = run_codebase_plugins(
stage='output', plugins=output_plugins, codebase=codebase,
stage_msg='Save scan results...',
plugin_msg=' Save scan results as: %(name)s...',
quiet=quiet, verbose=verbose, kwargs=kwargs, echo_func=echo_func,
)
success = success and output_success
########################################################################
# 9. display summary
########################################################################
codebase.timings['total'] = time() - processing_start
# TODO: compute summary for output plugins too??
if not quiet:
scan_names = ', '.join(p.name for p in scanner_plugins)
echo_func('Scanning done.', fg='green' if success else 'red')
display_summary(codebase, scan_names, processes, errors=errors,
echo_func=echo_func)
########################################################################
# 10. optionally assemble results to return
########################################################################
if return_results:
# the structure is exactly the same as the JSON output
from formattedcode.output_json import get_results
results = get_results(codebase, as_list=True, **kwargs)
finally:
# remove temporary files
scancode_temp_dir = scancode_config.scancode_temp_dir
if keep_temp_files:
if not quiet:
msg = 'Keeping temporary files in: "{}".'.format(scancode_temp_dir)
echo_func(msg, fg='green' if success else 'red')
else:
if not quiet:
echo_func('Removing temporary files...', fg='green', nl=False)
from commoncode import fileutils
fileutils.delete(scancode_temp_dir)
if not quiet: