Skip to main content

codeint_config/
cli.rs

1use std::path::{Path, PathBuf};
2
3use clap::Parser;
4
5use crate::PluginLimits;
6use crate::agent_home;
7use crate::calendar_day::CalendarDay;
8use crate::check_run_env;
9use crate::churn::{ChurnSince, ChurnWindow};
10use crate::command::{
11    AgentCommand, BaselineCommand, CheckRunConfig, Command, ConfigError, ConfigFormat,
12    DEFAULT_PLUGIN_DOWNLOAD_TIMEOUT_SECONDS, DEFAULT_PLUGIN_MAX_DOWNLOAD_BYTES, FindingsShown,
13    Invocation, MAX_PLUGIN_DOWNLOAD_MIB, PluginCommand, PluginHostConfig, RatchetCommand,
14    ReportDestination, ReportInput, ReportMode, ReportRenderFormat, SchemaFormat, StateCommand,
15    TrendFormat, TrendRange, WORST_FINDINGS_PER_METRIC,
16};
17use crate::coupling::{CouplingRatio, CouplingSettings};
18use crate::resolved::ConfigOverrides;
19use crate::result_cache_folder;
20
21mod args;
22#[cfg(test)]
23mod tests;
24
25pub(crate) use args::Arguments;
26
27use args::{
28    AgentSubcommandArguments, BaselineSubcommandArguments, CheckRunArguments, CommandArguments,
29    HistoryReportArguments, ImpactArguments, PluginSubcommandArguments, RatchetSubcommandArguments,
30    ReportArguments, StateSubcommandArguments, TraceArguments,
31};
32
33const TEST_CA_CERT_VARIABLE: &str = "CODEINT_TEST_CA_CERT";
34const PLUGIN_MAX_DOWNLOAD_MB_VARIABLE: &str = "CODEINT_PLUGIN_MAX_DOWNLOAD_MB";
35const RELEASE_BASE_URL_VARIABLE: &str = "CODEINT_RELEASE_BASE_URL";
36const PLUGIN_CACHE_SUBDIR: &str = "plugins";
37const COMPILED_PLUGIN_CACHE_SUBDIR: &str = "plugins-compiled";
38const NO_COMPILED_PLUGIN_CACHE_VARIABLE: &str = "CODEINT_NO_PLUGIN_COMPILE_CACHE";
39const BYTES_PER_MIB: u64 = 1024 * 1024;
40
41pub fn read_invocation() -> Result<Invocation, ConfigError> {
42    let arguments = Arguments::parse();
43    let current_folder = std::env::current_dir().map_err(ConfigError::CurrentFolder)?;
44    let command = build_command(&current_folder, arguments.command)?;
45    Ok(Invocation { command })
46}
47
48fn build_command(
49    current_folder: &Path,
50    arguments: CommandArguments,
51) -> Result<Command, ConfigError> {
52    match arguments {
53        CommandArguments::Check {
54            path,
55            coverage_reports,
56            ignore_baseline,
57            report,
58        } => build_check_command(
59            current_folder,
60            path,
61            CheckSelection {
62                coverage_reports,
63                ignore_baseline,
64            },
65            report,
66        ),
67        CommandArguments::Diff { target, report } => build_diff_command(
68            current_folder,
69            target.base_ref,
70            target.head_ref,
71            target.rename.rename_threshold,
72            report,
73        ),
74        CommandArguments::Trend {
75            since,
76            commits,
77            output,
78            format,
79        } => Ok(report_target(current_folder, output.output)?.into_trend(
80            resolve_trend_range(since, commits),
81            format,
82            result_cache_folder_of_this_process(current_folder),
83        )),
84        CommandArguments::Impact(mut args) => {
85            let output = args.output.output.take();
86            Ok(report_target(current_folder, output)?.into_impact(args))
87        }
88        CommandArguments::Trace(mut args) => {
89            let output = args.output.output.take();
90            Ok(report_target(current_folder, output)?.into_trace(args))
91        }
92        other => build_auxiliary_command(current_folder, other),
93    }
94}
95
96fn build_auxiliary_command(
97    current_folder: &Path,
98    arguments: CommandArguments,
99) -> Result<Command, ConfigError> {
100    match arguments {
101        CommandArguments::Init { adopt, format } => Ok(Command::Init {
102            folder: current_folder.to_path_buf(),
103            adopt,
104            format,
105            plugin_host: plugin_host_config_of_this_process(current_folder)?,
106        }),
107        CommandArguments::Update { check, version } => Ok(build_update_command(check, version)),
108        CommandArguments::Mcp => Ok(Command::Mcp {
109            result_cache: result_cache_folder_of_this_process(current_folder),
110            plugin_host: plugin_host_config_of_this_process(current_folder)?,
111            folder: current_folder.to_path_buf(),
112        }),
113        CommandArguments::Guard { path, format } => Ok(Command::Guard {
114            folder: current_folder.to_path_buf(),
115            target: path,
116            format,
117        }),
118        CommandArguments::Churn { history } => build_churn_command(current_folder, history),
119        CommandArguments::Coupling {
120            history,
121            max_commit_files,
122            min_co_changes,
123            min_ratio,
124            include_tests,
125        } => build_coupling_command(
126            current_folder,
127            history,
128            max_commit_files.get(),
129            min_co_changes.get(),
130            min_ratio,
131            include_tests,
132        ),
133        other => build_tooling_command(current_folder, other),
134    }
135}
136
137fn build_tooling_command(
138    current_folder: &Path,
139    arguments: CommandArguments,
140) -> Result<Command, ConfigError> {
141    match arguments {
142        CommandArguments::Schema { output, format } => {
143            build_schema_command(current_folder, output.output, format)
144        }
145        CommandArguments::Config {
146            path,
147            resolved: _,
148            format,
149            budgets,
150            source_sets,
151            plugin_limits,
152        } => build_config_command(
153            current_folder,
154            path,
155            format,
156            ConfigOverrides {
157                budgets,
158                source_sets,
159                plugin_memory_mb: plugin_limits.memory_mb,
160                plugin_timeout_ms: plugin_limits.timeout_ms,
161            },
162        ),
163        CommandArguments::Report {
164            input,
165            output,
166            all,
167            format,
168            check_run,
169        } => build_report_command(current_folder, input, output.output, all, format, check_run),
170        CommandArguments::Doctor { path, format } => {
171            build_doctor_command(current_folder, path, format)
172        }
173        other => build_management_command(current_folder, other),
174    }
175}
176
177fn build_management_command(
178    current_folder: &Path,
179    arguments: CommandArguments,
180) -> Result<Command, ConfigError> {
181    match arguments {
182        CommandArguments::Agent { command } => build_agent_command(current_folder, command),
183        CommandArguments::Ratchet { command } => build_ratchet_command(current_folder, command),
184        CommandArguments::Plugin { command } => build_plugin_command(current_folder, command),
185        CommandArguments::Baseline { command } => build_baseline_command(current_folder, command),
186        CommandArguments::State { command } => build_state_command(current_folder, command),
187        CommandArguments::Check { .. }
188        | CommandArguments::Diff { .. }
189        | CommandArguments::Trend { .. }
190        | CommandArguments::Impact(_)
191        | CommandArguments::Trace(_)
192        | CommandArguments::Init { .. }
193        | CommandArguments::Update { .. }
194        | CommandArguments::Mcp
195        | CommandArguments::Guard { .. }
196        | CommandArguments::Churn { .. }
197        | CommandArguments::Coupling { .. }
198        | CommandArguments::Schema { .. }
199        | CommandArguments::Config { .. }
200        | CommandArguments::Report { .. }
201        | CommandArguments::Doctor { .. } => unreachable!("handled by build_command"),
202    }
203}
204
205fn build_doctor_command(
206    current_folder: &Path,
207    path: Option<PathBuf>,
208    format: crate::command::DoctorFormat,
209) -> Result<Command, ConfigError> {
210    Ok(Command::Doctor {
211        folder: existing_folder(current_folder, path)?,
212        format,
213        plugin_host: plugin_host_config_of_this_process(current_folder)?,
214    })
215}
216
217fn build_schema_command(
218    current_folder: &Path,
219    output: Option<PathBuf>,
220    format: SchemaFormat,
221) -> Result<Command, ConfigError> {
222    Ok(Command::Schema {
223        destination: report_destination(current_folder, output)?,
224        format,
225    })
226}
227
228fn build_report_command(
229    current_folder: &Path,
230    input: PathBuf,
231    output: Option<PathBuf>,
232    all: bool,
233    format: Option<ReportRenderFormat>,
234    check_run: CheckRunArguments,
235) -> Result<Command, ConfigError> {
236    let source = if input.as_os_str() == "-" {
237        ReportInput::StandardInput
238    } else {
239        ReportInput::File(input)
240    };
241    let mode = if check_run.check_run || check_run.publish_check_run {
242        let resolved_env = check_run_env::from_process(check_run.head_sha, check_run.repository);
243        ReportMode::CheckRun(CheckRunConfig {
244            name: check_run.name,
245            base_ref: check_run.base_ref,
246            env_base_ref: resolved_env.env_base_ref,
247            head_sha: resolved_env.head_sha,
248            conclusion: check_run.conclusion,
249            max_annotations: check_run.max_annotations,
250            publish: check_run.publish_check_run.then_some(resolved_env.publish),
251        })
252    } else {
253        ReportMode::Render { all, format }
254    };
255    Ok(Command::Report {
256        folder: current_folder.to_path_buf(),
257        input: source,
258        destination: report_destination(current_folder, output)?,
259        mode,
260    })
261}
262
263fn build_config_command(
264    current_folder: &Path,
265    path: Option<PathBuf>,
266    format: ConfigFormat,
267    overrides: ConfigOverrides,
268) -> Result<Command, ConfigError> {
269    Ok(Command::Config {
270        folder: existing_folder(current_folder, path)?,
271        format,
272        overrides,
273    })
274}
275
276fn build_agent_command(
277    current_folder: &Path,
278    arguments: AgentSubcommandArguments,
279) -> Result<Command, ConfigError> {
280    match arguments {
281        AgentSubcommandArguments::Status {
282            client,
283            format,
284            config_root,
285        } => Ok(Command::Agent(AgentCommand::Status {
286            config_root: agent_home_of_this_process(current_folder, config_root.as_deref())?,
287            client,
288            format,
289        })),
290        AgentSubcommandArguments::Install {
291            dry_run,
292            client,
293            format,
294            config_root,
295        } => Ok(Command::Agent(AgentCommand::Install {
296            config_root: agent_home_of_this_process(current_folder, config_root.as_deref())?,
297            client,
298            dry_run,
299            format,
300        })),
301    }
302}
303
304fn build_plugin_command(
305    current_folder: &Path,
306    arguments: PluginSubcommandArguments,
307) -> Result<Command, ConfigError> {
308    match arguments {
309        PluginSubcommandArguments::Test {
310            path,
311            kind,
312            sources,
313            plugin_limits,
314            format,
315        } => {
316            let defaults = PluginLimits::default();
317            Ok(Command::Plugin(PluginCommand::Test {
318                plugin_host: plugin_host_config_of_this_process(current_folder)?,
319                path: current_folder.join(path),
320                kind,
321                sources: sources
322                    .into_iter()
323                    .map(|source| current_folder.join(source))
324                    .collect(),
325                limits: PluginLimits {
326                    memory_mb: plugin_limits.memory_mb.unwrap_or(defaults.memory_mb),
327                    timeout_ms: plugin_limits.timeout_ms.unwrap_or(defaults.timeout_ms),
328                },
329                format,
330            }))
331        }
332    }
333}
334
335fn build_state_update_command<F: From<args::StateUpdateFormat>>(
336    current_folder: &Path,
337    target: args::StateUpdateTargetArguments,
338    reset: bool,
339) -> Result<crate::command::StateUpdateCommand<F>, ConfigError> {
340    Ok(crate::command::StateUpdateCommand {
341        folder: existing_folder(current_folder, target.path)?,
342        reset,
343        coverage_reports: target.coverage_reports,
344        format: target.format.into(),
345        plugin_host: plugin_host_config_of_this_process(current_folder)?,
346    })
347}
348
349fn build_ratchet_command(
350    current_folder: &Path,
351    arguments: RatchetSubcommandArguments,
352) -> Result<Command, ConfigError> {
353    match arguments {
354        RatchetSubcommandArguments::Update { target, reset } => Ok(Command::Ratchet(
355            RatchetCommand::Update(build_state_update_command(current_folder, target, reset)?),
356        )),
357    }
358}
359
360fn build_baseline_command(
361    current_folder: &Path,
362    arguments: BaselineSubcommandArguments,
363) -> Result<Command, ConfigError> {
364    match arguments {
365        BaselineSubcommandArguments::Update { target, reset } => Ok(Command::Baseline(
366            BaselineCommand::Update(build_state_update_command(current_folder, target, reset)?),
367        )),
368    }
369}
370
371fn build_state_command(
372    current_folder: &Path,
373    arguments: StateSubcommandArguments,
374) -> Result<Command, ConfigError> {
375    match arguments {
376        StateSubcommandArguments::Check {
377            base_ref,
378            path,
379            head_ref,
380            rename,
381            output,
382            format,
383        } => Ok(Command::State(StateCommand::Check {
384            folder: existing_folder(current_folder, path)?,
385            base_ref,
386            head_ref,
387            rename_threshold: rename.rename_threshold,
388            destination: report_destination(current_folder, output.output)?,
389            format,
390        })),
391    }
392}
393
394fn agent_home_of_this_process(
395    current_folder: &Path,
396    explicit: Option<&Path>,
397) -> Result<PathBuf, ConfigError> {
398    agent_home::resolve_agent_home(current_folder, explicit, cfg!(windows), std::env::var_os)
399        .ok_or(ConfigError::MissingAgentHome)
400}
401
402fn resolve_trend_range(
403    since: Option<CalendarDay>,
404    commits: Option<std::num::NonZeroUsize>,
405) -> TrendRange {
406    match (since, commits) {
407        (Some(day), None) => TrendRange::Since(day),
408        (None, Some(count)) => TrendRange::Latest(count.get()),
409        _ => TrendRange::default(),
410    }
411}
412
413fn resolve_churn_window(
414    since: Option<ChurnSince>,
415    commits: Option<std::num::NonZeroUsize>,
416) -> ChurnWindow {
417    match (since, commits) {
418        (Some(since), None) => ChurnWindow::from(since),
419        (None, Some(count)) => ChurnWindow::Commits(count.get()),
420        _ => ChurnWindow::default(),
421    }
422}
423
424fn build_churn_command(
425    current_folder: &Path,
426    history: HistoryReportArguments,
427) -> Result<Command, ConfigError> {
428    Ok(Command::Churn {
429        folder: current_folder.to_path_buf(),
430        window: resolve_churn_window(history.since, history.commits),
431        destination: report_destination(current_folder, history.output.output)?,
432        findings: findings_shown(history.all),
433        format: history.format,
434        plugin_host: plugin_host_config_of_this_process(current_folder)?,
435    })
436}
437
438fn build_coupling_command(
439    current_folder: &Path,
440    history: HistoryReportArguments,
441    max_commit_files: usize,
442    min_co_changes: usize,
443    min_ratio: CouplingRatio,
444    include_tests: bool,
445) -> Result<Command, ConfigError> {
446    Ok(Command::Coupling {
447        folder: current_folder.to_path_buf(),
448        settings: CouplingSettings {
449            window: resolve_churn_window(history.since, history.commits),
450            max_commit_files,
451            min_co_changes,
452            min_ratio,
453            include_tests,
454        },
455        destination: report_destination(current_folder, history.output.output)?,
456        findings: findings_shown(history.all),
457        format: history.format,
458        plugin_host: plugin_host_config_of_this_process(current_folder)?,
459    })
460}
461
462struct CheckSelection {
463    coverage_reports: Vec<PathBuf>,
464    ignore_baseline: bool,
465}
466
467fn build_check_command(
468    current_folder: &Path,
469    path: Option<PathBuf>,
470    selection: CheckSelection,
471    report: ReportArguments,
472) -> Result<Command, ConfigError> {
473    Ok(Command::Check {
474        folder: existing_folder(current_folder, path)?,
475        destination: report_destination(current_folder, report.output.output)?,
476        findings: findings_shown(report.all),
477        format: report.format,
478        package: report.package,
479        owner: report.owner,
480        coverage_reports: selection.coverage_reports,
481        ignore_baseline: selection.ignore_baseline,
482        plugin_host: plugin_host_config_of_this_process(current_folder)?,
483    })
484}
485
486fn build_diff_command(
487    current_folder: &Path,
488    base_ref: String,
489    head_ref: Option<String>,
490    rename_threshold: u8,
491    report: ReportArguments,
492) -> Result<Command, ConfigError> {
493    Ok(Command::Diff {
494        folder: current_folder.to_path_buf(),
495        base_ref,
496        head_ref,
497        rename_threshold,
498        destination: report_destination(current_folder, report.output.output)?,
499        findings: findings_shown(report.all),
500        format: report.format,
501        package: report.package,
502        owner: report.owner,
503        result_cache: result_cache_folder_of_this_process(current_folder),
504        plugin_host: plugin_host_config_of_this_process(current_folder)?,
505    })
506}
507
508struct ReportTarget {
509    folder: PathBuf,
510    destination: ReportDestination,
511    plugin_host: PluginHostConfig,
512}
513
514impl ReportTarget {
515    fn into_trend(
516        self,
517        range: TrendRange,
518        format: Option<TrendFormat>,
519        result_cache: Option<PathBuf>,
520    ) -> Command {
521        Command::Trend {
522            folder: self.folder,
523            range,
524            destination: self.destination,
525            format,
526            result_cache,
527            plugin_host: self.plugin_host,
528        }
529    }
530
531    fn into_impact(self, args: ImpactArguments) -> Command {
532        Command::Impact {
533            folder: self.folder,
534            paths: args.paths,
535            changed: args.changed,
536            depth: args.depth,
537            package: args.package,
538            destination: self.destination,
539            format: args.format,
540            plugin_host: self.plugin_host,
541        }
542    }
543
544    fn into_trace(self, args: TraceArguments) -> Command {
545        Command::Trace {
546            folder: self.folder,
547            from: args.from,
548            to: args.to,
549            all: args.all,
550            max_paths: args.max_paths,
551            package: args.package,
552            destination: self.destination,
553            format: args.format,
554            plugin_host: self.plugin_host,
555        }
556    }
557}
558
559fn report_target(
560    current_folder: &Path,
561    output: Option<PathBuf>,
562) -> Result<ReportTarget, ConfigError> {
563    Ok(ReportTarget {
564        folder: current_folder.to_path_buf(),
565        destination: report_destination(current_folder, output)?,
566        plugin_host: plugin_host_config_of_this_process(current_folder)?,
567    })
568}
569
570fn build_update_command(check_only: bool, version: Option<String>) -> Command {
571    Command::Update {
572        check_only,
573        version,
574        release_base_url: std::env::var(RELEASE_BASE_URL_VARIABLE)
575            .ok()
576            .filter(|value| !value.is_empty()),
577    }
578}
579
580fn read_env_var(name: &str) -> Option<std::ffi::OsString> {
581    std::env::var_os(name)
582}
583
584fn result_cache_folder_of_this_process(current_folder: &Path) -> Option<PathBuf> {
585    result_cache_folder::result_cache_folder(
586        current_folder,
587        result_cache_folder::CacheFolderConvention::of_this_platform(),
588        read_env_var,
589    )
590}
591
592fn plugin_host_config_of_this_process(
593    current_folder: &Path,
594) -> Result<PluginHostConfig, ConfigError> {
595    let result_cache = result_cache_folder_of_this_process(current_folder);
596    let cache_dir = result_cache
597        .as_ref()
598        .map(|dir| dir.join(PLUGIN_CACHE_SUBDIR));
599    let compiled_plugin_cache = compiled_plugin_cache_folder(result_cache.as_deref(), read_env_var);
600    let ca_cert = std::env::var_os(TEST_CA_CERT_VARIABLE)
601        .filter(|value| !value.is_empty())
602        .map(|value| current_folder.join(value));
603    let max_download_bytes = parse_plugin_max_download_bytes(read_env_var)?;
604    Ok(PluginHostConfig {
605        cache_dir,
606        ca_cert,
607        download_timeout_seconds: DEFAULT_PLUGIN_DOWNLOAD_TIMEOUT_SECONDS,
608        max_download_bytes,
609        compiled_plugin_cache,
610    })
611}
612
613fn compiled_plugin_cache_folder(
614    result_cache: Option<&Path>,
615    lookup: impl Fn(&str) -> Option<std::ffi::OsString>,
616) -> Option<PathBuf> {
617    if lookup(NO_COMPILED_PLUGIN_CACHE_VARIABLE).is_some_and(|value| !value.is_empty()) {
618        return None;
619    }
620    let folder = std::path::absolute(result_cache?).ok()?;
621    Some(folder.join(COMPILED_PLUGIN_CACHE_SUBDIR))
622}
623
624fn parse_plugin_max_download_bytes(
625    lookup: impl Fn(&str) -> Option<std::ffi::OsString>,
626) -> Result<u64, ConfigError> {
627    let Some(raw) = lookup(PLUGIN_MAX_DOWNLOAD_MB_VARIABLE) else {
628        return Ok(DEFAULT_PLUGIN_MAX_DOWNLOAD_BYTES);
629    };
630    if raw.is_empty() {
631        return Ok(DEFAULT_PLUGIN_MAX_DOWNLOAD_BYTES);
632    }
633    let Some(text) = raw.to_str() else {
634        return Err(ConfigError::InvalidPluginMaxDownloadMb {
635            value: raw.to_string_lossy().into_owned(),
636        });
637    };
638    let parsed = text
639        .parse::<u64>()
640        .ok()
641        .filter(|&mb| mb > 0 && mb <= MAX_PLUGIN_DOWNLOAD_MIB)
642        .and_then(|mb| mb.checked_mul(BYTES_PER_MIB));
643    parsed.ok_or_else(|| ConfigError::InvalidPluginMaxDownloadMb {
644        value: text.to_owned(),
645    })
646}
647
648fn existing_folder(current_folder: &Path, path: Option<PathBuf>) -> Result<PathBuf, ConfigError> {
649    let Some(path) = path else {
650        return Ok(current_folder.to_path_buf());
651    };
652    let folder = std::fs::canonicalize(current_folder.join(&path)).map_err(|source| {
653        if source.kind() == std::io::ErrorKind::NotFound {
654            ConfigError::MissingPath { path: path.clone() }
655        } else {
656            ConfigError::UnreadablePath {
657                path: path.clone(),
658                source,
659            }
660        }
661    })?;
662    if folder.is_dir() {
663        Ok(folder)
664    } else {
665        Err(ConfigError::NotAFolder { path })
666    }
667}
668
669fn report_destination(
670    current_folder: &Path,
671    output: Option<PathBuf>,
672) -> Result<ReportDestination, ConfigError> {
673    let Some(path) = output else {
674        return Ok(ReportDestination::StandardOutput);
675    };
676    let folder = path.parent().unwrap_or(Path::new("")).to_path_buf();
677    if current_folder.join(&folder).is_dir() {
678        Ok(ReportDestination::File(path))
679    } else {
680        Err(ConfigError::MissingOutputFolder { path, folder })
681    }
682}
683
684fn findings_shown(all: bool) -> FindingsShown {
685    if all {
686        FindingsShown::All
687    } else {
688        FindingsShown::WorstPerMetric(WORST_FINDINGS_PER_METRIC)
689    }
690}