gx 0.8.5

CLI to manage Github Actions dependencies
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
#![expect(
    unused_crate_dependencies,
    reason = "dev-dependencies are only used in integration tests"
)]

use clap::{Parser, Subcommand};
use gx::audit::Error as AuditError;
use gx::command::{Command as _, CommandReport as _};
use gx::config::{Config, Error as ConfigError, Settings};
use gx::infra::{repo, repo::Error as RepoError};
use gx::init::Error as InitError;
use gx::lint::Error as LintError;
use gx::output::lines::Line as OutputLine;
use gx::output::log_file::LogFile;
use gx::output::printer::Printer;
use gx::tidy::RunError as TidyRunError;
use gx::upgrade::command::RunError as UpgradeRunError;
use gx::{audit, init, lint, tidy, upgrade};
use indicatif::ProgressBar;
use thiserror::Error;

/// Top-level error type for the gx CLI binary.
#[derive(Debug, Error)]
enum GxError {
    /// Upgrade resolution failed.
    #[error(transparent)]
    Resolve(#[from] upgrade::cli::Error),

    /// Configuration loading failed.
    #[error(transparent)]
    Config(#[from] ConfigError),

    /// Init command failed.
    #[error(transparent)]
    Init(#[from] InitError),

    /// Tidy command failed.
    #[error(transparent)]
    Tidy(#[from] TidyRunError),

    /// Upgrade command failed.
    #[error(transparent)]
    Upgrade(#[from] UpgradeRunError),

    /// Lint command failed.
    #[error(transparent)]
    Lint(#[from] LintError),

    /// Audit command failed.
    #[error(transparent)]
    Audit(#[from] AuditError),

    /// Repository detection failed.
    #[error(transparent)]
    Repo(#[from] RepoError),

    /// I/O error.
    #[error(transparent)]
    Io(#[from] std::io::Error),
}

#[derive(Parser)]
#[command(name = "gx")]
#[command(about = "CLI to manage Github Actions dependencies", long_about = None)]
#[command(version)]
/// CLI argument parser for the gx binary.
struct Cli {
    /// The subcommand to execute.
    #[command(subcommand)]
    command: Commands,
}

/// Available subcommands for the gx CLI.
#[derive(Subcommand)]
enum Commands {
    /// Ensure the manifest and lock matches the workflow code.
    Tidy,
    /// Create manifest and lock files from current workflows.
    Init,
    /// Upgrade actions to newer versions.
    Upgrade {
        /// Optional action identifier to upgrade (e.g., `actions/checkout`).
        #[arg(value_name = "ACTION")]
        action: Option<String>,
        /// Upgrade to the latest version instead of safe update.
        #[arg(long)]
        latest: bool,
        /// Emit the result as JSON on stdout (for scripting / unattended PRs).
        #[arg(long)]
        json: bool,
    },
    /// Run lint checks on workflows.
    ///
    /// Reports action-hygiene issues (sha-mismatch, unpinned, stale-comment,
    /// unsynced-manifest) and workflow-security issues (missing-permissions,
    /// excessive-permissions, dangerous-trigger, pr-head-checkout,
    /// missing-concurrency, unprotected-secrets). Configure per-rule severity
    /// and ignores under `[lint.rules]` in `.github/gx.toml`. See
    /// `docs/lint-rules.md`.
    Lint,
    /// Audit locked actions against security advisories and upstream repository state.
    ///
    /// Unlike `gx lint`, which is fully offline, audit queries GitHub and its verdict
    /// changes over time: the same commit can be clean today and vulnerable tomorrow.
    /// It reads `.github/gx.lock` and requires a GitHub token in `GITHUB_TOKEN`.
    Audit {
        /// Emit the findings as JSON on stdout (for scripting / CI).
        #[arg(long)]
        json: bool,
    },
}

impl Commands {
    /// Whether this invocation writes a machine-readable document to stdout.
    ///
    /// Owned here rather than tested at each use site because `--json` turns stdout
    /// into a single document, and every human-facing line — spinner, CI notice, log
    /// path — must be suppressed consistently. Three call sites testing the same
    /// condition separately is how one of them gets missed when a command gains the flag.
    const fn json_mode(&self) -> bool {
        match self {
            Self::Upgrade { json, .. } | Self::Audit { json } => *json,
            Self::Tidy | Self::Init | Self::Lint => false,
        }
    }
}

/// Create a progress callback that updates the spinner, log file, and CI output.
fn make_cb<'cb>(
    spinner: Option<&'cb ProgressBar>,
    log_file: &'cb mut Option<LogFile>,
    is_ci: bool,
) -> impl FnMut(&str) + 'cb {
    move |msg: &str| {
        if let Some(pb) = spinner {
            pb.set_message(msg.to_owned());
        }
        if let Some(lf) = log_file.as_mut() {
            lf.write(msg);
        }
        if is_ci {
            use std::time::{SystemTime, UNIX_EPOCH};
            let secs = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs();
            let h = (secs / 3600) % 24;
            let m = (secs / 60) % 60;
            let s = secs % 60;
            #[expect(
                clippy::print_stdout,
                reason = "CI verbose mode outputs directly to stdout"
            )]
            {
                println!(" [{h:02}:{m:02}:{s:02}] {msg}");
            }
        }
    }
}

/// Clear and finish the spinner if present.
fn finish_spinner(spinner: Option<ProgressBar>) {
    if let Some(pb) = spinner {
        pb.finish_and_clear();
    }
}

/// Append the log file path to the output lines if a log file exists.
fn append_log_path(log_file: Option<&LogFile>, lines: &mut Vec<OutputLine>) {
    if let Some(lf) = log_file {
        lines.push(OutputLine::LogPath {
            path: lf.path().clone(),
        });
    }
}

/// Run a command with the standard spinner → render → print flow shared by
/// tidy, init, and lint. Returns the log file so `main` keeps it alive; exits
/// the process directly on a non-zero report exit code.
fn run_reported<C>(
    printer: &Printer,
    repo_root: &std::path::Path,
    config: Config,
    is_ci: bool,
    log_file: Option<LogFile>,
    spinner_text: &str,
    command: &C,
) -> Result<Option<LogFile>, GxError>
where
    C: gx::command::Command,
    GxError: From<C::Error>,
{
    let spinner = printer.spinner(spinner_text);
    let mut lf = log_file;
    let report = {
        let mut cb = make_cb(spinner.as_ref(), &mut lf, is_ci);
        command.run(repo_root, config, &mut cb)?
    };
    finish_spinner(spinner);
    let mut lines = report.render();
    append_log_path(lf.as_ref(), &mut lines);
    printer.print_lines(&lines);
    if report.exit_code() != 0 {
        std::process::exit(report.exit_code());
    }
    Ok(lf)
}

/// Run the upgrade command, rendering either human output or, with `--json`, a
/// single JSON document on stdout. Returns the log file to keep it alive until
/// `main` drops it. Exits the process directly on a non-zero report exit code.
fn run_upgrade(
    printer: &Printer,
    repo_root: &std::path::Path,
    config: Config,
    log_file: Option<LogFile>,
    action: Option<&str>,
    latest: bool,
    json: bool,
) -> Result<Option<LogFile>, GxError> {
    let request = upgrade::cli::resolve_upgrade_mode(action, latest)?;
    // In JSON mode stdout must be a single JSON document, so suppress the spinner
    // and the local log file (their progress noise would corrupt it).
    let spinner = if json {
        None
    } else {
        printer.spinner("Checking actions...")
    };
    let mut lf = if json { None } else { log_file };
    let report = {
        let mut cb = make_cb(spinner.as_ref(), &mut lf, printer.is_ci && !json);
        upgrade::command::Upgrade { request }.run(repo_root, config, &mut cb)?
    };
    finish_spinner(spinner);

    if json {
        #[expect(clippy::print_stdout, reason = "JSON contract is written to stdout")]
        {
            println!("{}", report.to_json());
        }
    } else {
        let mut lines = report.render();
        append_log_path(lf.as_ref(), &mut lines);
        printer.print_lines(&lines);
    }

    if report.exit_code() != 0 {
        std::process::exit(report.exit_code());
    }

    Ok(lf)
}

/// Run the audit command, rendering either human output or, with `--json`, a single
/// JSON document on stdout. Returns the log file to keep it alive until `run` drops it.
/// Exits the process directly on a non-zero report exit code.
///
/// A missing token surfaces as `Err` from `run` and propagates out of `main`, so no
/// report — and under `--json` no document at all — is ever printed for a run that did
/// not actually audit anything.
fn run_audit(
    printer: &Printer,
    repo_root: &std::path::Path,
    config: Config,
    log_file: Option<LogFile>,
    json: bool,
) -> Result<Option<LogFile>, GxError> {
    // In JSON mode stdout must be a single JSON document, so suppress the spinner and
    // the local log file (their progress noise would corrupt it).
    let spinner = if json {
        None
    } else {
        printer.spinner("Auditing...")
    };
    let mut lf = if json { None } else { log_file };
    let audit = audit::Audit::from_settings(&config.settings)?;
    let report = {
        let mut cb = make_cb(spinner.as_ref(), &mut lf, printer.is_ci && !json);
        audit.run(repo_root, config, &mut cb)?
    };
    finish_spinner(spinner);

    if json {
        #[expect(clippy::print_stdout, reason = "JSON contract is written to stdout")]
        {
            println!("{}", report.to_json());
        }
    } else {
        let mut lines = report.render();
        append_log_path(lf.as_ref(), &mut lines);
        printer.print_lines(&lines);
    }

    if report.exit_code() != 0 {
        std::process::exit(report.exit_code());
    }

    Ok(lf)
}

fn main() {
    // `run` returns the error rather than `main` doing so, because `Termination` prints a
    // returned error with `Debug` — `Audit(MissingToken)` — which would bury the message
    // telling the user which variable to set. Printing `Display` here surfaces the full,
    // actionable text, and every error type in `GxError` already writes a good one.
    if let Err(error) = run() {
        #[expect(
            clippy::print_stderr,
            reason = "top-level error reporting, before any printer exists"
        )]
        {
            eprintln!("Error: {error}");
        }
        std::process::exit(1);
    }
}

/// The real entry point. See [`main`] for why the error is returned rather than propagated.
fn run() -> Result<(), GxError> {
    let cli = Cli::parse();
    if matches!(cli.command, Commands::Audit { .. }) {
        audit::require_token(&Settings::from_env())?;
    }

    let printer = Printer::new();
    let is_ci = printer.is_ci;

    let cmd_name = match &cli.command {
        Commands::Tidy => "tidy",
        Commands::Init => "init",
        Commands::Upgrade { .. } => "upgrade",
        Commands::Lint => "lint",
        Commands::Audit { .. } => "audit",
    };

    // `--json` turns stdout into a single machine-readable document, so every
    // human-facing line below (CI notice, log path, ".github not found") must be
    // suppressed for it.
    let json_mode = cli.command.json_mode();

    // Create log file for local runs (not CI)
    let mut log_file: Option<LogFile> = if is_ci || json_mode {
        None
    } else {
        LogFile::new(cmd_name).ok()
    };

    if is_ci && !json_mode {
        printer.print_lines(&[OutputLine::CiNotice {
            message: "CI detected, running in verbose mode".to_owned(),
        }]);
    }

    let cwd = std::env::current_dir()?;
    let repo_root = match repo::find_root(&cwd) {
        Ok(root) => root,
        Err(RepoError::GithubFolder) => {
            if json_mode {
                // Emit a valid, empty JSON document so a consumer's parser never breaks.
                // Each command has its own document shape, so the right one must be
                // chosen here — a consumer of `gx audit --json` parses findings, not
                // upgrades, and would break on the other command's schema.
                let empty = match &cli.command {
                    Commands::Audit { .. } => audit::Report::default().to_json(),
                    Commands::Tidy | Commands::Init | Commands::Lint | Commands::Upgrade { .. } => {
                        upgrade::command::empty_json_report()
                    }
                };
                #[expect(clippy::print_stdout, reason = "JSON contract is written to stdout")]
                {
                    println!("{empty}");
                }
            } else {
                printer.print_lines(&[OutputLine::Summary {
                    text: ".github folder not found. gx didn't modify any file.".to_owned(),
                }]);
            }
            return Ok(());
        }
        Err(e) => return Err(e.into()),
    };

    let config = Config::load(&repo_root)?;

    let lf = log_file.take();
    log_file = match cli.command {
        Commands::Tidy => run_reported(
            &printer,
            &repo_root,
            config,
            is_ci,
            lf,
            "Running tidy...",
            &tidy::Tidy,
        )?,
        Commands::Init => run_reported(
            &printer,
            &repo_root,
            config,
            is_ci,
            lf,
            "Initializing...",
            &init::Init,
        )?,
        Commands::Lint => run_reported(
            &printer,
            &repo_root,
            config,
            is_ci,
            lf,
            "Linting...",
            &lint::Lint,
        )?,
        Commands::Upgrade {
            action,
            latest,
            json,
        } => run_upgrade(
            &printer,
            &repo_root,
            config,
            lf,
            action.as_deref(),
            latest,
            json,
        )?,
        Commands::Audit { json } => run_audit(&printer, &repo_root, config, lf, json)?,
    };

    drop(log_file);
    Ok(())
}