Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
86 changes: 86 additions & 0 deletions src/scanoss/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import pypac

from scanoss.cryptography import Cryptography, create_cryptography_config_from_args
from scanoss.delta import Delta
from scanoss.export.dependency_track import DependencyTrackExporter
from scanoss.inspection.dependency_track.project_violation import (
DependencyTrackProjectViolationPolicyCheck,
Expand Down Expand Up @@ -919,6 +920,43 @@ def setup_args() -> None: # noqa: PLR0912, PLR0915
)
p_folder_hash.set_defaults(func=folder_hash)

# Sub-command: delta
p_delta = subparsers.add_parser(
'delta',
aliases=['dl'],
description=f'SCANOSS Delta commands: {__version__}',
help='Delta support commands',
)

delta_sub = p_delta.add_subparsers(
title='Delta Commands',
dest='subparsercmd',
description='Delta sub-commands',
help='Delta sub-commands'
)

# Delta Sub-command: copy
p_copy = delta_sub.add_parser(
'copy',
aliases=['cpy'],
description=f'Copy file list into delta dir: {__version__}',
help='Copy file list into delta dir',
)
p_copy.add_argument(
'--input',
'-i',
type=str,
required=True,
help='Input file with diff list',
)
p_copy.add_argument(
'--folder',
'-f',
type=str,
help='Delta folder to copy to',
)
p_copy.set_defaults(func=delta_copy)

# Output options
for p in [
p_scan,
Expand All @@ -939,6 +977,7 @@ def setup_args() -> None: # noqa: PLR0912, PLR0915
p_crypto_hints,
p_crypto_versions_in_range,
c_licenses,
p_copy,
]:
p.add_argument('--output', '-o', type=str, help='Output result file name (optional - default stdout).')

Expand Down Expand Up @@ -1136,6 +1175,7 @@ def setup_args() -> None: # noqa: PLR0912, PLR0915
p_crypto_versions_in_range,
c_licenses,
e_dt,
p_copy
]:
p.add_argument('--debug', '-d', action='store_true', help='Enable debug messages')
p.add_argument('--trace', '-t', action='store_true', help='Enable trace messages, including API posts')
Expand Down Expand Up @@ -2603,6 +2643,52 @@ def initialise_empty_file(filename: str):
print_stderr(f'Error: Unable to create output file {filename}: {e}')
sys.exit(1)

def delta_copy(parser, args):
"""
Handle delta copy command.

Copies files listed in an input file to a target directory while preserving
their directory structure. Creates a unique delta directory if none is specified.

Parameters
----------
parser : ArgumentParser
Command line parser object for help display
args : Namespace
Parsed command line arguments containing:
- input: Path to file containing list of files to copy
- folder: Optional target directory path
- output: Optional output file path
"""
# Validate required input file parameter
if args.input is None:
print_stderr('ERROR: Input file is required for copying')
parser.parse_args([args.subparser, args.subparsercmd, '-h'])
sys.exit(1)

# Initialise output file if specified
if args.output:
initialise_empty_file(args.output)

try:
# Create and configure delta copy command
i_delta = Delta(
debug=args.debug,
trace=args.trace,
quiet=args.quiet,
filepath=args.input,
folder=args.folder,
output=args.output,
)

# Execute copy and exit with appropriate status code
status, _ = i_delta.copy()
sys.exit(status)
except Exception as e:
print_stderr(e)
if args.debug:
traceback.print_exc()
sys.exit(1)

def main():
"""
Expand Down
110 changes: 110 additions & 0 deletions src/scanoss/delta.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
"""
SPDX-License-Identifier: MIT

Copyright (c) 2025, SCANOSS

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import os
import shutil
import tempfile

from .scanossbase import ScanossBase


class Delta(ScanossBase):
"""

"""
def __init__(
self,
debug: bool = False,
trace: bool = False,
quiet: bool = False,
filepath: str = None,
folder: str = None,
output: str = None,
):
"""

"""
super().__init__(debug, trace, quiet)
self.filepath = filepath
self.folder = folder
self.output = output

def copy(self):
"""
Copy files listed in the input file to the delta directory.

Reads the input file line by line, where each line contains a file path.
Creates the delta directory if it doesn't exist, then copies each file
while preserving its directory structure.

:return: Tuple of (status_code, folder_path) where status_code is 0 for success,
1 for error, and folder_path is the delta directory path
"""
# Validate that input file exists
if not os.path.exists(self.filepath):
self.print_stderr(f'ERROR: Input file {self.filepath} does not exist')
return 1, ''

# Create delta dir (folder)
folder = self.delta_dir(self.folder)
if not folder:
self.print_stderr(f'ERROR: Input folder {self.folder} already exists')
return 1, ''
self.print_to_file_or_stdout(folder, self.output)
# Read files from filepath
with open(self.filepath, 'r') as f:
for line in f:
source_file = line.rstrip('\n')
# Skip empty lines
if not source_file:
continue
# Check if source file exists
if not os.path.exists(source_file):
self.print_stderr(f'WARNING: File {source_file} does not exist, skipping')
continue
# Copy files into delta dir
dest_path = os.path.join(folder, source_file)
os.makedirs(os.path.dirname(dest_path), exist_ok=True)
shutil.copy(source_file, dest_path)
return 0, folder

def delta_dir(self, folder):
"""
Create or validate the delta directory.

If no folder is specified, creates a unique temporary directory with
a 'delta-' prefix in the current directory. If a folder is specified,
validates that it doesn't already exist before creating it.

:param folder: Optional target directory path
:return: Path to the delta directory, or empty string if folder already exists
"""
if folder and os.path.exists(folder):
self.print_stderr(f'Folder {folder} already exists')
return ''
elif folder:
os.makedirs(folder, exist_ok=True)
else:
folder = tempfile.mkdtemp(prefix="delta-", dir='.')
return folder