Skip to main content

provenant/cli/
mod.rs

1// SPDX-FileCopyrightText: nexB Inc. and others
2// SPDX-FileCopyrightText: Provenant contributors
3// SPDX-License-Identifier: Apache-2.0
4// Derived from ScanCode Toolkit (Apache-2.0); modified. See NOTICE.
5
6mod run;
7
8pub use run::run;
9
10use clap::{ArgGroup, Args, Parser, Subcommand};
11use serde_json::{Map as JsonMap, Number as JsonNumber, Value as JsonValue};
12use std::ffi::OsString;
13use std::fs;
14#[cfg(test)]
15use std::ops::Deref;
16use std::path::{Path, PathBuf};
17use yaml_serde::Value as YamlValue;
18
19use crate::app::request::{InputMode, OutputTarget, ScanRequest};
20use crate::license_detection::DEFAULT_LICENSEDB_URL_TEMPLATE;
21use crate::output::OutputFormat;
22use crate::scanner::MemoryMode;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum ProcessMode {
26    Parallel(usize),
27    SequentialWithTimeouts,
28    SequentialWithoutTimeouts,
29}
30
31impl Default for ProcessMode {
32    fn default() -> Self {
33        let cpus = std::thread::available_parallelism().map_or(1, |n| n.get());
34        if cpus > 1 {
35            ProcessMode::Parallel(cpus - 1)
36        } else {
37            ProcessMode::Parallel(1)
38        }
39    }
40}
41
42impl ProcessMode {
43    fn default_value() -> Self {
44        let cpus = std::thread::available_parallelism().map_or(1, |n| n.get());
45        if cpus > 1 {
46            ProcessMode::Parallel(cpus - 1)
47        } else {
48            ProcessMode::Parallel(1)
49        }
50    }
51
52    pub fn to_i32(self) -> i32 {
53        match self {
54            ProcessMode::Parallel(n) => n as i32,
55            ProcessMode::SequentialWithTimeouts => 0,
56            ProcessMode::SequentialWithoutTimeouts => -1,
57        }
58    }
59}
60
61impl std::fmt::Display for ProcessMode {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        write!(f, "{}", self.to_i32())
64    }
65}
66
67fn parse_processes(value: &str) -> Result<ProcessMode, String> {
68    let parsed: i32 = value
69        .parse()
70        .map_err(|e| format!("invalid integer for --processes: {e}"))?;
71    if parsed > 0 {
72        Ok(ProcessMode::Parallel(
73            u32::try_from(parsed).unwrap() as usize
74        ))
75    } else if parsed == 0 {
76        Ok(ProcessMode::SequentialWithTimeouts)
77    } else {
78        Ok(ProcessMode::SequentialWithoutTimeouts)
79    }
80}
81
82const PDF_OXIDE_LOG_HELP: &str = "Troubleshooting PDF parser logs:\n  Provenant suppresses noisy pdf_oxide logs by default.\n  To inspect raw pdf_oxide logs for debugging, rerun with RUST_LOG=pdf_oxide=warn (or =error).";
83const CLI_ABOUT: &str = "Rust scanner for ScanCode-compatible workflows. Not affiliated with, endorsed by, or sponsored by ScanCode Toolkit, AboutCode, or nexB Inc.";
84const CLI_LONG_ABOUT: &str = "Rust scanner for ScanCode-compatible workflows.\n\nNot affiliated with, endorsed by, or sponsored by ScanCode Toolkit, AboutCode, or nexB Inc.";
85
86fn parse_license_policy_arg(value: &str) -> Result<String, String> {
87    let policy_path = Path::new(value);
88    let metadata = fs::metadata(policy_path).map_err(|err| {
89        format!(
90            "Failed to read license policy file {:?}: {err}",
91            policy_path
92        )
93    })?;
94    if !metadata.is_file() {
95        return Err(format!(
96            "License policy path {:?} is not a regular file",
97            policy_path
98        ));
99    }
100
101    let policy_text = fs::read_to_string(policy_path).map_err(|err| {
102        format!(
103            "Failed to read license policy file {:?}: {err}",
104            policy_path
105        )
106    })?;
107    if policy_text.trim().is_empty() {
108        return Err(format!("License policy file {:?} is empty", policy_path));
109    }
110
111    let policy_value: YamlValue = yaml_serde::from_str(&policy_text).map_err(|err| {
112        format!(
113            "Failed to parse license policy file {:?}: {err}",
114            policy_path
115        )
116    })?;
117    let has_license_policies = policy_value
118        .as_mapping()
119        .and_then(|mapping| mapping.get(YamlValue::String("license_policies".to_string())))
120        .is_some();
121    if !has_license_policies {
122        return Err(format!(
123            "License policy file {:?} is missing a 'license_policies' attribute",
124            policy_path
125        ));
126    }
127
128    Ok(value.to_string())
129}
130
131#[derive(Parser, Debug)]
132#[command(
133    author = "The Provenant contributors",
134    version = crate::version::BUILD_VERSION,
135    long_version = crate::version::build_long_version(),
136    after_help = PDF_OXIDE_LOG_HELP,
137    about = CLI_ABOUT,
138    long_about = CLI_LONG_ABOUT,
139    arg_required_else_help = true,
140    subcommand_required = true
141)]
142pub struct Cli {
143    #[command(subcommand)]
144    pub command: Command,
145}
146
147#[derive(Subcommand, Debug, Clone)]
148pub enum Command {
149    /// Scan files or existing ScanCode-style JSON inputs.
150    Scan(Box<ScanArgs>),
151    /// Run the long-lived HTTP service.
152    Serve(ServeArgs),
153    /// Compare ScanCode and Provenant JSON outputs to review migration-confidence deltas.
154    Compare(CompareArgs),
155    /// Show attribution notices for embedded license detection data.
156    ShowAttribution,
157    /// Export the effective built-in license dataset to DIR and exit.
158    ExportLicenseDataset(ExportLicenseDatasetArgs),
159}
160
161#[derive(Args, Debug, Clone)]
162pub struct CompareArgs {
163    /// Path to an existing ScanCode JSON output file.
164    #[arg(long = "scancode-json", value_name = "PATH")]
165    pub scancode_json: PathBuf,
166
167    /// Path to an existing Provenant JSON output file.
168    #[arg(long = "provenant-json", value_name = "PATH")]
169    pub provenant_json: PathBuf,
170
171    /// Directory where comparison artifacts should be written. Defaults to a timestamped directory in the current working directory.
172    #[arg(long = "artifact-dir", value_name = "DIR")]
173    pub artifact_dir: Option<PathBuf>,
174}
175
176#[derive(Args, Debug, Clone)]
177pub struct ExportLicenseDatasetArgs {
178    #[arg(value_name = "DIR")]
179    pub dir: String,
180}
181
182#[derive(clap::ValueEnum, Debug, Clone, Copy, PartialEq, Eq, Default)]
183pub enum CompatibilityMode {
184    #[default]
185    Native,
186    Scancode,
187}
188
189impl CompatibilityMode {
190    fn as_str(self) -> &'static str {
191        match self {
192            Self::Native => "native",
193            Self::Scancode => "scancode",
194        }
195    }
196}
197
198#[derive(Args, Debug, Clone)]
199pub struct ServeArgs {
200    /// Bind the service shell to HOST:PORT.
201    #[arg(long = "bind", value_name = "ADDR", default_value = "127.0.0.1:8080")]
202    pub bind: String,
203
204    /// Allow paths, URL, and repository inputs when bound beyond localhost.
205    #[arg(long = "allow-privileged-inputs")]
206    pub allow_privileged_inputs: bool,
207}
208
209#[derive(Args, Debug, Clone)]
210#[command(
211    group(
212        ArgGroup::new("output")
213            .required(true)
214            .multiple(true)
215            .args([
216                "output_json",
217                "output_json_pp",
218                "output_json_lines",
219                "output_yaml",
220                "output_debian",
221                "output_html",
222                "output_spdx_tv",
223                "output_spdx_rdf",
224                "output_cyclonedx",
225                "output_cyclonedx_xml",
226                "custom_output"
227            ])
228    ),
229    after_help = PDF_OXIDE_LOG_HELP
230)]
231pub struct ScanArgs {
232    /// File or directory paths to scan
233    #[arg(required = false)]
234    pub dir_path: Vec<String>,
235
236    /// Write scan output as compact JSON to FILE
237    #[arg(long = "json", value_name = "FILE", allow_hyphen_values = true)]
238    pub output_json: Option<String>,
239
240    /// Write scan output as pretty-printed JSON to FILE
241    #[arg(long = "json-pp", value_name = "FILE", allow_hyphen_values = true)]
242    pub output_json_pp: Option<String>,
243
244    /// Write scan output as JSON Lines to FILE
245    #[arg(long = "json-lines", value_name = "FILE", allow_hyphen_values = true)]
246    pub output_json_lines: Option<String>,
247
248    /// Write scan output as YAML to FILE
249    #[arg(long = "yaml", value_name = "FILE", allow_hyphen_values = true)]
250    pub output_yaml: Option<String>,
251
252    /// Write scan output in machine-readable Debian copyright format to FILE (requires --license, --copyright, and --license-text)
253    #[arg(
254        long = "debian",
255        value_name = "FILE",
256        allow_hyphen_values = true,
257        requires_all = ["copyright", "license", "license_text"]
258    )]
259    pub output_debian: Option<String>,
260
261    /// Write scan output as HTML report to FILE
262    #[arg(long = "html", value_name = "FILE", allow_hyphen_values = true)]
263    pub output_html: Option<String>,
264
265    /// Write scan output as SPDX tag/value to FILE
266    #[arg(long = "spdx-tv", value_name = "FILE", allow_hyphen_values = true)]
267    pub output_spdx_tv: Option<String>,
268
269    /// Write scan output as SPDX RDF/XML to FILE
270    #[arg(long = "spdx-rdf", value_name = "FILE", allow_hyphen_values = true)]
271    pub output_spdx_rdf: Option<String>,
272
273    /// Write scan output as CycloneDX JSON to FILE
274    #[arg(long = "cyclonedx", value_name = "FILE", allow_hyphen_values = true)]
275    pub output_cyclonedx: Option<String>,
276
277    /// Write scan output as CycloneDX XML to FILE
278    #[arg(
279        long = "cyclonedx-xml",
280        value_name = "FILE",
281        allow_hyphen_values = true
282    )]
283    pub output_cyclonedx_xml: Option<String>,
284
285    /// Write scan output to FILE formatted with the custom template
286    #[arg(
287        long = "custom-output",
288        value_name = "FILE",
289        requires = "custom_template",
290        allow_hyphen_values = true
291    )]
292    pub custom_output: Option<String>,
293
294    /// Use this template FILE with --custom-output
295    #[arg(
296        long = "custom-template",
297        value_name = "FILE",
298        requires = "custom_output"
299    )]
300    pub custom_template: Option<String>,
301
302    /// Maximum recursion depth (0 means no depth limit)
303    #[arg(short, long, default_value = "0")]
304    pub max_depth: usize,
305
306    #[arg(short = 'n', long, default_value_t = ProcessMode::default_value(), value_parser = parse_processes, allow_hyphen_values = true)]
307    pub processes: ProcessMode,
308
309    #[arg(long, default_value_t = 120.0)]
310    pub timeout: f64,
311
312    #[arg(short, long, conflicts_with = "verbose")]
313    pub quiet: bool,
314
315    #[arg(short, long, conflicts_with = "quiet")]
316    pub verbose: bool,
317
318    #[arg(long, conflicts_with = "full_root")]
319    pub strip_root: bool,
320
321    #[arg(long, conflicts_with = "strip_root")]
322    pub full_root: bool,
323
324    /// Exclude patterns (ScanCode-compatible alias: --ignore)
325    #[arg(long = "exclude", visible_alias = "ignore", value_delimiter = ',')]
326    pub exclude: Vec<String>,
327
328    /// Include files matching PATTERN. Use `**` when you want recursion across directories.
329    #[arg(long, value_delimiter = ',')]
330    pub include: Vec<String>,
331
332    /// Read selected scan paths from FILE (or '-' for stdin), relative to the explicit scan root.
333    #[arg(long = "paths-file", value_name = "FILE", allow_hyphen_values = true)]
334    pub paths_file: Vec<String>,
335
336    #[arg(long = "cache-dir", value_name = "PATH")]
337    pub cache_dir: Option<String>,
338
339    #[arg(long = "cache-clear")]
340    pub cache_clear: bool,
341
342    #[arg(long = "incremental")]
343    pub incremental: bool,
344
345    /// Trust size + mtime for incremental reuse, skipping the content re-hash of
346    /// unchanged files. Speeds up warm incremental re-scans at the cost of
347    /// missing the rare edit that keeps the same size and mtime tick. Such a miss
348    /// is not permanent: the next scan without this flag re-hashes and detects it.
349    /// Default off keeps the paranoid full-hash check so scans stay reproducible.
350    #[arg(long = "cache-trust-mtime", requires = "incremental")]
351    pub cache_trust_mtime: bool,
352
353    /// Maximum number of file and directory scan details kept in memory.
354    /// Use 0 for unlimited memory or -1 for disk-only spill during the scan.
355    #[arg(
356        long = "max-in-memory",
357        value_name = "INT",
358        default_value_t = MemoryMode::Limit(10000),
359        value_parser = parse_max_in_memory,
360        allow_hyphen_values = true
361    )]
362    pub max_in_memory: MemoryMode,
363
364    /// Collect file information such as checksums, type hints, and source/script flags.
365    #[arg(short = 'i', long)]
366    pub info: bool,
367
368    /// Load one or more existing ScanCode-style JSON scans instead of rescanning inputs.
369    #[arg(long)]
370    pub from_json: bool,
371
372    /// Scan input for application package and dependency manifests, lockfiles and related data
373    #[arg(short = 'p', long)]
374    pub package: bool,
375
376    /// Select a compatibility bundle for intentional Provenant-vs-ScanCode behavior differences.
377    #[arg(
378        long = "compat-mode",
379        visible_alias = "compat",
380        value_enum,
381        default_value_t = CompatibilityMode::Native
382    )]
383    pub compat_mode: CompatibilityMode,
384
385    /// Scan input for installed system package databases (RPM, dpkg, apk, etc.)
386    #[arg(long = "system-package")]
387    pub system_package: bool,
388
389    /// Scan supported compiled Go and Rust binaries for embedded package metadata.
390    #[arg(long = "package-in-compiled")]
391    pub package_in_compiled: bool,
392
393    /// Scan for system and application package data and skip license/copyright detection and top-level package creation.
394    #[arg(
395        long = "package-only",
396        conflicts_with_all = ["license", "summary", "package", "system_package"]
397    )]
398    pub package_only: bool,
399
400    /// Disable package assembly (merging related manifest/lockfiles into packages)
401    #[arg(long)]
402    pub no_assemble: bool,
403
404    /// Path to a custom license dataset root containing manifest.json, rules/, and licenses/.
405    /// If not specified, uses the built-in embedded license index.
406    #[arg(
407        long = "license-dataset-path",
408        value_name = "PATH",
409        requires = "license"
410    )]
411    pub license_dataset_path: Option<String>,
412
413    /// Force rebuild of the license index cache, ignoring any existing cache.
414    #[arg(long)]
415    pub reindex: bool,
416
417    /// Build the license index in memory for this run without reading or writing persistent cache files.
418    #[arg(long = "no-license-index-cache")]
419    pub no_license_index_cache: bool,
420
421    /// Include matched text in license detection output
422    #[arg(long = "license-text", requires = "license")]
423    pub license_text: bool,
424
425    #[arg(long = "license-text-diagnostics", requires = "license_text")]
426    pub license_text_diagnostics: bool,
427
428    #[arg(long = "license-diagnostics", requires = "license")]
429    pub license_diagnostics: bool,
430
431    #[arg(long = "unknown-licenses", requires = "license")]
432    pub unknown_licenses: bool,
433
434    /// Disable approximate sequence matching during `--license` detection.
435    #[arg(long = "no-sequence-matching", requires = "license")]
436    pub no_sequence_matching: bool,
437
438    #[arg(
439        long = "license-score",
440        default_value_t = 0,
441        requires = "license",
442        value_parser = clap::value_parser!(u8).range(0..=100)
443    )]
444    pub license_score: u8,
445
446    #[arg(
447        long = "license-url-template",
448        default_value = DEFAULT_LICENSEDB_URL_TEMPLATE,
449        requires = "license"
450    )]
451    pub license_url_template: String,
452
453    #[arg(long)]
454    pub filter_clues: bool,
455
456    #[arg(
457        long = "ignore-author",
458        value_name = "PATTERN",
459        help = "Ignore a file and all its findings if an author matches the regex PATTERN"
460    )]
461    pub ignore_author: Vec<String>,
462
463    #[arg(
464        long = "ignore-copyright-holder",
465        value_name = "PATTERN",
466        help = "Ignore a file and all its findings if a copyright holder matches the regex PATTERN"
467    )]
468    pub ignore_copyright_holder: Vec<String>,
469
470    #[arg(long)]
471    pub only_findings: bool,
472
473    #[arg(long, requires = "info")]
474    pub mark_source: bool,
475
476    #[arg(long)]
477    pub classify: bool,
478
479    #[arg(long, requires = "classify")]
480    pub summary: bool,
481
482    #[arg(long = "license-clarity-score", requires = "classify")]
483    pub license_clarity_score: bool,
484
485    #[arg(long = "license-references", requires = "license")]
486    pub license_references: bool,
487
488    /// Evaluate file license detections against a YAML license policy file.
489    #[arg(
490        long = "license-policy",
491        value_name = "FILE",
492        value_parser = parse_license_policy_arg
493    )]
494    pub license_policy: Option<String>,
495
496    #[arg(long)]
497    pub tallies: bool,
498
499    #[arg(long = "tallies-key-files", requires_all = ["tallies", "classify"])]
500    pub tallies_key_files: bool,
501
502    #[arg(long = "tallies-with-details")]
503    pub tallies_with_details: bool,
504
505    #[arg(long = "facet", value_name = "<facet>=<pattern>")]
506    pub facet: Vec<String>,
507
508    #[arg(long = "tallies-by-facet", requires_all = ["facet", "tallies"])]
509    pub tallies_by_facet: bool,
510
511    #[arg(long)]
512    pub generated: bool,
513
514    /// Scan input for licenses
515    #[arg(short = 'l', long)]
516    pub license: bool,
517
518    #[arg(short = 'c', long)]
519    pub copyright: bool,
520
521    /// Scan input for email addresses
522    #[arg(short = 'e', long)]
523    pub email: bool,
524
525    /// Report only up to INT emails found in a file. Use 0 for no limit.
526    #[arg(long, default_value_t = 50, requires = "email")]
527    pub max_email: usize,
528
529    /// Scan input for URLs
530    #[arg(short = 'u', long)]
531    pub url: bool,
532
533    /// Report only up to INT URLs found in a file. Use 0 for no limit.
534    #[arg(long, default_value_t = 50, requires = "url")]
535    pub max_url: usize,
536}
537
538impl Cli {
539    pub fn parse() -> Self {
540        <Self as Parser>::parse_from(rewrite_args_for_default_scan(std::env::args_os()))
541    }
542
543    pub fn try_parse_from<I, T>(itr: I) -> Result<Self, clap::Error>
544    where
545        I: IntoIterator<Item = T>,
546        T: Into<OsString>,
547    {
548        <Self as Parser>::try_parse_from(rewrite_args_for_default_scan(itr))
549    }
550
551    pub(crate) fn scan_args(&self) -> Option<&ScanArgs> {
552        match &self.command {
553            Command::Scan(scan_args) => Some(scan_args.as_ref()),
554            Command::Serve(_)
555            | Command::Compare(_)
556            | Command::ShowAttribution
557            | Command::ExportLicenseDataset(_) => None,
558        }
559    }
560}
561
562#[cfg(test)]
563impl Deref for Cli {
564    type Target = ScanArgs;
565
566    fn deref(&self) -> &Self::Target {
567        self.scan_args()
568            .expect("scan arguments are only available for the scan command")
569    }
570}
571
572fn rewrite_args_for_default_scan<I, T>(itr: I) -> Vec<OsString>
573where
574    I: IntoIterator<Item = T>,
575    T: Into<OsString>,
576{
577    let mut args: Vec<OsString> = itr.into_iter().map(Into::into).collect();
578    if args.len() <= 1 {
579        return args;
580    }
581
582    let first = args[1].to_string_lossy();
583    if matches!(
584        first.as_ref(),
585        "scan"
586            | "serve"
587            | "compare"
588            | "show-attribution"
589            | "export-license-dataset"
590            | "help"
591            | "-h"
592            | "--help"
593            | "-V"
594            | "--version"
595    ) {
596        return args;
597    }
598
599    if first.starts_with('-') || Path::new(first.as_ref()).exists() {
600        args.insert(1, OsString::from("scan"));
601    }
602
603    args
604}
605
606fn parse_max_in_memory(value: &str) -> Result<MemoryMode, String> {
607    let parsed = value
608        .parse::<i64>()
609        .map_err(|_| format!("invalid integer value: {value}"))?;
610    if parsed < -1 {
611        return Err("--max-in-memory must be -1, 0, or a positive integer".to_string());
612    }
613    match parsed {
614        -1 => Ok(MemoryMode::StreamUnlimited),
615        0 => Ok(MemoryMode::CollectFirst),
616        n if n > 0 => Ok(MemoryMode::Limit(usize::try_from(n).unwrap_or(usize::MAX))),
617        _ => Ok(MemoryMode::CollectFirst),
618    }
619}
620
621impl ScanArgs {
622    pub(crate) fn output_targets(&self) -> Vec<OutputTarget> {
623        let mut targets = Vec::new();
624
625        if let Some(file) = &self.output_json {
626            targets.push(OutputTarget {
627                format: OutputFormat::Json,
628                file: file.clone(),
629                custom_template: None,
630            });
631        }
632
633        if let Some(file) = &self.output_json_pp {
634            targets.push(OutputTarget {
635                format: OutputFormat::JsonPretty,
636                file: file.clone(),
637                custom_template: None,
638            });
639        }
640
641        if let Some(file) = &self.output_json_lines {
642            targets.push(OutputTarget {
643                format: OutputFormat::JsonLines,
644                file: file.clone(),
645                custom_template: None,
646            });
647        }
648
649        if let Some(file) = &self.output_yaml {
650            targets.push(OutputTarget {
651                format: OutputFormat::Yaml,
652                file: file.clone(),
653                custom_template: None,
654            });
655        }
656
657        if let Some(file) = &self.output_debian {
658            targets.push(OutputTarget {
659                format: OutputFormat::Debian,
660                file: file.clone(),
661                custom_template: None,
662            });
663        }
664
665        if let Some(file) = &self.output_html {
666            targets.push(OutputTarget {
667                format: OutputFormat::Html,
668                file: file.clone(),
669                custom_template: None,
670            });
671        }
672
673        if let Some(file) = &self.output_spdx_tv {
674            targets.push(OutputTarget {
675                format: OutputFormat::SpdxTv,
676                file: file.clone(),
677                custom_template: None,
678            });
679        }
680
681        if let Some(file) = &self.output_spdx_rdf {
682            targets.push(OutputTarget {
683                format: OutputFormat::SpdxRdf,
684                file: file.clone(),
685                custom_template: None,
686            });
687        }
688
689        if let Some(file) = &self.output_cyclonedx {
690            targets.push(OutputTarget {
691                format: OutputFormat::CycloneDxJson,
692                file: file.clone(),
693                custom_template: None,
694            });
695        }
696
697        if let Some(file) = &self.output_cyclonedx_xml {
698            targets.push(OutputTarget {
699                format: OutputFormat::CycloneDxXml,
700                file: file.clone(),
701                custom_template: None,
702            });
703        }
704
705        if let Some(file) = &self.custom_output {
706            targets.push(OutputTarget {
707                format: OutputFormat::CustomTemplate,
708                file: file.clone(),
709                custom_template: self.custom_template.clone(),
710            });
711        }
712
713        targets
714    }
715
716    pub(crate) fn output_header_options(&self) -> JsonMap<String, JsonValue> {
717        let mut options = JsonMap::new();
718        if !self.dir_path.is_empty() {
719            options.insert(
720                "input".to_string(),
721                JsonValue::Array(
722                    self.dir_path
723                        .iter()
724                        .cloned()
725                        .map(JsonValue::String)
726                        .collect(),
727                ),
728            );
729        }
730
731        let mut flags = Vec::new();
732
733        push_string_option(&mut flags, "--cache-dir", self.cache_dir.as_ref());
734        push_bool_option(&mut flags, "--cache-clear", self.cache_clear);
735        push_bool_option(&mut flags, "--cache-trust-mtime", self.cache_trust_mtime);
736        push_bool_option(&mut flags, "--classify", self.classify);
737        push_string_option(&mut flags, "--custom-output", self.custom_output.as_ref());
738        push_string_option(
739            &mut flags,
740            "--custom-template",
741            self.custom_template.as_ref(),
742        );
743        push_bool_option(&mut flags, "--copyright", self.copyright);
744        if self.compat_mode != CompatibilityMode::Native {
745            flags.push((
746                "--compat-mode".to_string(),
747                JsonValue::String(self.compat_mode.as_str().to_string()),
748            ));
749        }
750        push_string_option(&mut flags, "--cyclonedx", self.output_cyclonedx.as_ref());
751        push_string_option(
752            &mut flags,
753            "--cyclonedx-xml",
754            self.output_cyclonedx_xml.as_ref(),
755        );
756        push_string_option(&mut flags, "--debian", self.output_debian.as_ref());
757        push_bool_option(&mut flags, "--email", self.email);
758        push_array_option(&mut flags, "--facet", &self.facet);
759        push_bool_option(&mut flags, "--filter-clues", self.filter_clues);
760        push_bool_option(&mut flags, "--from-json", self.from_json);
761        push_bool_option(&mut flags, "--full-root", self.full_root);
762        push_bool_option(&mut flags, "--generated", self.generated);
763        push_string_option(&mut flags, "--html", self.output_html.as_ref());
764        push_array_option(&mut flags, "--ignore", &self.exclude);
765        push_array_option(&mut flags, "--ignore-author", &self.ignore_author);
766        push_array_option(
767            &mut flags,
768            "--ignore-copyright-holder",
769            &self.ignore_copyright_holder,
770        );
771        push_bool_option(&mut flags, "--incremental", self.incremental);
772        push_array_option(&mut flags, "--include", &self.include);
773        push_bool_option(&mut flags, "--info", self.info);
774        push_string_option(&mut flags, "--json", self.output_json.as_ref());
775        push_string_option(&mut flags, "--json-lines", self.output_json_lines.as_ref());
776        push_string_option(&mut flags, "--json-pp", self.output_json_pp.as_ref());
777        push_bool_option(&mut flags, "--license", self.license);
778        push_bool_option(
779            &mut flags,
780            "--license-clarity-score",
781            self.license_clarity_score,
782        );
783        push_bool_option(
784            &mut flags,
785            "--license-diagnostics",
786            self.license_diagnostics,
787        );
788        push_string_option(
789            &mut flags,
790            "--license-dataset-path",
791            self.license_dataset_path.as_ref(),
792        );
793        push_string_option(&mut flags, "--license-policy", self.license_policy.as_ref());
794        push_bool_option(
795            &mut flags,
796            "--no-license-index-cache",
797            self.no_license_index_cache,
798        );
799        push_bool_option(&mut flags, "--license-references", self.license_references);
800        push_bool_option(&mut flags, "--reindex", self.reindex);
801        push_non_default_u8_option(&mut flags, "--license-score", self.license_score, 0);
802        push_bool_option(&mut flags, "--license-text", self.license_text);
803        push_bool_option(
804            &mut flags,
805            "--license-text-diagnostics",
806            self.license_text_diagnostics,
807        );
808        push_non_default_string_option(
809            &mut flags,
810            "--license-url-template",
811            &self.license_url_template,
812            DEFAULT_LICENSEDB_URL_TEMPLATE,
813        );
814        push_non_default_usize_option(&mut flags, "--max-depth", self.max_depth, 0);
815        match self.max_in_memory {
816            MemoryMode::Limit(10000) => {}
817            MemoryMode::CollectFirst => {
818                flags.push(("--max-in-memory".to_string(), JsonValue::Number(0.into())));
819            }
820            MemoryMode::StreamUnlimited => {
821                flags.push((
822                    "--max-in-memory".to_string(),
823                    JsonValue::Number((-1i64).into()),
824                ));
825            }
826            MemoryMode::Limit(n) => {
827                flags.push(("--max-in-memory".to_string(), JsonValue::Number(n.into())));
828            }
829        }
830        if self.email {
831            push_non_default_usize_option(&mut flags, "--max-email", self.max_email, 50);
832        }
833        if self.url {
834            push_non_default_usize_option(&mut flags, "--max-url", self.max_url, 50);
835        }
836        push_bool_option(&mut flags, "--mark-source", self.mark_source);
837        push_bool_option(&mut flags, "--no-assemble", self.no_assemble);
838        push_bool_option(&mut flags, "--only-findings", self.only_findings);
839        push_bool_option(&mut flags, "--package", self.package);
840        push_bool_option(
841            &mut flags,
842            "--package-in-compiled",
843            self.package_in_compiled,
844        );
845        push_bool_option(&mut flags, "--package-only", self.package_only);
846        push_array_option(&mut flags, "--paths-file", &self.paths_file);
847        push_non_default_process_mode_option(
848            &mut flags,
849            "--processes",
850            self.processes,
851            ProcessMode::default_value(),
852        );
853        push_bool_option(&mut flags, "--quiet", self.quiet);
854        push_string_option(&mut flags, "--spdx-rdf", self.output_spdx_rdf.as_ref());
855        push_string_option(&mut flags, "--spdx-tv", self.output_spdx_tv.as_ref());
856        push_bool_option(&mut flags, "--strip-root", self.strip_root);
857        push_bool_option(&mut flags, "--summary", self.summary);
858        push_bool_option(&mut flags, "--system-package", self.system_package);
859        push_bool_option(&mut flags, "--tallies", self.tallies);
860        push_bool_option(&mut flags, "--tallies-by-facet", self.tallies_by_facet);
861        push_bool_option(&mut flags, "--tallies-key-files", self.tallies_key_files);
862        push_bool_option(
863            &mut flags,
864            "--tallies-with-details",
865            self.tallies_with_details,
866        );
867        push_non_default_f64_option(&mut flags, "--timeout", self.timeout, 120.0);
868        push_bool_option(&mut flags, "--unknown-licenses", self.unknown_licenses);
869        push_bool_option(
870            &mut flags,
871            "--no-sequence-matching",
872            self.no_sequence_matching,
873        );
874        push_bool_option(&mut flags, "--url", self.url);
875        push_bool_option(&mut flags, "--verbose", self.verbose);
876        push_string_option(&mut flags, "--yaml", self.output_yaml.as_ref());
877
878        flags.sort_by(|left, right| left.0.cmp(&right.0));
879        for (key, value) in flags {
880            options.insert(key, value);
881        }
882
883        options
884    }
885}
886
887impl From<&ScanArgs> for ScanRequest {
888    fn from(cli: &ScanArgs) -> Self {
889        Self {
890            input_paths: cli.dir_path.clone(),
891            input_mode: if cli.from_json {
892                InputMode::FromJson
893            } else {
894                InputMode::Native
895            },
896            output_targets: cli.output_targets(),
897            output_header_options: cli.output_header_options(),
898            progress_mode: if cli.quiet {
899                crate::progress::ProgressMode::Quiet
900            } else if cli.verbose {
901                crate::progress::ProgressMode::Verbose
902            } else {
903                crate::progress::ProgressMode::Default
904            },
905            process_mode: cli.processes,
906            timeout_seconds: cli.timeout,
907            quiet: cli.quiet,
908            verbose: cli.verbose,
909            strip_root: cli.strip_root,
910            full_root: cli.full_root,
911            exclude: cli.exclude.clone(),
912            include: cli.include.clone(),
913            paths_files: cli.paths_file.clone(),
914            respect_process_cache_env: true,
915            cache_dir: cli.cache_dir.clone(),
916            cache_clear: cli.cache_clear,
917            incremental: cli.incremental,
918            cache_trust_mtime: cli.cache_trust_mtime,
919            max_depth: cli.max_depth,
920            max_in_memory: cli.max_in_memory,
921            info: cli.info,
922            package: cli.package,
923            system_package: cli.system_package,
924            package_in_compiled: cli.package_in_compiled,
925            package_only: cli.package_only,
926            no_assemble: cli.no_assemble,
927            license_dataset_path: cli.license_dataset_path.clone(),
928            reindex: cli.reindex,
929            no_license_index_cache: cli.no_license_index_cache,
930            license_text: cli.license_text,
931            license_text_diagnostics: cli.license_text_diagnostics,
932            license_diagnostics: cli.license_diagnostics,
933            unknown_licenses: cli.unknown_licenses,
934            no_sequence_matching: cli.no_sequence_matching,
935            license_score: cli.license_score,
936            license_url_template: cli.license_url_template.clone(),
937            filter_clues: cli.filter_clues,
938            ignore_author: cli.ignore_author.clone(),
939            ignore_copyright_holder: cli.ignore_copyright_holder.clone(),
940            only_findings: cli.only_findings,
941            mark_source: cli.mark_source,
942            classify: cli.classify,
943            summary: cli.summary,
944            license_clarity_score: cli.license_clarity_score,
945            license_references: cli.license_references,
946            license_policy: cli.license_policy.clone(),
947            tallies: cli.tallies,
948            tallies_key_files: cli.tallies_key_files,
949            tallies_with_details: cli.tallies_with_details,
950            facet: cli.facet.clone(),
951            tallies_by_facet: cli.tallies_by_facet,
952            generated: cli.generated,
953            license: cli.license,
954            copyright: cli.copyright,
955            email: cli.email,
956            max_email: cli.max_email,
957            url: cli.url,
958            max_url: cli.max_url,
959            scan_bounds: crate::app::request::ScanBounds::default(),
960        }
961    }
962}
963
964fn push_bool_option(options: &mut Vec<(String, JsonValue)>, key: &str, enabled: bool) {
965    if enabled {
966        options.push((key.to_string(), JsonValue::Bool(true)));
967    }
968}
969
970fn push_string_option(options: &mut Vec<(String, JsonValue)>, key: &str, value: Option<&String>) {
971    if let Some(value) = value {
972        options.push((key.to_string(), JsonValue::String(value.clone())));
973    }
974}
975
976fn push_non_default_string_option(
977    options: &mut Vec<(String, JsonValue)>,
978    key: &str,
979    value: &str,
980    default: &str,
981) {
982    if value != default {
983        options.push((key.to_string(), JsonValue::String(value.to_string())));
984    }
985}
986
987fn push_array_option(options: &mut Vec<(String, JsonValue)>, key: &str, values: &[String]) {
988    if !values.is_empty() {
989        options.push((
990            key.to_string(),
991            JsonValue::Array(values.iter().cloned().map(JsonValue::String).collect()),
992        ));
993    }
994}
995
996fn push_non_default_usize_option(
997    options: &mut Vec<(String, JsonValue)>,
998    key: &str,
999    value: usize,
1000    default: usize,
1001) {
1002    if value != default {
1003        options.push((key.to_string(), JsonValue::Number(value.into())));
1004    }
1005}
1006
1007fn push_non_default_u8_option(
1008    options: &mut Vec<(String, JsonValue)>,
1009    key: &str,
1010    value: u8,
1011    default: u8,
1012) {
1013    if value != default {
1014        options.push((key.to_string(), JsonValue::Number(value.into())));
1015    }
1016}
1017
1018fn push_non_default_process_mode_option(
1019    options: &mut Vec<(String, JsonValue)>,
1020    key: &str,
1021    value: ProcessMode,
1022    default: ProcessMode,
1023) {
1024    if value != default {
1025        options.push((key.to_string(), JsonValue::Number(value.to_i32().into())));
1026    }
1027}
1028
1029fn push_non_default_f64_option(
1030    options: &mut Vec<(String, JsonValue)>,
1031    key: &str,
1032    value: f64,
1033    default: f64,
1034) {
1035    if (value - default).abs() > f64::EPSILON
1036        && let Some(number) = JsonNumber::from_f64(value)
1037    {
1038        options.push((key.to_string(), JsonValue::Number(number)));
1039    }
1040}
1041
1042#[cfg(test)]
1043mod tests;