Skip to main content

cargo_qc/
lib.rs

1#![doc = include_str!("../README.md")]
2#![warn(missing_docs)]
3
4/// Configuration options and project context parsing.
5pub mod config;
6/// Error definitions for the cargo-qc pipeline.
7pub mod error;
8/// History logging and file output formatting.
9pub mod history;
10/// Test and build execution wrappers.
11pub mod runner;
12/// Terminal spinner implementation.
13pub mod spinner;
14/// Telemetry handling.
15pub mod telemetry;
16
17use config::{ProjectContext, QcOptions};
18use error::QcError;
19use owo_colors::OwoColorize;
20use std::fmt::Display;
21use std::time::Instant;
22
23const PREFIX: &str = "[cargo-qc]";
24const CHECK_LABEL_WIDTH: usize = 34;
25
26use std::sync::atomic::{AtomicBool, Ordering};
27
28static GLOBAL_NO_COLOR: AtomicBool = AtomicBool::new(false);
29
30/// Sets the global no-color flag for logging functions.
31fn set_no_color(no_color: bool) {
32    GLOBAL_NO_COLOR.store(no_color, Ordering::Relaxed);
33}
34
35pub(crate) fn no_color() -> bool {
36    GLOBAL_NO_COLOR.load(Ordering::Relaxed)
37}
38
39/// Logs a plain message to the console with the `[cargo-qc]` prefix.
40pub fn log_line(message: impl Display) {
41    if no_color() {
42        println!("{} {}", PREFIX, message);
43    } else {
44        println!("{} {}", PREFIX.dimmed(), message);
45    }
46}
47
48/// Logs a check step (e.g. fmt, clippy) and whether it passed (`✅` or `❌`).
49pub fn log_check(label: &str, passed: bool) {
50    let icon = if passed { "✅" } else { "❌" };
51    if no_color() {
52        println!("{} {label:<CHECK_LABEL_WIDTH$}{icon}", PREFIX);
53    } else {
54        println!("{} {label:<CHECK_LABEL_WIDTH$}{icon}", PREFIX.dimmed());
55    }
56}
57
58/// Logs a fatal error message in red.
59pub fn log_error(message: impl Display) {
60    if no_color() {
61        eprintln!("error: {message}");
62    } else {
63        eprintln!("{} {message}", "error:".red().bold());
64    }
65}
66
67/// Logs a warning message in yellow.
68pub fn log_warning(message: impl Display) {
69    if no_color() {
70        println!("warning: {message}");
71    } else {
72        println!("{} {message}", "warning:".yellow().bold());
73    }
74}
75
76// Re-export QcOptions for public usage
77pub use config::QcOptions as Options;
78
79/// Main entry point for the `cargo qc` library.
80///
81/// Runs the configured quality gates (fmt, clippy, build, test) sequentially,
82/// writes the results to `.qc_history.md`, and saves any errors to `.qc_errors.log`.
83pub fn run(options: QcOptions) -> anyhow::Result<()> {
84    let start_time = Instant::now();
85    set_no_color(options.no_color);
86
87    let is_tty = std::io::IsTerminal::is_terminal(&std::io::stdout());
88    let disable_spinners = options.ci || !is_tty;
89
90    if no_color() {
91        log_line("Local Quality Control");
92    } else {
93        log_line("Local Quality Control".bold());
94    }
95
96    let ctx = ProjectContext::detect()?;
97
98    if no_color() {
99        log_line(format!("Project: {} v{}", ctx.project_name, ctx.version));
100    } else {
101        log_line(format!(
102            "Project: {} v{}",
103            ctx.project_name.bold(),
104            ctx.version.cyan()
105        ));
106    }
107    log_line(format!("Directory: {}", ctx.current_dir.display()));
108
109    ctx.ensure_gitignore(options.ci)?;
110
111    let done_signal = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
112    let done_clone = std::sync::Arc::clone(&done_signal);
113    let no_color_val = options.no_color;
114    std::thread::spawn(move || {
115        let mut elapsed = 0;
116        while elapsed < 15 {
117            if done_clone.load(std::sync::atomic::Ordering::Relaxed) {
118                return;
119            }
120            std::thread::sleep(std::time::Duration::from_secs(1));
121            elapsed += 1;
122        }
123        if !done_clone.load(std::sync::atomic::Ordering::Relaxed) {
124            if no_color_val {
125                println!(
126                    "\n[cargo-qc] Note: The process is taking longer than expected (15s). Please be patient..."
127                );
128            } else {
129                println!(
130                    "\n{} Note: The process is taking longer than expected (15s). Please be patient...",
131                    "[cargo-qc]".dimmed()
132                );
133            }
134        }
135    });
136
137    let mut err_log = String::new();
138
139    let fmt_pass = if !options.skip_fmt {
140        runner::run_fmt(&mut err_log, disable_spinners, options.no_color)
141    } else {
142        true
143    };
144
145    let clippy_pass = if !options.skip_clippy {
146        runner::run_clippy(
147            &mut err_log,
148            disable_spinners,
149            options.no_color,
150            options.strict,
151        )
152    } else {
153        true
154    };
155
156    let build_pass = if !options.skip_build {
157        runner::run_build(&mut err_log, disable_spinners, options.no_color)
158    } else {
159        true
160    };
161
162    let test_pass = if !options.skip_test {
163        runner::run_test(&mut err_log, disable_spinners, options.no_color)
164    } else {
165        true
166    };
167
168    done_signal.store(true, std::sync::atomic::Ordering::Relaxed);
169
170    let all_passed = fmt_pass && clippy_pass && build_pass && test_pass;
171    let failed_count = [fmt_pass, clippy_pass, build_pass, test_pass]
172        .iter()
173        .filter(|passed| !**passed)
174        .count();
175
176    let duration = start_time.elapsed();
177
178    history::record_history(
179        &ctx.log_dir,
180        &ctx.version,
181        fmt_pass,
182        clippy_pass,
183        build_pass,
184        test_pass,
185        duration,
186    )?;
187
188    if let Some(telemetry_url) = options.telemetry {
189        telemetry::send(
190            &telemetry_url,
191            &ctx.version,
192            fmt_pass,
193            clippy_pass,
194            build_pass,
195            test_pass,
196            all_passed,
197            duration.as_secs_f64(),
198        );
199    }
200
201    if !all_passed {
202        let err_log_path = history::record_errors(&ctx.log_dir, &ctx.version, &err_log)?;
203        return Err(QcError::ChecksFailed {
204            failed_count,
205            log_path: err_log_path,
206        }
207        .into());
208    }
209
210    history::log_success();
211    Ok(())
212}