Skip to content

Commit 47b4cc5

Browse files
authored
Merge pull request #375 from nexB/361-remove-mappings
Remove mappings #361
2 parents 71eb1df + b03c1eb commit 47b4cc5

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

53 files changed

+699
-971
lines changed

src/attributecode/__init__.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -65,13 +65,24 @@ def __new__(self, severity, message):
6565
Error, severity, message)
6666

6767
def __repr__(self, *args, **kwargs):
68+
sev, msg = self._get_values()
69+
return 'Error(%(sev)s, %(msg)s)' % locals()
70+
71+
def __eq__(self, other):
72+
return repr(self) == repr(other)
73+
74+
def _get_values(self):
6875
sev = severities[self.severity]
6976
msg = self._clean_string(repr(self.message))
70-
return 'Error(%(sev)s, %(msg)s)' % locals()
77+
return sev, msg
78+
79+
def render(self):
80+
sev, msg = self._get_values()
81+
return '%(sev)s: %(msg)s' % locals()
7182

7283
def to_dict(self, *args, **kwargs):
7384
"""
74-
Return an ordered mapping of self.
85+
Return an ordered dict of self.
7586
"""
7687
return self._asdict()
7788

@@ -114,7 +125,3 @@ def _clean_string(s):
114125
DEBUG : 'DEBUG',
115126
NOTSET : 'NOTSET'
116127
}
117-
118-
119-
DEFAULT_MAPPING = os.path.join(os.path.abspath(
120-
os.path.dirname(__file__)), 'mapping.config')

src/attributecode/__main__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,6 @@
1919
from __future__ import unicode_literals
2020

2121

22-
if __name__ == '__main__': # pragma: nocover
22+
if __name__ == '__main__': # pragma: nocover
2323
from attributecode import cmd
24-
cmd.cli()
24+
cmd.about()

src/attributecode/attrib.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
def generate(abouts, template=None, variables=None):
4242
"""
4343
Generate an attribution text from an `abouts` list of About objects, a
44-
`template` template text and a `variables` optional mapping of extra
44+
`template` template text and a `variables` optional dict of extra
4545
variables.
4646
4747
Return a tuple of (error, attribution text) where error is an Error object
@@ -153,28 +153,25 @@ def generate_from_file(abouts, template_loc=DEFAULT_TEMPLATE_FILE, variables=Non
153153
"""
154154
Generate an attribution text from an `abouts` list of About objects, a
155155
`template_loc` template file location and a `variables` optional
156-
mapping of extra variables.
156+
dict of extra variables.
157157
158158
Return a tuple of (error, attribution text) where error is an Error object
159159
or None and attribution text is the generated text or None.
160160
"""
161-
161+
162162
template_loc = add_unc(template_loc)
163163
with io.open(template_loc, encoding='utf-8') as tplf:
164164
tpls = tplf.read()
165165
return generate(abouts, template=tpls, variables=variables)
166166

167167

168-
def generate_and_save(abouts, output_location, template_loc=None, variables=None,
169-
mapping_file=None):
168+
def generate_and_save(abouts, output_location, template_loc=None, variables=None):
170169
"""
171170
Generate an attribution text from an `abouts` list of About objects, a
172171
`template_loc` template file location and a `variables` optional
173-
mapping of extra variables. Save the generated attribution text in the
174-
`output_location` file.
172+
dict of extra variables. Save the generated attribution text in the
173+
`output_location` file.
175174
Return a list of Error objects if any.
176-
177-
Optionally use the `mapping_file` mapping config if provided.
178175
"""
179176
updated_abouts = []
180177
errors = []
@@ -200,7 +197,7 @@ def generate_and_save(abouts, output_location, template_loc=None, variables=None
200197
if rendering_error:
201198
errors.append(rendering_error)
202199

203-
if rendered:
200+
if rendered:
204201
output_location = add_unc(output_location)
205202
with io.open(output_location, 'w', encoding='utf-8') as of:
206203
of.write(rendered)

src/attributecode/cmd.py

Lines changed: 11 additions & 112 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@
3434

3535
from attributecode import __about_spec_version__
3636
from attributecode import __version__
37-
from attributecode import DEFAULT_MAPPING
3837
from attributecode import severities
3938
from attributecode.attrib import check_template
4039
from attributecode.attrib import DEFAULT_TEMPLATE_FILE
@@ -43,6 +42,7 @@
4342
from attributecode.model import collect_inventory
4443
from attributecode.model import write_output
4544
from attributecode.util import extract_zip
45+
from attributecode.util import filter_errors
4646

4747

4848
__copyright__ = """
@@ -107,7 +107,7 @@ def about():
107107

108108
def validate_key_values(ctx, param, value):
109109
"""
110-
Return the a mapping of {key: [values,...] if valid or raise a UsageError
110+
Return the a dict of {key: [values,...] if valid or raise a UsageError
111111
otherwise.
112112
"""
113113
if not value:
@@ -122,20 +122,6 @@ def validate_key_values(ctx, param, value):
122122
return kvals
123123

124124

125-
def validate_mapping(mapping, mapping_file):
126-
"""
127-
Return a mapping_file or None.
128-
Raise a UsageError on errors.
129-
"""
130-
if mapping and mapping_file:
131-
raise click.UsageError(
132-
'Invalid options combination: '
133-
'--mapping and --mapping-file are mutually exclusive.')
134-
if mapping:
135-
return DEFAULT_MAPPING
136-
return mapping_file or None
137-
138-
139125
def validate_extensions(ctx, param, value, extensions=tuple(('.csv', '.json',))):
140126
if not value:
141127
return
@@ -171,19 +157,6 @@ def validate_extensions(ctx, param, value, extensions=tuple(('.csv', '.json',)))
171157
type=click.Choice(['json', 'csv']),
172158
help='Set OUTPUT inventory file format.')
173159

174-
@click.option('--mapping',
175-
is_flag=True,
176-
help='Use the default built-in "mapping.config" file '
177-
'with mapping between input keys and .ABOUT field names.'
178-
'Cannot be combined with the --mapping-file option.')
179-
180-
@click.option('--mapping-file',
181-
metavar='FILE',
182-
type=click.Path(exists=True, dir_okay=False, readable=True, resolve_path=True),
183-
help='Path to an optional custom mapping FILE '
184-
'with mapping between input keys and .ABOUT field names. '
185-
'Cannot be combined with the --mapping option.')
186-
187160
@click.option('-q', '--quiet',
188161
is_flag=True,
189162
help='Do not print error or warning messages.')
@@ -194,8 +167,7 @@ def validate_extensions(ctx, param, value, extensions=tuple(('.csv', '.json',)))
194167

195168
@click.help_option('-h', '--help')
196169

197-
def inventory(location, output, mapping, mapping_file,
198-
format, quiet, verbose): # NOQA
170+
def inventory(location, output, format, quiet, verbose): # NOQA
199171
"""
200172
Collect the inventory of .ABOUT file data as CSV or JSON.
201173
@@ -211,29 +183,9 @@ def inventory(location, output, mapping, mapping_file,
211183
if location.lower().endswith('.zip'):
212184
# accept zipped ABOUT files as input
213185
location = extract_zip(location)
214-
215-
mapping_file = validate_mapping(mapping, mapping_file)
216-
217-
errors, abouts = collect_inventory(location, mapping_file=mapping_file)
218-
219-
# Do not write the output if one of the ABOUT files has duplicated keys
220-
# TODO: why do this check here?? Also if this is the place, we should list what the errors are.
221-
dup_error_msg = u'Duplicated keys'
222-
halt_output = False
223-
for err in errors:
224-
if dup_error_msg in err.message:
225-
halt_output = True
226-
break
227-
228-
if not halt_output:
229-
write_errors = write_output(abouts=abouts, location=output, format=format)
230-
for err in write_errors:
231-
errors.append(err)
232-
else:
233-
if not quiet:
234-
msg = u'Duplicated keys are not supported.\nPlease correct and re-run.'
235-
click.echo(msg)
236-
186+
errors, abouts = collect_inventory(location)
187+
write_errors = write_output(abouts=abouts, location=output, format=format)
188+
errors.extend(write_errors)
237189
errors_count = report_errors(errors, quiet, verbose, log_file_loc=output + '-error.log')
238190
if not quiet:
239191
msg = 'Inventory collected in {output}.'.format(**locals())
@@ -272,19 +224,6 @@ def inventory(location, output, mapping, mapping_file,
272224
type=click.Path(exists=True, file_okay=False, readable=True, resolve_path=True),
273225
help='Path to a directory with reference license data and text files.')
274226

275-
@click.option('--mapping',
276-
is_flag=True,
277-
help='Use the default built-in "mapping.config" file '
278-
'with mapping between input keys and .ABOUT field names.'
279-
'Cannot be combined with the --mapping-file option.')
280-
281-
@click.option('--mapping-file',
282-
metavar='FILE',
283-
type=click.Path(exists=True, dir_okay=False, readable=True, resolve_path=True),
284-
help='Path to an optional custom mapping FILE '
285-
'with mapping between input keys and .ABOUT field names. '
286-
'Cannot be combined with the --mapping option.')
287-
288227
@click.option('-q', '--quiet',
289228
is_flag=True,
290229
help='Do not print error or warning messages.')
@@ -295,11 +234,7 @@ def inventory(location, output, mapping, mapping_file,
295234

296235
@click.help_option('-h', '--help')
297236

298-
def gen(location, output,
299-
fetch_license,
300-
reference,
301-
mapping, mapping_file,
302-
quiet, verbose):
237+
def gen(location, output, fetch_license, reference, quiet, verbose):
303238
"""
304239
Generate .ABOUT files in OUTPUT from an inventory of .ABOUT files at LOCATION.
305240
@@ -311,8 +246,6 @@ def gen(location, output,
311246
print_version()
312247
click.echo('Generating .ABOUT files...')
313248

314-
mapping_file = validate_mapping(mapping, mapping_file)
315-
316249
if not location.endswith(('.csv', '.json',)):
317250
raise click.UsageError('ERROR: Invalid input file extension: must be one .csv or .json.')
318251

@@ -321,7 +254,6 @@ def gen(location, output,
321254
base_dir=output,
322255
reference_dir=reference,
323256
fetch_license=fetch_license,
324-
mapping_file=mapping_file
325257
)
326258

327259
errors_count = report_errors(errors, quiet, verbose, log_file_loc=output + '-error.log')
@@ -378,25 +310,6 @@ def validate_template(ctx, param, value):
378310
metavar='<key>=<value>',
379311
help='Add variable text as key=value for use in a custom attribution template.')
380312

381-
@click.option('--inventory',
382-
metavar='FILE',
383-
type=click.Path(exists=True, dir_okay=False, resolve_path=True),
384-
help='Path to an optional JSON or CSV inventory FILE listing the '
385-
'subset of .ABOUT files paths to consider when generating the attribution document.')
386-
387-
@click.option('--mapping',
388-
is_flag=True,
389-
help='Use the default built-in "mapping.config" file '
390-
'with mapping between input keys and .ABOUT field names.'
391-
'Cannot be combined with the --mapping-file option.')
392-
393-
@click.option('--mapping-file',
394-
metavar='FILE',
395-
type=click.Path(exists=True, dir_okay=False, readable=True, resolve_path=True),
396-
help='Path to an optional custom mapping FILE '
397-
'with mapping between input keys and .ABOUT field names. '
398-
'Cannot be combined with the --mapping option.')
399-
400313
@click.option('-q', '--quiet',
401314
is_flag=True,
402315
help='Do not print error or warning messages.')
@@ -407,9 +320,7 @@ def validate_template(ctx, param, value):
407320

408321
@click.help_option('-h', '--help')
409322

410-
def attrib(location, output, template, vartext,
411-
inventory, mapping, mapping_file,
412-
quiet, verbose):
323+
def attrib(location, output, template, vartext, quiet, verbose):
413324
"""
414325
Generate an attribution document at OUTPUT using .ABOUT files at LOCATION.
415326
@@ -421,20 +332,17 @@ def attrib(location, output, template, vartext,
421332
print_version()
422333
click.echo('Generating attribution...')
423334

424-
mapping_file = validate_mapping(mapping, mapping_file)
425-
426335
# accept zipped ABOUT files as input
427336
if location.lower().endswith('.zip'):
428337
location = extract_zip(location)
429338

430-
errors, abouts = collect_inventory(location, mapping_file=mapping_file)
339+
errors, abouts = collect_inventory(location)
431340

432341
attrib_errors = generate_attribution_doc(
433342
abouts=abouts,
434343
output_location=output,
435344
template_loc=template,
436345
variables=vartext,
437-
mapping_file=mapping_file,
438346
)
439347
errors.extend(attrib_errors)
440348

@@ -531,7 +439,7 @@ def print_config_help(ctx, param, value):
531439

532440
def transform(location, output, configuration, quiet, verbose): # NOQA
533441
"""
534-
Transform the CSV file at LOCATION by applying renamings, filters and checks
442+
Transform the CSV file at LOCATION by applying renamings, filters and checks
535443
and write a new CSV to OUTPUT.
536444
537445
LOCATION: Path to a CSV file.
@@ -609,23 +517,14 @@ def get_error_messages(errors, quiet=False, verbose=False):
609517
messages .append(msg)
610518
return messages, severe_errors_count
611519

612-
613-
def filter_errors(errors, minimum_severity=WARNING):
614-
"""
615-
Return a list of unique `errors` Error object filtering errors that have a
616-
severity below `minimum_severity`.
617-
"""
618-
return unique([e for e in errors if e.severity >= minimum_severity])
619-
620-
621520
######################################################################
622521
# Misc
623522
######################################################################
624523

625524
def parse_key_values(key_values):
626525
"""
627526
Given a list of "key=value" strings, return:
628-
- a mapping {key: [value, value, ...]}
527+
- a dict {key: [value, value, ...]}
629528
- a sorted list of unique error messages for invalid entries where there is
630529
a missing a key or value.
631530
"""

0 commit comments

Comments
 (0)