1mod 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(Box<ScanArgs>),
151 Serve(ServeArgs),
153 Compare(CompareArgs),
155 ShowAttribution,
157 ExportLicenseDataset(ExportLicenseDatasetArgs),
159}
160
161#[derive(Args, Debug, Clone)]
162pub struct CompareArgs {
163 #[arg(long = "scancode-json", value_name = "PATH")]
165 pub scancode_json: PathBuf,
166
167 #[arg(long = "provenant-json", value_name = "PATH")]
169 pub provenant_json: PathBuf,
170
171 #[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 #[arg(long = "bind", value_name = "ADDR", default_value = "127.0.0.1:8080")]
202 pub bind: String,
203
204 #[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 #[arg(required = false)]
234 pub dir_path: Vec<String>,
235
236 #[arg(long = "json", value_name = "FILE", allow_hyphen_values = true)]
238 pub output_json: Option<String>,
239
240 #[arg(long = "json-pp", value_name = "FILE", allow_hyphen_values = true)]
242 pub output_json_pp: Option<String>,
243
244 #[arg(long = "json-lines", value_name = "FILE", allow_hyphen_values = true)]
246 pub output_json_lines: Option<String>,
247
248 #[arg(long = "yaml", value_name = "FILE", allow_hyphen_values = true)]
250 pub output_yaml: Option<String>,
251
252 #[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 #[arg(long = "html", value_name = "FILE", allow_hyphen_values = true)]
263 pub output_html: Option<String>,
264
265 #[arg(long = "spdx-tv", value_name = "FILE", allow_hyphen_values = true)]
267 pub output_spdx_tv: Option<String>,
268
269 #[arg(long = "spdx-rdf", value_name = "FILE", allow_hyphen_values = true)]
271 pub output_spdx_rdf: Option<String>,
272
273 #[arg(long = "cyclonedx", value_name = "FILE", allow_hyphen_values = true)]
275 pub output_cyclonedx: Option<String>,
276
277 #[arg(
279 long = "cyclonedx-xml",
280 value_name = "FILE",
281 allow_hyphen_values = true
282 )]
283 pub output_cyclonedx_xml: Option<String>,
284
285 #[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 #[arg(
296 long = "custom-template",
297 value_name = "FILE",
298 requires = "custom_output"
299 )]
300 pub custom_template: Option<String>,
301
302 #[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 #[arg(long = "exclude", visible_alias = "ignore", value_delimiter = ',')]
326 pub exclude: Vec<String>,
327
328 #[arg(long, value_delimiter = ',')]
330 pub include: Vec<String>,
331
332 #[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 #[arg(
348 long = "max-in-memory",
349 value_name = "INT",
350 default_value_t = MemoryMode::Limit(10000),
351 value_parser = parse_max_in_memory,
352 allow_hyphen_values = true
353 )]
354 pub max_in_memory: MemoryMode,
355
356 #[arg(short = 'i', long)]
358 pub info: bool,
359
360 #[arg(long)]
362 pub from_json: bool,
363
364 #[arg(short = 'p', long)]
366 pub package: bool,
367
368 #[arg(
370 long = "compat-mode",
371 visible_alias = "compat",
372 value_enum,
373 default_value_t = CompatibilityMode::Native
374 )]
375 pub compat_mode: CompatibilityMode,
376
377 #[arg(long = "system-package")]
379 pub system_package: bool,
380
381 #[arg(long = "package-in-compiled")]
383 pub package_in_compiled: bool,
384
385 #[arg(
387 long = "package-only",
388 conflicts_with_all = ["license", "summary", "package", "system_package"]
389 )]
390 pub package_only: bool,
391
392 #[arg(long)]
394 pub no_assemble: bool,
395
396 #[arg(
399 long = "license-dataset-path",
400 value_name = "PATH",
401 requires = "license"
402 )]
403 pub license_dataset_path: Option<String>,
404
405 #[arg(long)]
407 pub reindex: bool,
408
409 #[arg(long = "no-license-index-cache")]
411 pub no_license_index_cache: bool,
412
413 #[arg(long = "license-text", requires = "license")]
415 pub license_text: bool,
416
417 #[arg(long = "license-text-diagnostics", requires = "license_text")]
418 pub license_text_diagnostics: bool,
419
420 #[arg(long = "license-diagnostics", requires = "license")]
421 pub license_diagnostics: bool,
422
423 #[arg(long = "unknown-licenses", requires = "license")]
424 pub unknown_licenses: bool,
425
426 #[arg(long = "no-sequence-matching", requires = "license")]
428 pub no_sequence_matching: bool,
429
430 #[arg(
431 long = "license-score",
432 default_value_t = 0,
433 requires = "license",
434 value_parser = clap::value_parser!(u8).range(0..=100)
435 )]
436 pub license_score: u8,
437
438 #[arg(
439 long = "license-url-template",
440 default_value = DEFAULT_LICENSEDB_URL_TEMPLATE,
441 requires = "license"
442 )]
443 pub license_url_template: String,
444
445 #[arg(long)]
446 pub filter_clues: bool,
447
448 #[arg(
449 long = "ignore-author",
450 value_name = "PATTERN",
451 help = "Ignore a file and all its findings if an author matches the regex PATTERN"
452 )]
453 pub ignore_author: Vec<String>,
454
455 #[arg(
456 long = "ignore-copyright-holder",
457 value_name = "PATTERN",
458 help = "Ignore a file and all its findings if a copyright holder matches the regex PATTERN"
459 )]
460 pub ignore_copyright_holder: Vec<String>,
461
462 #[arg(long)]
463 pub only_findings: bool,
464
465 #[arg(long, requires = "info")]
466 pub mark_source: bool,
467
468 #[arg(long)]
469 pub classify: bool,
470
471 #[arg(long, requires = "classify")]
472 pub summary: bool,
473
474 #[arg(long = "license-clarity-score", requires = "classify")]
475 pub license_clarity_score: bool,
476
477 #[arg(long = "license-references", requires = "license")]
478 pub license_references: bool,
479
480 #[arg(
482 long = "license-policy",
483 value_name = "FILE",
484 value_parser = parse_license_policy_arg
485 )]
486 pub license_policy: Option<String>,
487
488 #[arg(long)]
489 pub tallies: bool,
490
491 #[arg(long = "tallies-key-files", requires_all = ["tallies", "classify"])]
492 pub tallies_key_files: bool,
493
494 #[arg(long = "tallies-with-details")]
495 pub tallies_with_details: bool,
496
497 #[arg(long = "facet", value_name = "<facet>=<pattern>")]
498 pub facet: Vec<String>,
499
500 #[arg(long = "tallies-by-facet", requires_all = ["facet", "tallies"])]
501 pub tallies_by_facet: bool,
502
503 #[arg(long)]
504 pub generated: bool,
505
506 #[arg(short = 'l', long)]
508 pub license: bool,
509
510 #[arg(short = 'c', long)]
511 pub copyright: bool,
512
513 #[arg(short = 'e', long)]
515 pub email: bool,
516
517 #[arg(long, default_value_t = 50, requires = "email")]
519 pub max_email: usize,
520
521 #[arg(short = 'u', long)]
523 pub url: bool,
524
525 #[arg(long, default_value_t = 50, requires = "url")]
527 pub max_url: usize,
528}
529
530impl Cli {
531 pub fn parse() -> Self {
532 <Self as Parser>::parse_from(rewrite_args_for_default_scan(std::env::args_os()))
533 }
534
535 pub fn try_parse_from<I, T>(itr: I) -> Result<Self, clap::Error>
536 where
537 I: IntoIterator<Item = T>,
538 T: Into<OsString>,
539 {
540 <Self as Parser>::try_parse_from(rewrite_args_for_default_scan(itr))
541 }
542
543 pub(crate) fn scan_args(&self) -> Option<&ScanArgs> {
544 match &self.command {
545 Command::Scan(scan_args) => Some(scan_args.as_ref()),
546 Command::Serve(_)
547 | Command::Compare(_)
548 | Command::ShowAttribution
549 | Command::ExportLicenseDataset(_) => None,
550 }
551 }
552}
553
554#[cfg(test)]
555impl Deref for Cli {
556 type Target = ScanArgs;
557
558 fn deref(&self) -> &Self::Target {
559 self.scan_args()
560 .expect("scan arguments are only available for the scan command")
561 }
562}
563
564fn rewrite_args_for_default_scan<I, T>(itr: I) -> Vec<OsString>
565where
566 I: IntoIterator<Item = T>,
567 T: Into<OsString>,
568{
569 let mut args: Vec<OsString> = itr.into_iter().map(Into::into).collect();
570 if args.len() <= 1 {
571 return args;
572 }
573
574 let first = args[1].to_string_lossy();
575 if matches!(
576 first.as_ref(),
577 "scan"
578 | "serve"
579 | "compare"
580 | "show-attribution"
581 | "export-license-dataset"
582 | "help"
583 | "-h"
584 | "--help"
585 | "-V"
586 | "--version"
587 ) {
588 return args;
589 }
590
591 if first.starts_with('-') || Path::new(first.as_ref()).exists() {
592 args.insert(1, OsString::from("scan"));
593 }
594
595 args
596}
597
598fn parse_max_in_memory(value: &str) -> Result<MemoryMode, String> {
599 let parsed = value
600 .parse::<i64>()
601 .map_err(|_| format!("invalid integer value: {value}"))?;
602 if parsed < -1 {
603 return Err("--max-in-memory must be -1, 0, or a positive integer".to_string());
604 }
605 match parsed {
606 -1 => Ok(MemoryMode::StreamUnlimited),
607 0 => Ok(MemoryMode::CollectFirst),
608 n if n > 0 => Ok(MemoryMode::Limit(usize::try_from(n).unwrap_or(usize::MAX))),
609 _ => Ok(MemoryMode::CollectFirst),
610 }
611}
612
613impl ScanArgs {
614 pub(crate) fn output_targets(&self) -> Vec<OutputTarget> {
615 let mut targets = Vec::new();
616
617 if let Some(file) = &self.output_json {
618 targets.push(OutputTarget {
619 format: OutputFormat::Json,
620 file: file.clone(),
621 custom_template: None,
622 });
623 }
624
625 if let Some(file) = &self.output_json_pp {
626 targets.push(OutputTarget {
627 format: OutputFormat::JsonPretty,
628 file: file.clone(),
629 custom_template: None,
630 });
631 }
632
633 if let Some(file) = &self.output_json_lines {
634 targets.push(OutputTarget {
635 format: OutputFormat::JsonLines,
636 file: file.clone(),
637 custom_template: None,
638 });
639 }
640
641 if let Some(file) = &self.output_yaml {
642 targets.push(OutputTarget {
643 format: OutputFormat::Yaml,
644 file: file.clone(),
645 custom_template: None,
646 });
647 }
648
649 if let Some(file) = &self.output_debian {
650 targets.push(OutputTarget {
651 format: OutputFormat::Debian,
652 file: file.clone(),
653 custom_template: None,
654 });
655 }
656
657 if let Some(file) = &self.output_html {
658 targets.push(OutputTarget {
659 format: OutputFormat::Html,
660 file: file.clone(),
661 custom_template: None,
662 });
663 }
664
665 if let Some(file) = &self.output_spdx_tv {
666 targets.push(OutputTarget {
667 format: OutputFormat::SpdxTv,
668 file: file.clone(),
669 custom_template: None,
670 });
671 }
672
673 if let Some(file) = &self.output_spdx_rdf {
674 targets.push(OutputTarget {
675 format: OutputFormat::SpdxRdf,
676 file: file.clone(),
677 custom_template: None,
678 });
679 }
680
681 if let Some(file) = &self.output_cyclonedx {
682 targets.push(OutputTarget {
683 format: OutputFormat::CycloneDxJson,
684 file: file.clone(),
685 custom_template: None,
686 });
687 }
688
689 if let Some(file) = &self.output_cyclonedx_xml {
690 targets.push(OutputTarget {
691 format: OutputFormat::CycloneDxXml,
692 file: file.clone(),
693 custom_template: None,
694 });
695 }
696
697 if let Some(file) = &self.custom_output {
698 targets.push(OutputTarget {
699 format: OutputFormat::CustomTemplate,
700 file: file.clone(),
701 custom_template: self.custom_template.clone(),
702 });
703 }
704
705 targets
706 }
707
708 pub(crate) fn output_header_options(&self) -> JsonMap<String, JsonValue> {
709 let mut options = JsonMap::new();
710 if !self.dir_path.is_empty() {
711 options.insert(
712 "input".to_string(),
713 JsonValue::Array(
714 self.dir_path
715 .iter()
716 .cloned()
717 .map(JsonValue::String)
718 .collect(),
719 ),
720 );
721 }
722
723 let mut flags = Vec::new();
724
725 push_string_option(&mut flags, "--cache-dir", self.cache_dir.as_ref());
726 push_bool_option(&mut flags, "--cache-clear", self.cache_clear);
727 push_bool_option(&mut flags, "--classify", self.classify);
728 push_string_option(&mut flags, "--custom-output", self.custom_output.as_ref());
729 push_string_option(
730 &mut flags,
731 "--custom-template",
732 self.custom_template.as_ref(),
733 );
734 push_bool_option(&mut flags, "--copyright", self.copyright);
735 if self.compat_mode != CompatibilityMode::Native {
736 flags.push((
737 "--compat-mode".to_string(),
738 JsonValue::String(self.compat_mode.as_str().to_string()),
739 ));
740 }
741 push_string_option(&mut flags, "--cyclonedx", self.output_cyclonedx.as_ref());
742 push_string_option(
743 &mut flags,
744 "--cyclonedx-xml",
745 self.output_cyclonedx_xml.as_ref(),
746 );
747 push_string_option(&mut flags, "--debian", self.output_debian.as_ref());
748 push_bool_option(&mut flags, "--email", self.email);
749 push_array_option(&mut flags, "--facet", &self.facet);
750 push_bool_option(&mut flags, "--filter-clues", self.filter_clues);
751 push_bool_option(&mut flags, "--from-json", self.from_json);
752 push_bool_option(&mut flags, "--full-root", self.full_root);
753 push_bool_option(&mut flags, "--generated", self.generated);
754 push_string_option(&mut flags, "--html", self.output_html.as_ref());
755 push_array_option(&mut flags, "--ignore", &self.exclude);
756 push_array_option(&mut flags, "--ignore-author", &self.ignore_author);
757 push_array_option(
758 &mut flags,
759 "--ignore-copyright-holder",
760 &self.ignore_copyright_holder,
761 );
762 push_bool_option(&mut flags, "--incremental", self.incremental);
763 push_array_option(&mut flags, "--include", &self.include);
764 push_bool_option(&mut flags, "--info", self.info);
765 push_string_option(&mut flags, "--json", self.output_json.as_ref());
766 push_string_option(&mut flags, "--json-lines", self.output_json_lines.as_ref());
767 push_string_option(&mut flags, "--json-pp", self.output_json_pp.as_ref());
768 push_bool_option(&mut flags, "--license", self.license);
769 push_bool_option(
770 &mut flags,
771 "--license-clarity-score",
772 self.license_clarity_score,
773 );
774 push_bool_option(
775 &mut flags,
776 "--license-diagnostics",
777 self.license_diagnostics,
778 );
779 push_string_option(
780 &mut flags,
781 "--license-dataset-path",
782 self.license_dataset_path.as_ref(),
783 );
784 push_string_option(&mut flags, "--license-policy", self.license_policy.as_ref());
785 push_bool_option(
786 &mut flags,
787 "--no-license-index-cache",
788 self.no_license_index_cache,
789 );
790 push_bool_option(&mut flags, "--license-references", self.license_references);
791 push_bool_option(&mut flags, "--reindex", self.reindex);
792 push_non_default_u8_option(&mut flags, "--license-score", self.license_score, 0);
793 push_bool_option(&mut flags, "--license-text", self.license_text);
794 push_bool_option(
795 &mut flags,
796 "--license-text-diagnostics",
797 self.license_text_diagnostics,
798 );
799 push_non_default_string_option(
800 &mut flags,
801 "--license-url-template",
802 &self.license_url_template,
803 DEFAULT_LICENSEDB_URL_TEMPLATE,
804 );
805 push_non_default_usize_option(&mut flags, "--max-depth", self.max_depth, 0);
806 match self.max_in_memory {
807 MemoryMode::Limit(10000) => {}
808 MemoryMode::CollectFirst => {
809 flags.push(("--max-in-memory".to_string(), JsonValue::Number(0.into())));
810 }
811 MemoryMode::StreamUnlimited => {
812 flags.push((
813 "--max-in-memory".to_string(),
814 JsonValue::Number((-1i64).into()),
815 ));
816 }
817 MemoryMode::Limit(n) => {
818 flags.push(("--max-in-memory".to_string(), JsonValue::Number(n.into())));
819 }
820 }
821 if self.email {
822 push_non_default_usize_option(&mut flags, "--max-email", self.max_email, 50);
823 }
824 if self.url {
825 push_non_default_usize_option(&mut flags, "--max-url", self.max_url, 50);
826 }
827 push_bool_option(&mut flags, "--mark-source", self.mark_source);
828 push_bool_option(&mut flags, "--no-assemble", self.no_assemble);
829 push_bool_option(&mut flags, "--only-findings", self.only_findings);
830 push_bool_option(&mut flags, "--package", self.package);
831 push_bool_option(
832 &mut flags,
833 "--package-in-compiled",
834 self.package_in_compiled,
835 );
836 push_bool_option(&mut flags, "--package-only", self.package_only);
837 push_array_option(&mut flags, "--paths-file", &self.paths_file);
838 push_non_default_process_mode_option(
839 &mut flags,
840 "--processes",
841 self.processes,
842 ProcessMode::default_value(),
843 );
844 push_bool_option(&mut flags, "--quiet", self.quiet);
845 push_string_option(&mut flags, "--spdx-rdf", self.output_spdx_rdf.as_ref());
846 push_string_option(&mut flags, "--spdx-tv", self.output_spdx_tv.as_ref());
847 push_bool_option(&mut flags, "--strip-root", self.strip_root);
848 push_bool_option(&mut flags, "--summary", self.summary);
849 push_bool_option(&mut flags, "--system-package", self.system_package);
850 push_bool_option(&mut flags, "--tallies", self.tallies);
851 push_bool_option(&mut flags, "--tallies-by-facet", self.tallies_by_facet);
852 push_bool_option(&mut flags, "--tallies-key-files", self.tallies_key_files);
853 push_bool_option(
854 &mut flags,
855 "--tallies-with-details",
856 self.tallies_with_details,
857 );
858 push_non_default_f64_option(&mut flags, "--timeout", self.timeout, 120.0);
859 push_bool_option(&mut flags, "--unknown-licenses", self.unknown_licenses);
860 push_bool_option(
861 &mut flags,
862 "--no-sequence-matching",
863 self.no_sequence_matching,
864 );
865 push_bool_option(&mut flags, "--url", self.url);
866 push_bool_option(&mut flags, "--verbose", self.verbose);
867 push_string_option(&mut flags, "--yaml", self.output_yaml.as_ref());
868
869 flags.sort_by(|left, right| left.0.cmp(&right.0));
870 for (key, value) in flags {
871 options.insert(key, value);
872 }
873
874 options
875 }
876}
877
878impl From<&ScanArgs> for ScanRequest {
879 fn from(cli: &ScanArgs) -> Self {
880 Self {
881 input_paths: cli.dir_path.clone(),
882 input_mode: if cli.from_json {
883 InputMode::FromJson
884 } else {
885 InputMode::Native
886 },
887 output_targets: cli.output_targets(),
888 output_header_options: cli.output_header_options(),
889 progress_mode: if cli.quiet {
890 crate::progress::ProgressMode::Quiet
891 } else if cli.verbose {
892 crate::progress::ProgressMode::Verbose
893 } else {
894 crate::progress::ProgressMode::Default
895 },
896 process_mode: cli.processes,
897 timeout_seconds: cli.timeout,
898 quiet: cli.quiet,
899 verbose: cli.verbose,
900 strip_root: cli.strip_root,
901 full_root: cli.full_root,
902 exclude: cli.exclude.clone(),
903 include: cli.include.clone(),
904 paths_files: cli.paths_file.clone(),
905 respect_process_cache_env: true,
906 cache_dir: cli.cache_dir.clone(),
907 cache_clear: cli.cache_clear,
908 incremental: cli.incremental,
909 max_depth: cli.max_depth,
910 max_in_memory: cli.max_in_memory,
911 info: cli.info,
912 package: cli.package,
913 system_package: cli.system_package,
914 package_in_compiled: cli.package_in_compiled,
915 package_only: cli.package_only,
916 no_assemble: cli.no_assemble,
917 license_dataset_path: cli.license_dataset_path.clone(),
918 reindex: cli.reindex,
919 no_license_index_cache: cli.no_license_index_cache,
920 license_text: cli.license_text,
921 license_text_diagnostics: cli.license_text_diagnostics,
922 license_diagnostics: cli.license_diagnostics,
923 unknown_licenses: cli.unknown_licenses,
924 no_sequence_matching: cli.no_sequence_matching,
925 license_score: cli.license_score,
926 license_url_template: cli.license_url_template.clone(),
927 filter_clues: cli.filter_clues,
928 ignore_author: cli.ignore_author.clone(),
929 ignore_copyright_holder: cli.ignore_copyright_holder.clone(),
930 only_findings: cli.only_findings,
931 mark_source: cli.mark_source,
932 classify: cli.classify,
933 summary: cli.summary,
934 license_clarity_score: cli.license_clarity_score,
935 license_references: cli.license_references,
936 license_policy: cli.license_policy.clone(),
937 tallies: cli.tallies,
938 tallies_key_files: cli.tallies_key_files,
939 tallies_with_details: cli.tallies_with_details,
940 facet: cli.facet.clone(),
941 tallies_by_facet: cli.tallies_by_facet,
942 generated: cli.generated,
943 license: cli.license,
944 copyright: cli.copyright,
945 email: cli.email,
946 max_email: cli.max_email,
947 url: cli.url,
948 max_url: cli.max_url,
949 }
950 }
951}
952
953fn push_bool_option(options: &mut Vec<(String, JsonValue)>, key: &str, enabled: bool) {
954 if enabled {
955 options.push((key.to_string(), JsonValue::Bool(true)));
956 }
957}
958
959fn push_string_option(options: &mut Vec<(String, JsonValue)>, key: &str, value: Option<&String>) {
960 if let Some(value) = value {
961 options.push((key.to_string(), JsonValue::String(value.clone())));
962 }
963}
964
965fn push_non_default_string_option(
966 options: &mut Vec<(String, JsonValue)>,
967 key: &str,
968 value: &str,
969 default: &str,
970) {
971 if value != default {
972 options.push((key.to_string(), JsonValue::String(value.to_string())));
973 }
974}
975
976fn push_array_option(options: &mut Vec<(String, JsonValue)>, key: &str, values: &[String]) {
977 if !values.is_empty() {
978 options.push((
979 key.to_string(),
980 JsonValue::Array(values.iter().cloned().map(JsonValue::String).collect()),
981 ));
982 }
983}
984
985fn push_non_default_usize_option(
986 options: &mut Vec<(String, JsonValue)>,
987 key: &str,
988 value: usize,
989 default: usize,
990) {
991 if value != default {
992 options.push((key.to_string(), JsonValue::Number(value.into())));
993 }
994}
995
996fn push_non_default_u8_option(
997 options: &mut Vec<(String, JsonValue)>,
998 key: &str,
999 value: u8,
1000 default: u8,
1001) {
1002 if value != default {
1003 options.push((key.to_string(), JsonValue::Number(value.into())));
1004 }
1005}
1006
1007fn push_non_default_process_mode_option(
1008 options: &mut Vec<(String, JsonValue)>,
1009 key: &str,
1010 value: ProcessMode,
1011 default: ProcessMode,
1012) {
1013 if value != default {
1014 options.push((key.to_string(), JsonValue::Number(value.to_i32().into())));
1015 }
1016}
1017
1018fn push_non_default_f64_option(
1019 options: &mut Vec<(String, JsonValue)>,
1020 key: &str,
1021 value: f64,
1022 default: f64,
1023) {
1024 if (value - default).abs() > f64::EPSILON
1025 && let Some(number) = JsonNumber::from_f64(value)
1026 {
1027 options.push((key.to_string(), JsonValue::Number(number)));
1028 }
1029}
1030
1031#[cfg(test)]
1032mod tests;