github-actions-maintainer 0.7.4

General-purpose GitHub Actions maintenance toolkit with secure workflow pinning
Documentation
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
mod input_env;
mod release_cli;

// Tests live in a sibling file to keep this module readable; they remain
// `super::`-scoped unit tests.
#[cfg(test)]
#[path = "cli_tests.rs"]
mod cli_tests;

use std::{ffi::OsString, path::PathBuf};

use anyhow::Result;
use clap::{Args, Parser, Subcommand};
use github_actions_maintainer::{
    CargoUpdateOptions, CargoUpdater, CratesIoClient, FileUpdate, GitHubClient, PinMode,
    PinOptions, PolicyOptions, PolicyReport, PolicyScanner, PullRequestOptions,
    RemoteUpdatePublisher, UpdateChange, UpdateMode, UpdateOptions, WorkflowPinner,
    WorkflowUpdater,
};
use release_cli::{ReleaseArgs, run_release};

#[derive(Debug, Parser)]
#[command(
    author,
    version,
    about = "General-purpose GitHub Actions maintenance with secure pinning as the first feature."
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,

    #[arg(long, env = "GITHUB_API_BASE_URL", hide = true, global = true)]
    github_api_base_url: Option<String>,

    #[arg(long, env = "CRATES_IO_API_BASE_URL", hide = true, global = true)]
    crates_api_base_url: Option<String>,
}

#[derive(Debug, Subcommand)]
enum Commands {
    /// Resolve floating GitHub Action refs to immutable commit SHAs.
    Pin(PinArgs),
    /// Update GitHub Actions to the latest release or tag, then pin them.
    Update(UpdateArgs),
    /// Report current and latest versions for GitHub Actions in workflows.
    Status(StatusArgs),
    /// Scan workflows for script usage and baseline policy findings.
    Policy(PolicyArgs),
    /// Bump the Cargo version from conventional commits, then commit, tag, and
    /// publish a GitHub Release.
    Release(ReleaseArgs),
}

#[derive(Debug, Args)]
struct RepoArgs {
    /// Repository root to scan.
    #[arg(long, env = "INPUT_REPO", default_value = ".")]
    repo: PathBuf,

    /// Relative path to workflow files beneath the repository root.
    #[arg(long, env = "INPUT_WORKFLOWS-PATH", default_value = ".github/workflows")]
    workflows_path: PathBuf,

    /// GitHub token used to raise API rate limits; falls back to `GITHUB_TOKEN`.
    #[arg(long, env = "INPUT_TOKEN", hide_env_values = true)]
    token: Option<String>,

    /// Repository owner used for remote PR creation; falls back to `OWNER`.
    #[arg(long, env = "INPUT_OWNER")]
    owner: Option<String>,

    /// Repository name used for remote PR creation; falls back to `REPO_NAME`.
    #[arg(long = "repo-name", env = "INPUT_REPO-NAME")]
    repo_name: Option<String>,

    /// Create a branch and pull request remotely instead of rewriting files locally.
    #[arg(long, env = "INPUT_CREATE-PR", default_value_t = false, num_args = 0..=1, default_missing_value = "true")]
    create_pr: bool,

    /// Override the base branch for remote PR creation.
    #[arg(long, env = "INPUT_BASE-BRANCH")]
    base_branch: Option<String>,

    /// Override the update branch name for remote PR creation.
    #[arg(long, env = "INPUT_BRANCH-NAME")]
    branch_name: Option<String>,

    /// Labels to add to a created pull request, comma-separated.
    #[arg(long, env = "INPUT_LABELS", default_value = "dependencies")]
    labels: String,

    /// Pull request title for remote update mode.
    #[arg(long, env = "INPUT_TITLE", default_value = "Update dependencies")]
    title: String,

    /// Commit message for remote update mode.
    #[arg(long, env = "INPUT_COMMIT-MESSAGE", default_value = "Update dependencies")]
    commit_message: String,
}

#[derive(Debug, Args)]
struct PinArgs {
    #[command(flatten)]
    repo: RepoArgs,

    #[command(flatten)]
    #[allow(dead_code)]
    targets: TargetArgs,

    /// Show changes without rewriting files.
    #[arg(long, env = "INPUT_DRY-RUN", default_value_t = false, num_args = 0..=1, default_missing_value = "true")]
    dry_run: bool,
}

#[derive(Debug, Args)]
struct UpdateArgs {
    #[command(flatten)]
    repo: RepoArgs,

    #[command(flatten)]
    targets: TargetArgs,

    /// Show available updates without rewriting files.
    #[arg(long, env = "INPUT_DRY-RUN", default_value_t = false, num_args = 0..=1, default_missing_value = "true")]
    dry_run: bool,
}

#[derive(Debug, Args)]
struct StatusArgs {
    #[command(flatten)]
    repo: RepoArgs,

    #[command(flatten)]
    targets: TargetArgs,

    #[arg(long, env = "INPUT_DRY-RUN", hide = true, default_value_t = false, num_args = 0..=1, default_missing_value = "true")]
    _dry_run: bool,
}

// Every field here is an independent action input, and one of them only exists
// to absorb the `--dry-run` the container action passes to every command, so
// there is no state machine to factor these into.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Args)]
struct PolicyArgs {
    #[command(flatten)]
    repo: RepoArgs,

    /// Report explicit Bash/sh and Python usage in `run:` and `shell:` blocks.
    #[arg(long, env = "INPUT_CHECK-SCRIPTS", default_value_t = true, num_args = 0..=1, default_missing_value = "true")]
    check_scripts: bool,

    /// Report unpinned actions, permission, and job timeout findings.
    #[arg(long, env = "INPUT_CHECK-POLICIES", default_value_t = true, num_args = 0..=1, default_missing_value = "true")]
    check_policies: bool,

    /// Exit non-zero when the scan reports any finding.
    #[arg(long, env = "INPUT_FAIL-ON-FINDINGS", default_value_t = false, num_args = 0..=1, default_missing_value = "true")]
    fail_on_findings: bool,

    #[arg(long, env = "INPUT_DRY-RUN", hide = true, default_value_t = false, num_args = 0..=1, default_missing_value = "true")]
    _dry_run: bool,
}

#[derive(Debug, Args, Clone, Default)]
struct TargetArgs {
    /// Include GitHub Actions workflow updates.
    #[arg(long = "github-actions", env = "INPUT_GITHUB-ACTIONS", default_value_t = false, num_args = 0..=1, default_missing_value = "true")]
    github_actions: bool,

    /// Include cargo package dependency updates.
    #[arg(long, env = "INPUT_CARGO", default_value_t = false, num_args = 0..=1, default_missing_value = "true")]
    cargo: bool,

    /// Include both GitHub Actions and cargo package updates.
    #[arg(long, env = "INPUT_ALL", default_value_t = false, num_args = 0..=1, default_missing_value = "true")]
    all: bool,
}

#[derive(Debug, Clone, Copy)]
struct SelectedTargets {
    github_actions: bool,
    cargo: bool,
}

impl TargetArgs {
    const fn resolve(&self) -> SelectedTargets {
        if self.all {
            return SelectedTargets { github_actions: true, cargo: true };
        }

        if !self.github_actions && !self.cargo {
            return SelectedTargets { github_actions: true, cargo: false };
        }

        SelectedTargets { github_actions: self.github_actions, cargo: self.cargo }
    }
}

fn main() {
    // SAFETY: `normalize_inputs` mutates the process environment. This is the
    // first statement in `main`, so no other thread exists yet and nothing else
    // has read the environment.
    let args = unsafe { input_env::normalize_inputs(std::env::args_os()) };

    if let Err(error) = run(args) {
        eprintln!("error: {error:#}");
        std::process::exit(1);
    }
}

fn run(args: Vec<OsString>) -> Result<()> {
    let cli = Cli::parse_from(args);

    match cli.command {
        Commands::Pin(args) => run_pin(args, cli.github_api_base_url),
        Commands::Update(args) => {
            run_update(args, cli.github_api_base_url, cli.crates_api_base_url)
        }
        Commands::Status(args) => {
            run_status(args, cli.github_api_base_url, cli.crates_api_base_url)
        }
        Commands::Policy(args) => run_policy(args),
        Commands::Release(args) => run_release(args, cli.github_api_base_url),
    }
}

fn run_policy(args: PolicyArgs) -> Result<()> {
    let scanner = PolicyScanner::new();
    let report = scanner.scan(&PolicyOptions {
        repo_root: args.repo.repo,
        workflows_path: args.repo.workflows_path,
        check_scripts: args.check_scripts,
        check_policies: args.check_policies,
    })?;

    print_policy_report(&report);

    if args.fail_on_findings && report.has_findings() {
        anyhow::bail!(
            "workflow policy scan found {} script usages and {} policy violations",
            report.script_usages.len(),
            report.policy_violations.len()
        );
    }

    Ok(())
}

fn print_policy_report(report: &PolicyReport) {
    println!(
        "Scanned {} workflow files. Found {} script usages and {} policy violations.",
        report.workflow_files,
        report.script_usages.len(),
        report.policy_violations.len()
    );
    println!(
        "Script summary: bash={}, python={}",
        report.summary.bash_scripts, report.summary.python_scripts
    );
    println!(
        "Policy summary: high={}, medium={}, low={}",
        report.summary.high_violations,
        report.summary.medium_violations,
        report.summary.low_violations
    );

    if !report.script_usages.is_empty() {
        println!();
        println!("Script usages:");
        for usage in &report.script_usages {
            println!(
                "- {}:{} [{}] {}",
                usage.file.display(),
                usage.line_number,
                usage.script_type_label(),
                usage.command
            );
        }
    }

    if !report.policy_violations.is_empty() {
        println!();
        println!("Policy violations:");
        for violation in &report.policy_violations {
            println!(
                "- {}:{} [{}] {}: {}",
                violation.file.display(),
                violation.line_number,
                violation.severity_label(),
                violation.violation_type_label(),
                violation.description
            );
        }
    }
}

fn run_pin(args: PinArgs, github_api_base_url: Option<String>) -> Result<()> {
    let github = GitHubClient::new(
        github_api_base_url.unwrap_or_else(|| String::from("https://api.github.com")),
        args.repo.token,
    )?;
    let pinner = WorkflowPinner::new(github);
    let report = pinner.pin(&PinOptions {
        repo_root: args.repo.repo,
        workflows_path: args.repo.workflows_path,
        mode: if args.dry_run { PinMode::DryRun } else { PinMode::Apply },
    })?;

    if report.changes.is_empty() {
        println!(
            "No floating GitHub Actions references needed pinning. Scanned {} references across {} workflow files; {} were already pinned.",
            report.references_scanned, report.workflow_files, report.already_pinned
        );
        return Ok(());
    }

    if args.dry_run {
        println!(
            "Dry run: would pin {} action references across {} files.",
            report.changes.len(),
            report.changed_files()
        );
    } else {
        println!(
            "Pinned {} action references across {} files.",
            report.changes.len(),
            report.changed_files()
        );
    }

    for change in &report.changes {
        println!(
            "- {}:{} {}@{} -> {}",
            change.file.display(),
            change.line_number,
            change.action_slug,
            change.from_version,
            change.to_sha
        );
    }

    Ok(())
}

fn run_update(
    args: UpdateArgs,
    github_api_base_url: Option<String>,
    crates_api_base_url: Option<String>,
) -> Result<()> {
    let repo_args = args.repo;
    let repo_root = repo_args.repo.clone();
    let workflows_path = repo_args.workflows_path.clone();
    let token = repo_args.token.clone();
    let remote_mode = repo_args.create_pr;
    let targets = args.targets.resolve();
    let update_mode =
        if args.dry_run || remote_mode { UpdateMode::DryRun } else { UpdateMode::Apply };

    let action_report = if targets.github_actions {
        let github = GitHubClient::new(
            github_api_base_url.clone().unwrap_or_else(|| String::from("https://api.github.com")),
            token.clone(),
        )?;
        let updater = WorkflowUpdater::new(github);
        Some(updater.update(&UpdateOptions {
            repo_root: repo_root.clone(),
            workflows_path,
            mode: update_mode,
        })?)
    } else {
        None
    };

    let cargo_report = if targets.cargo {
        let crates_io = CratesIoClient::new(
            crates_api_base_url.unwrap_or_else(|| String::from("https://crates.io/api/v1")),
        )?;
        let updater = CargoUpdater::new(crates_io);
        Some(
            updater
                .update(&CargoUpdateOptions { repo_root: repo_root.clone(), mode: update_mode })?,
        )
    } else {
        None
    };

    let mut combined_changes = Vec::new();
    let mut combined_file_updates = Vec::new();
    if let Some(report) = &action_report {
        combined_changes.extend(report.changes.clone());
        combined_file_updates.extend(report.file_updates.clone());
    }
    if let Some(report) = &cargo_report {
        combined_changes.extend(report.changes.clone());
        combined_file_updates.extend(report.file_updates.clone());
    }

    if combined_changes.is_empty() {
        print_update_noop_summary(action_report.as_ref(), cargo_report.as_ref());
        return Ok(());
    }

    if remote_mode {
        if args.dry_run {
            println!(
                "Would create a pull request with {} dependency updates across {} files.",
                combined_changes.len(),
                count_changed_files(&combined_file_updates)
            );
        } else {
            let github = GitHubClient::new(
                github_api_base_url.unwrap_or_else(|| String::from("https://api.github.com")),
                token,
            )?;
            let (owner, repo_name) = resolve_remote_repository(&repo_args)?;
            let publisher = RemoteUpdatePublisher::new(github);
            let result = publisher
                .publish(
                    &combined_file_updates,
                    &combined_changes,
                    &PullRequestOptions {
                        repo_root,
                        owner,
                        repo: repo_name,
                        base_branch: repo_args.base_branch,
                        branch_name: repo_args.branch_name,
                        labels: parse_labels(&repo_args.labels),
                        title: repo_args.title,
                        commit_message: repo_args.commit_message,
                    },
                )?
                .expect("remote publish returns a pull request result when changes exist");

            println!(
                "Created pull request #{} on branch {}: {}",
                result.number, result.branch_name, result.url
            );
        }

        print_update_changes(&combined_changes);

        return Ok(());
    }

    println!(
        "{} {} dependency updates across {} files.",
        if args.dry_run { "Would apply" } else { "Applied" },
        combined_changes.len(),
        count_changed_files(&combined_file_updates)
    );

    print_update_changes(&combined_changes);

    Ok(())
}

fn parse_labels(raw: &str) -> Vec<String> {
    raw.split(',').map(str::trim).filter(|label| !label.is_empty()).map(ToOwned::to_owned).collect()
}

fn resolve_remote_repository(args: &RepoArgs) -> Result<(String, String)> {
    resolve_repository(args.owner.as_deref(), args.repo_name.as_deref())
}

fn resolve_repository(owner: Option<&str>, repo_name: Option<&str>) -> Result<(String, String)> {
    match (owner.map(str::trim), repo_name.map(str::trim)) {
        (Some(owner), Some(repo_name)) if !owner.is_empty() && !repo_name.is_empty() => {
            return Ok((owner.to_owned(), repo_name.to_owned()));
        }
        _ => {}
    }

    if let Ok(repository) = std::env::var("GITHUB_REPOSITORY")
        && let Some((owner, repo_name)) = repository.split_once('/')
    {
        return Ok((owner.to_owned(), repo_name.to_owned()));
    }

    anyhow::bail!(
        "--owner and --repo-name (or the GITHUB_REPOSITORY environment variable) are required"
    )
}

fn run_status(
    args: StatusArgs,
    github_api_base_url: Option<String>,
    crates_api_base_url: Option<String>,
) -> Result<()> {
    let targets = args.targets.resolve();
    let printed_section = if targets.github_actions {
        let github = GitHubClient::new(
            github_api_base_url.unwrap_or_else(|| String::from("https://api.github.com")),
            args.repo.token.clone(),
        )?;
        let updater = WorkflowUpdater::new(github);
        let report = updater.update(&UpdateOptions {
            repo_root: args.repo.repo.clone(),
            workflows_path: args.repo.workflows_path.clone(),
            mode: UpdateMode::Status,
        })?;

        let updates_needed = report.entries.iter().filter(|entry| entry.update_needed).count();
        println!(
            "Scanned {} action references across {} workflow files. {} need changes.",
            report.references_scanned, report.workflow_files, updates_needed
        );

        for entry in &report.entries {
            println!(
                "- {}:{} {} current={} latest={} pinned={} status={}",
                entry.file.display(),
                entry.line_number,
                entry.action_slug,
                entry.current_version,
                entry.latest_version,
                entry.pinned,
                if entry.update_needed { "update-needed" } else { "current" }
            );
        }

        true
    } else {
        false
    };

    if targets.cargo {
        if printed_section {
            println!();
        }

        let crates_io = CratesIoClient::new(
            crates_api_base_url.unwrap_or_else(|| String::from("https://crates.io/api/v1")),
        )?;
        let updater = CargoUpdater::new(crates_io);
        let report = updater
            .update(&CargoUpdateOptions { repo_root: args.repo.repo, mode: UpdateMode::Status })?;

        let updates_needed = report.entries.iter().filter(|entry| entry.update_needed).count();
        println!(
            "Scanned {} cargo dependencies across {} manifests. {} need changes; {} are unmanaged.",
            report.dependencies_scanned,
            report.manifest_files,
            updates_needed,
            report.unmanaged_dependencies
        );

        for entry in &report.entries {
            let reason_suffix = entry
                .reason
                .as_deref()
                .map(|reason| format!(" reason={reason}"))
                .unwrap_or_default();
            println!(
                "- {} {} current={} latest={} managed={} status={}{}",
                entry.file.display(),
                entry.dependency_name,
                entry.current_requirement.as_deref().unwrap_or("n/a"),
                entry.latest_version.as_deref().unwrap_or("n/a"),
                entry.managed,
                cargo_status_label(entry),
                reason_suffix
            );
        }
    }

    Ok(())
}

const fn cargo_status_label(
    entry: &github_actions_maintainer::CargoDependencyEntry,
) -> &'static str {
    if !entry.managed {
        "unmanaged"
    } else if entry.update_needed {
        "update-needed"
    } else {
        "current"
    }
}

fn print_update_noop_summary(
    action_report: Option<&github_actions_maintainer::UpdateReport>,
    cargo_report: Option<&github_actions_maintainer::CargoUpdateReport>,
) {
    if let Some(report) = action_report {
        println!(
            "All scanned GitHub Actions are already current and pinned. Scanned {} references across {} workflow files.",
            report.references_scanned, report.workflow_files
        );
    }

    if let Some(report) = cargo_report {
        println!(
            "All managed cargo dependencies are already current. Scanned {} dependencies across {} manifests; {} unmanaged dependencies were skipped.",
            report.dependencies_scanned, report.manifest_files, report.unmanaged_dependencies
        );
    }
}

fn count_changed_files(file_updates: &[FileUpdate]) -> usize {
    let mut files = file_updates.iter().map(|update| update.file.as_path()).collect::<Vec<_>>();
    files.sort();
    files.dedup();
    files.len()
}

fn print_update_changes(changes: &[UpdateChange]) {
    for change in changes {
        match change.line_number {
            Some(line_number) => println!(
                "- {} {}:{} {} {} -> {}",
                change.kind.label(),
                change.file.display(),
                line_number,
                change.subject,
                change.from_version,
                change.to_version
            ),
            None => println!(
                "- {} {} {} {} -> {}",
                change.kind.label(),
                change.file.display(),
                change.subject,
                change.from_version,
                change.to_version
            ),
        }
    }
}