Skip to content

Add a validation check to raise an error if a directory is passed to the --from-json option #4035

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 12 additions & 10 deletions src/scancode/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,26 +181,28 @@ def validate_input_path(ctx, param, value):
Validate a ``value`` list of inputs path strings
"""
options = ctx.params
from_json = options.get("--from-json", False)
from_json = options.get("from_json", False)
for inp in value:
if not (is_file(location=inp, follow_symlinks=True) or is_dir(location=inp, follow_symlinks=True)):
raise click.BadParameter(f"input: {inp!r} is not a regular file or a directory")

if not is_readable(location=inp):
raise click.BadParameter(f"input: {inp!r} is not readable")

if from_json and not is_file(location=inp, follow_symlinks=True):
# extra JSON validation
raise click.BadParameter(f"JSON input: {inp!r} is not a file")
if from_json:
if is_dir(location=inp, follow_symlinks=True):
raise click.BadParameter("Error: Invalid value: Input JSON scan file(s) is not valid JSON")

if not inp.lower().endswith(".json"):
raise click.BadParameter(f"JSON input: {inp!r} is not a JSON file with a .json extension")
with open(inp) as js:
start = js.read(100).strip()
if not start.startswith("{"):
raise click.BadParameter(f"JSON input: {inp!r} is not a well formed JSON file")
raise click.BadParameter("Error: Invalid value: Input JSON scan file(s) is not valid JSON")

return value
try:
with open(inp, 'r', encoding='utf-8') as f:
json.load(f) # Try to parse the file as JSON
except (json.JSONDecodeError, UnicodeDecodeError):
raise click.BadParameter("Error: Invalid value: Input JSON scan file(s) is not valid JSON")

return value

@click.command(name='scancode',
epilog=epilog_text,
Expand Down