-
-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathcmd.py
More file actions
1068 lines (915 loc) · 34.1 KB
/
cmd.py
File metadata and controls
1068 lines (915 loc) · 34.1 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
#!/usr/bin/env python
# -*- coding: utf8 -*-
# ============================================================================
# Copyright (c) nexB Inc. http://www.nexb.com/ - All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.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.
# ============================================================================
from attributecode.util import write_licenses
from attributecode.util import get_temp_dir
from attributecode.util import filter_errors
from attributecode.util import extract_zip
from attributecode.transform import Transformer
from attributecode.transform import write_excel
from attributecode.transform import write_json
from attributecode.transform import write_csv
from attributecode.transform import transform_excel
from attributecode.transform import transform_json
from attributecode.transform import transform_csv
from attributecode.transform import transform_data
from attributecode.model import write_output
from attributecode.model import pre_process_and_fetch_license_dict
from attributecode.model import get_copy_list
from attributecode.model import copy_redist_src
from attributecode.model import (
collect_inventory,
collect_abouts_license_expression,
collect_inventory_license_expression,
)
from attributecode.gen import generate as generate_about_files, load_inventory
from attributecode.attrib import generate_and_save as generate_attribution_doc
from attributecode.attrib import DEFAULT_LICENSE_SCORE
from attributecode.attrib import check_template
from attributecode import severities
from attributecode import __version__
from attributecode import __about_spec_version__
from attributecode.util import unique
from attributecode import WARNING
from collections import defaultdict
from functools import partial
import os
import sys
import click
# silence unicode literals warnings
click.disable_unicode_literals_warning = True
__copyright__ = """
Copyright (c) nexB Inc and others. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.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."""
prog_name = "AboutCode-toolkit"
intro = """%(prog_name)s version %(__version__)s
ABOUT spec version: %(__about_spec_version__)s
https://aboutcode.org
%(__copyright__)s
""" % locals()
def print_version():
click.echo("Running aboutcode-toolkit version " + __version__)
class AboutCommand(click.Command):
"""
An enhanced click Command working around some Click quirk.
"""
def main(self, args=None, prog_name=None, complete_var=None, standalone_mode=True, **extra):
"""
Workaround click bug https://github.com/mitsuhiko/click/issues/365
"""
return click.Command.main(
self,
args=args,
prog_name=self.name,
complete_var=complete_var,
standalone_mode=standalone_mode,
**extra,
)
# we define a main entry command with subcommands
@click.group(name="about")
@click.version_option(version=__version__, prog_name=prog_name, message=intro)
@click.help_option("-h", "--help")
def about():
"""
Generate licensing attribution and credit notices from .ABOUT files and inventories.
Read, write and collect provenance and license inventories from .ABOUT files to and from JSON or CSV files.
Use about <command> --help for help on a command.
"""
######################################################################
# option validators
######################################################################
def validate_key_values(ctx, param, value):
"""
Return the a dict of {key: value} if valid or raise a UsageError
otherwise.
"""
if not value:
return
kvals, errors = parse_key_values(value)
if errors:
ive = "\n".join(sorted(" " + x for x in errors))
msg = "Invalid {param} option(s):\n{ive}".format(**locals())
raise click.UsageError(msg)
return kvals
def validate_extensions(
ctx,
param,
value,
extensions=tuple(
(
".csv",
".json",
)
),
):
if not value:
return
if not value.endswith(extensions):
msg = " ".join(extensions)
raise click.UsageError(
"Invalid {param} file extension: must be one of: {msg}".format(**locals())
)
return value
######################################################################
# inventory subcommand
######################################################################
@about.command(
cls=AboutCommand,
short_help="Collect the inventory of .ABOUT files to a CSV/JSON/XLSX file or stdout.",
)
@click.argument(
"location",
required=True,
metavar="LOCATION",
type=click.Path(exists=True, file_okay=True, dir_okay=True, readable=True, resolve_path=True),
)
@click.argument("output", required=True, metavar="OUTPUT")
@click.option(
"--exclude",
multiple=True,
metavar="PATTERN",
help="Exclude the processing of the specified input pattern (e.g. *tests* or test/).",
)
@click.option(
"-f",
"--format",
is_flag=False,
default="csv",
show_default=True,
type=click.Choice(["json", "csv", "excel"]),
help="Set OUTPUT inventory file format.",
)
@click.option("-q", "--quiet", is_flag=True, help="Do not print error or warning messages.")
@click.option("--verbose", is_flag=True, help="Show all error and warning messages.")
@click.help_option("-h", "--help")
def inventory(location, output, exclude, format, quiet, verbose): # NOQA
"""
Collect the inventory of .ABOUT files to a CSV/JSON/XLSX file.
LOCATION: Path to an ABOUT file or a directory with ABOUT files.
OUTPUT: Path to the CSV/JSON/XLSX inventory file to create, or
using '-' to print result on screen/to stdout (Excel-formatted output
cannot be used in stdout).
"""
# We are not using type=click.Path() to validate the output location as
# it does not support `-` , which is used to print the result to stdout.
if not output == "-":
parent_dir = os.path.dirname(output)
if not os.path.exists(parent_dir):
msg = "The OUTPUT directory: {parent_dir} does not exist.".format(**locals())
msg += "\nPlease correct and re-run"
click.echo(msg)
sys.exit(1)
else:
# Check the format if output is stdout as xlsx format cannot be displayed.
if format == "excel":
msg = "Excel-formatted output cannot be used in stdout."
click.echo(msg)
sys.exit(0)
if not quiet:
print_version()
click.echo("Collecting inventory from ABOUT files...")
if location.lower().endswith(".zip"):
# accept zipped ABOUT files as input
location = extract_zip(location)
errors, abouts = collect_inventory(location, exclude)
write_output(abouts=abouts, location=output, format=format)
if output == "-":
log_file_loc = None
else:
log_file_loc = output + "-error.log"
errors_count = report_errors(errors, quiet, verbose, log_file_loc)
if not quiet and not output == "-":
msg = "Inventory collected in {output}.".format(**locals())
click.echo(msg)
sys.exit(errors_count)
######################################################################
# gen subcommand
######################################################################
@about.command(
cls=AboutCommand, short_help="Generate .ABOUT files from an inventory as CSV/JSON/XLSX."
)
@click.argument(
"location",
required=True,
metavar="LOCATION",
type=click.Path(exists=True, file_okay=True, dir_okay=True, readable=True, resolve_path=True),
)
@click.argument(
"output",
required=True,
metavar="OUTPUT",
type=click.Path(exists=True, file_okay=False, writable=True, resolve_path=True),
)
@click.option(
"--android",
is_flag=True,
help="Generate MODULE_LICENSE_XXX (XXX will be replaced by license key) and NOTICE "
"as the same design as from Android.",
)
# FIXME: the CLI UX should be improved with two separate options for API key and URL
@click.option(
"--fetch-license",
is_flag=True,
help="Fetch license data and text files from the ScanCode LicenseDB.",
)
@click.option(
"--fetch-license-djc",
nargs=2,
type=str,
metavar="api_url api_key",
help="Fetch license data and text files from a DejaCode License Library "
"API URL using the API KEY.",
)
@click.option(
"--scancode", is_flag=True, help="Indicate the input JSON file is from scancode_toolkit."
)
@click.option(
"--reference",
metavar="DIR",
type=click.Path(exists=True, file_okay=False, readable=True, resolve_path=True),
help="Path to a directory with reference license data and text files.",
)
@click.option(
"--worksheet",
metavar="name",
help='The worksheet name from the INPUT. (Default: the "active" worksheet)',
)
@click.option("-q", "--quiet", is_flag=True, help="Do not print error or warning messages.")
@click.option("--verbose", is_flag=True, help="Show all error and warning messages.")
@click.help_option("-h", "--help")
def gen(
location,
output,
android,
fetch_license,
fetch_license_djc,
scancode,
reference,
worksheet,
quiet,
verbose,
):
"""
Given a CSV/JSON/XLSX inventory, generate ABOUT files in the output location.
LOCATION: Path to a JSON/CSV/XLSX inventory file.
OUTPUT: Path to a directory where ABOUT files are generated.
"""
if not quiet:
print_version()
click.echo("Generating .ABOUT files...")
# FIXME: This should be checked in the `click`
if not location.endswith((".csv", ".json", ".xlsx")):
raise click.UsageError(
"ERROR: Invalid input file extension: must be one .csv or .json or .xlsx."
)
if worksheet and not location.endswith(".xlsx"):
raise click.UsageError("ERROR: --worksheet option only works with .xlsx input.")
errors, abouts = generate_about_files(
location=location,
base_dir=output,
android=android,
reference_dir=reference,
fetch_license=fetch_license,
fetch_license_djc=fetch_license_djc,
scancode=scancode,
worksheet=worksheet,
)
errors_count = report_errors(errors, quiet, verbose, log_file_loc=output + "-error.log")
if not quiet:
abouts_count = len(abouts)
msg = "{abouts_count} .ABOUT files generated in {output}.".format(**locals())
click.echo(msg)
sys.exit(errors_count)
######################################################################
# gen_license subcommand
######################################################################
@about.command(
cls=AboutCommand,
short_help="Fetch and save all the licenses in the license_expression field to a directory.",
)
@click.argument(
"location",
required=True,
metavar="LOCATION",
type=click.Path(exists=True, file_okay=True, dir_okay=True, readable=True, resolve_path=True),
)
@click.argument(
"output",
required=True,
metavar="OUTPUT",
type=click.Path(exists=True, file_okay=False, writable=True, resolve_path=True),
)
@click.option(
"--djc",
nargs=2,
type=str,
metavar="api_url api_key",
help="Fetch licenses from a DejaCode License Library.",
)
@click.option(
"--scancode", is_flag=True, help="Indicate the input JSON file is from scancode_toolkit."
)
@click.option(
"--worksheet",
metavar="name",
help='The worksheet name from the INPUT. (Default: the "active" worksheet)',
)
@click.option("--verbose", is_flag=True, help="Show all error and warning messages.")
@click.help_option("-h", "--help")
def gen_license(location, output, djc, scancode, worksheet, verbose):
"""
Fetch licenses (Default: ScanCode LicenseDB) in the license_expression field and save to the output location.
LOCATION: Path to a JSON/CSV/XLSX/.ABOUT file(s)
OUTPUT: Path to a directory where license files are saved.
"""
print_version()
api_url = ""
api_key = ""
errors = []
if worksheet and not location.endswith(".xlsx"):
raise click.UsageError("ERROR: --worksheet option only works with .xlsx input.")
log_file_loc = os.path.join(output, "error.log")
if location.endswith(".csv") or location.endswith(".json") or location.endswith(".xlsx"):
errors, abouts = collect_inventory_license_expression(
location=location, scancode=scancode, worksheet=worksheet
)
if errors:
severe_errors_count = report_errors(
errors, quiet=False, verbose=verbose, log_file_loc=log_file_loc
)
sys.exit(severe_errors_count)
else:
# _errors, abouts = collect_inventory(location)
errors, abouts = collect_abouts_license_expression(location)
if djc:
# Strip the ' and " for api_url, and api_key from input
api_url = djc[0].strip("'").strip('"')
api_key = djc[1].strip("'").strip('"')
click.echo("Fetching licenses...")
from_check = False
license_dict, lic_errors = pre_process_and_fetch_license_dict(
abouts, from_check, api_url, api_key, scancode
)
if lic_errors:
errors.extend(lic_errors)
# A dictionary with license file name as the key and context as the value
lic_dict_output = {}
for key in license_dict:
if not key in lic_dict_output:
lic_filename = license_dict[key][1]
lic_context = license_dict[key][2]
lic_dict_output[lic_filename] = lic_context
write_errors = write_licenses(lic_dict_output, output)
if write_errors:
errors.extend(write_errors)
severe_errors_count = report_errors(
errors, quiet=False, verbose=verbose, log_file_loc=log_file_loc
)
sys.exit(severe_errors_count)
######################################################################
# attrib subcommand
######################################################################
def validate_template(ctx, param, value):
if not value:
return None
with open(value, encoding="utf-8", errors="replace") as templatef:
template_error = check_template(templatef.read())
if template_error:
lineno, message = template_error
raise click.UsageError(
'Template syntax error at line: {lineno}: "{message}"'.format(**locals())
)
return value
@about.command(
cls=AboutCommand, short_help="Generate an attribution document from JSON/CSV/XLSX/.ABOUT files."
)
@click.argument(
"input",
required=True,
metavar="INPUT",
type=click.Path(exists=True, file_okay=True, dir_okay=True, readable=True, resolve_path=True),
)
@click.argument(
"output",
required=True,
metavar="OUTPUT",
type=click.Path(exists=False, dir_okay=False, writable=True, resolve_path=True),
)
@click.option(
"--api_url", nargs=1, type=click.STRING, metavar="URL", help="URL to DejaCode License Library."
)
@click.option(
"--api_key",
nargs=1,
type=click.STRING,
metavar="KEY",
help="API Key for the DejaCode License Library",
)
@click.option(
"--min-license-score",
type=int,
help="Attribute components that have license score higher than or equal to the defined "
"--min-license-score.",
)
@click.option(
"--scancode", is_flag=True, help="Indicate the input JSON file is from scancode_toolkit."
)
@click.option(
"--reference",
metavar="DIR",
type=click.Path(exists=True, file_okay=False, readable=True, resolve_path=True),
help='Path to a directory with reference files where "license_file" and/or "notice_file"'
" located.",
)
@click.option(
"--template",
metavar="FILE",
callback=validate_template,
type=click.Path(exists=True, dir_okay=False, readable=True, resolve_path=True),
help="Path to an optional custom attribution template to generate the "
"attribution document. If not provided the default built-in template is used.",
)
@click.option(
"--vartext",
multiple=True,
callback=validate_key_values,
metavar="<key>=<value>",
help="Add variable text as key=value for use in a custom attribution template.",
)
@click.option(
"--worksheet",
metavar="name",
help='The worksheet name from the INPUT. (Default: the "active" worksheet)',
)
@click.option("-q", "--quiet", is_flag=True, help="Do not print error or warning messages.")
@click.option("--verbose", is_flag=True, help="Show all error and warning messages.")
@click.help_option("-h", "--help")
def attrib(
input,
output,
api_url,
api_key,
scancode,
min_license_score,
reference,
template,
vartext,
worksheet,
quiet,
verbose,
):
"""
Generate an attribution document at OUTPUT using JSON, CSV or XLSX or .ABOUT files at INPUT.
INPUT: Path to a file (.ABOUT/.csv/.json/.xlsx), directory or .zip archive containing .ABOUT files.
OUTPUT: Path where to write the attribution document.
"""
# A variable to define if the input ABOUT file(s)
is_about_input = False
rendered = ""
license_dict = {}
errors = []
if worksheet and not input.endswith(".xlsx"):
raise click.UsageError("ERROR: --worksheet option only works with .xlsx input.")
if not quiet:
print_version()
click.echo("Generating attribution...")
# accept zipped ABOUT files as input
if input.lower().endswith(".zip"):
input = extract_zip(input)
if scancode:
if not input.endswith(".json"):
msg = "The input file from scancode toolkit needs to be in JSON format."
click.echo(msg)
sys.exit(1)
if not min_license_score and not min_license_score == 0:
min_license_score = DEFAULT_LICENSE_SCORE
if min_license_score:
if not scancode:
msg = (
"This option requires a JSON file generated by scancode toolkit as the input. "
+ 'The "--scancode" option is required.'
)
click.echo(msg)
sys.exit(1)
if input.endswith(".json") or input.endswith(".csv") or input.endswith(".xlsx"):
is_about_input = False
from_attrib = True
if not reference:
# Set current directory as the reference dir
reference = os.path.dirname(input)
# Since the errors from load_inventory is only about field formatting or
# empty field which is irrelevant for attribtion process,
# See https://github.com/nexB/aboutcode-toolkit/issues/524
# I believe we do not need to capture these errors in attrib process
errors, abouts = load_inventory(
location=input,
from_attrib=from_attrib,
scancode=scancode,
reference_dir=reference,
worksheet=worksheet,
)
# Exit if CRITICAL error
if errors:
for e in errors:
if severities[e.severity] == "CRITICAL":
click.echo(e)
sys.exit(1)
else:
is_about_input = True
_errors, abouts = collect_inventory(input)
if not abouts:
msg = "No ABOUT file or reference is found from the input. Attribution generation halted."
click.echo(msg)
errors_count = 1
sys.exit(errors_count)
if not is_about_input:
# Check if both api_url and api_key present
if api_url or api_key:
if not api_url:
msg = '"--api_url" is required.'
click.echo(msg)
sys.exit(1)
if not api_key:
msg = '"--api_key" is required.'
click.echo(msg)
sys.exit(1)
else:
api_url = ""
api_key = ""
api_url = api_url.strip("'").strip('"')
api_key = api_key.strip("'").strip('"')
from_check = False
license_dict, lic_errors = pre_process_and_fetch_license_dict(
abouts, from_check, api_url, api_key, scancode, reference
)
errors.extend(lic_errors)
sorted_license_dict = sorted(license_dict)
# Read the license_file and store in a dictionary
for about in abouts:
if about.license_file.value or about.notice_file.value:
if not reference:
msg = '"license_file" / "notice_file" field contains value. Use `--reference` to indicate its parent directory.'
click.echo(msg)
# sys.exit(1)
if abouts:
attrib_errors, rendered = generate_attribution_doc(
abouts=abouts,
is_about_input=is_about_input,
license_dict=dict(sorted(license_dict.items())),
output_location=output,
scancode=scancode,
min_license_score=min_license_score,
template_loc=template,
vartext=vartext,
)
errors.extend(attrib_errors)
errors_count = report_errors(errors, quiet, verbose, log_file_loc=output + "-error.log")
if not quiet:
if rendered:
msg = "Attribution generated in: {output}".format(**locals())
click.echo(msg)
else:
msg = "Attribution generation failed."
click.echo(msg)
sys.exit(errors_count)
######################################################################
# collect_redist_src subcommand
######################################################################
@about.command(cls=AboutCommand, short_help="Collect redistributable sources.")
@click.argument(
"location",
required=True,
metavar="LOCATION",
type=click.Path(exists=True, file_okay=True, dir_okay=True, readable=True, resolve_path=True),
)
@click.argument("output", required=True, metavar="OUTPUT")
@click.option(
"--from-inventory",
metavar="FILE",
type=click.Path(exists=True, dir_okay=False, readable=True, resolve_path=True),
help="Path to an inventory CSV/JSON/XLSX file as the base list for files/directories "
"that need to be copied which have the 'redistribute' flagged.",
)
@click.option("--with-structures", is_flag=True, help="Copy sources with directory structure.")
@click.option("--zip", is_flag=True, help="Zip the copied sources to the output location.")
@click.option("-q", "--quiet", is_flag=True, help="Do not print error or warning messages.")
@click.option("--verbose", is_flag=True, help="Show all error and warning messages.")
@click.help_option("-h", "--help")
def collect_redist_src(location, output, from_inventory, with_structures, zip, quiet, verbose):
"""
Collect sources that have 'redistribute' flagged as 'True' in .ABOUT files or inventory
to the output location.
LOCATION: Path to a directory containing sources that need to be copied
(and containing ABOUT files if `inventory` is not provided)
OUTPUT: Path to a directory or a zip file where sources will be copied to.
"""
if zip:
if not output.endswith(".zip"):
click.echo("The output needs to be a zip file.")
sys.exit()
if not quiet:
print_version()
click.echo("Collecting inventory from ABOUT files...")
if location.lower().endswith(".zip"):
# accept zipped ABOUT files as input
location = extract_zip(location)
if from_inventory:
errors, abouts = load_inventory(from_inventory, location)
else:
errors, abouts = collect_inventory(location)
if zip:
# Copy to a temp location and the zip to the output location
output_location = get_temp_dir()
else:
output_location = output
copy_list, copy_list_errors = get_copy_list(abouts, location)
copy_errors = copy_redist_src(copy_list, location, output_location, with_structures)
if zip:
import shutil
# Stripped the .zip extension as the `shutil.make_archive` will
# append the .zip extension
output_no_extension = output.rsplit(".", 1)[0]
shutil.make_archive(output_no_extension, "zip", output_location)
errors.extend(copy_list_errors)
errors.extend(copy_errors)
errors_count = report_errors(errors, quiet, verbose, log_file_loc=output + "-error.log")
if not quiet:
msg = "Redistributed sources are copied to {output}.".format(**locals())
click.echo(msg)
sys.exit(errors_count)
######################################################################
# check subcommand
######################################################################
# FIXME: This is really only a dupe of the Inventory command
@about.command(
cls=AboutCommand,
short_help="Validate that the format of .ABOUT files is correct and report "
"errors and warnings.",
)
@click.argument(
"location",
required=True,
metavar="LOCATION",
type=click.Path(exists=True, file_okay=True, dir_okay=True, readable=True, resolve_path=True),
)
@click.option(
"--exclude",
multiple=True,
metavar="PATTERN",
help="Exclude the processing of the specified input pattern (e.g. *tests* or test/).",
)
@click.option("--license", is_flag=True, help="Validate the license_expression value in the input.")
@click.option(
"--djc",
nargs=2,
type=str,
metavar="api_url api_key",
help="Validate license_expression from a DejaCode License Library API URL using the API KEY.",
)
@click.option(
"--log", nargs=1, metavar="FILE", help="Path to a file to save the error messages if any."
)
@click.option("--verbose", is_flag=True, help="Show all error and warning messages.")
@click.help_option("-h", "--help")
def check(location, exclude, license, djc, log, verbose):
"""
Check .ABOUT file(s) at LOCATION for validity and print error messages.
LOCATION: Path to an ABOUT file or a directory with ABOUT files.
"""
print_version()
if log:
# Check if the error log location exist and create the parent directory if not
parent = os.path.dirname(log)
if not parent:
os.makedirs(parent)
api_url = ""
api_key = ""
if djc:
# Strip the ' and " for api_url, and api_key from input
api_url = djc[0].strip("'").strip('"')
api_key = djc[1].strip("'").strip('"')
click.echo("Checking ABOUT files...")
errors, abouts = collect_inventory(location, exclude)
# Validate license_expression
if license:
from_check = True
_key_text_dict, errs = pre_process_and_fetch_license_dict(
abouts, from_check, api_url, api_key
)
for e in errs:
errors.append(e)
severe_errors_count = report_errors(errors, quiet=False, verbose=verbose, log_file_loc=log)
sys.exit(severe_errors_count)
######################################################################
# transform subcommand
######################################################################
def print_config_help(ctx, param, value):
if not value or ctx.resilient_parsing:
return
from attributecode.transform import tranformer_config_help
click.echo(tranformer_config_help)
ctx.exit()
@about.command(
cls=AboutCommand,
short_help="Transform a CSV/JSON/XLSX by applying renamings, filters and checks.",
)
@click.argument(
"location",
required=True,
callback=partial(
validate_extensions,
extensions=(
".csv",
".json",
".xlsx",
),
),
metavar="LOCATION",
type=click.Path(exists=True, dir_okay=False, readable=True, resolve_path=True),
)
@click.argument(
"output",
required=True,
callback=partial(
validate_extensions,
extensions=(
".csv",
".json",
".xlsx",
),
),
metavar="OUTPUT",
type=click.Path(exists=False, dir_okay=False, writable=True, resolve_path=True),
)
@click.option(
"-c",
"--configuration",
metavar="FILE",
type=click.Path(exists=True, dir_okay=False, readable=True, resolve_path=True),
help="Path to an optional YAML configuration file. See --help-format for format help.",
)
@click.option(
"--worksheet",
metavar="name",
help='The worksheet name from the INPUT. (Default: the "active" worksheet)',
)
@click.option(
"--help-format",
is_flag=True,
is_eager=True,
expose_value=False,
callback=print_config_help,
help="Show configuration file format help and exit.",
)
@click.option("-q", "--quiet", is_flag=True, help="Do not print error or warning messages.")
@click.option("--verbose", is_flag=True, help="Show all error and warning messages.")
@click.help_option("-h", "--help")
def transform(location, output, configuration, worksheet, quiet, verbose): # NOQA
"""
Transform the CSV/JSON/XLSX file at LOCATION by applying renamings, filters and checks
and then write a new CSV/JSON/XLSX to OUTPUT.
LOCATION: Path to a CSV/JSON/XLSX file.
OUTPUT: Path to CSV/JSON/XLSX inventory file to create.
"""
if worksheet and not location.endswith(".xlsx"):
raise click.UsageError("ERROR: --worksheet option only works with .xlsx input.")
if not configuration:
transformer = Transformer.default()
else:
transformer = Transformer.from_file(configuration)
if not transformer:
msg = "Cannot transform without Transformer"
click.echo(msg)
sys.exit(1)
errors = []
updated_data = []
new_data = []
if location.endswith(".csv"):
new_data, errors = transform_csv(location)
elif location.endswith(".json"):
new_data, errors = transform_json(location)
elif location.endswith(".xlsx"):
new_data, errors = transform_excel(location, worksheet)
data_keys = new_data[0].keys() if new_data else []
transformer_keys = transformer.field_renamings.keys()
dup_keys = []
for key in transformer_keys:
if key in data_keys:
dup_keys.append(key)
if dup_keys:
msg = "The following field(s) in the input data are duplicated in the transformer field renamings: {dup_keys}.\nPlease correct and re-run.".format(
**locals()
)
click.echo(msg)
sys.exit(1)
if not errors:
updated_data, errors = transform_data(new_data, transformer)
if not updated_data:
msg = "The input is empty. Nothing is transformed."
click.echo(msg)
sys.exit(0)
if not errors:
if output.endswith(".csv"):
write_csv(output, updated_data)
elif output.endswith(".json"):
write_json(output, updated_data)
else:
write_excel(output, updated_data)
if not quiet:
print_version()
click.echo("Transforming...")
errors_count = report_errors(errors, quiet, verbose, log_file_loc=output + "-error.log")
if not quiet and not errors:
msg = "Transformed file is written to {output}.".format(**locals())
click.echo(msg)
sys.exit(errors_count)
######################################################################
# Error management
######################################################################
def report_errors(errors, quiet, verbose, log_file_loc=None):
"""
Report the `errors` list of Error objects to screen based on the `quiet` and
`verbose` flags.
If `log_file_loc` file location is provided also write a verbose log to this
file.
Return True if there were severe error reported.
"""
severe_errors_count = 0
if errors:
log_msgs, severe_errors_count = get_error_messages(errors, verbose)
if not quiet:
for msg in log_msgs:
click.echo(msg)
if log_msgs and log_file_loc:
with open(log_file_loc, "w", encoding="utf-8", errors="replace") as lf:
lf.write("\n".join(log_msgs))
click.echo("Error log: " + log_file_loc)