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