Skip to content

Commit

Permalink
Fix input validation for directories and handle unreachable functions…
Browse files Browse the repository at this point in the history
… in JSON checks

Signed-off-by: Aayush Kumar <[email protected]>
  • Loading branch information
aayushkdev committed Jan 17, 2025
1 parent b0aff52 commit 8397824
Showing 1 changed file with 12 additions and 10 deletions.
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

0 comments on commit 8397824

Please sign in to comment.