github-actions-maintainer 0.7.0

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
//! Automated release publishing driven by conventional commits.
//!
//! The publisher analyzes commits since the last release tag through the
//! GitHub REST API, bumps the Cargo manifest version, and creates the release
//! commit, tag, and GitHub Release without shelling out to git — so it runs in
//! minimal containers. Failures after object creation but before the branch
//! ref update leave only unreachable git objects behind, which GitHub
//! garbage-collects; the window between tag creation and release creation is
//! not auto-healed and requires a manual `gh release create` for the tag.

use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use semver::Version;

use crate::{
    conventional::{self, BumpLevel, ConventionalCommit},
    github::{GitHubClient, TreeEntry},
    remote, versioning,
};

const MAX_COMPARE_PAGES: u32 = 10;
const MAX_FIRST_RELEASE_PAGES: u32 = 3;
const AUTOMATED_RELEASE_BRANCH_PREFIX: &str = "automation/release";

/// How the release tag is created. Annotated tags are the default: they
/// carry a tagger identity and satisfy `git cat-file -t == "tag"` provenance
/// checks. The moving major alias tag is always lightweight.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Default)]
pub enum TagStyle {
    #[default]
    Annotated,
    Lightweight,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ReleaseOptions {
    pub repo_root: PathBuf,
    pub owner: String,
    pub repo: String,
    pub base_branch: Option<String>,
    /// Forced bump level; `None` derives it from conventional commits.
    pub bump: Option<BumpLevel>,
    pub tag_prefix: String,
    pub tag_style: TagStyle,
    pub update_major_alias: bool,
    /// Commit message template; `{version}` is replaced with the new version.
    pub commit_message: String,
    /// Create or refresh an automation-owned release branch and pull request
    /// instead of publishing directly to the base branch.
    pub create_pr: bool,
    pub release_branch: String,
    pub dry_run: bool,
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum ReleaseOutcome {
    Released,
    PullRequestCreated,
    PullRequestUpdated,
    DryRun,
    SkippedNoReleasableChanges,
    SkippedRace,
    SkippedTagExists,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ReleaseReport {
    pub outcome: ReleaseOutcome,
    pub current_version: String,
    pub next_version: Option<String>,
    pub bump: Option<BumpLevel>,
    pub tag: Option<String>,
    pub major_alias: Option<String>,
    pub commit_sha: Option<String>,
    pub release_url: Option<String>,
    pub pull_request_number: Option<u64>,
    pub pull_request_url: Option<String>,
    pub release_branch: Option<String>,
    pub notes: Option<String>,
    pub commits_analyzed: usize,
    pub commit_range_truncated: bool,
    pub files_updated: Vec<PathBuf>,
}

impl ReleaseReport {
    /// Render `$GITHUB_OUTPUT` lines. Keys are always present; values are
    /// empty when the outcome did not produce them.
    pub fn github_outputs(&self, notes_file: &Path) -> String {
        let notes_path =
            if self.notes.is_some() { notes_file.display().to_string() } else { String::new() };
        format!(
            "released={}\nversion={}\ntag={}\nrelease-url={}\nrelease-pr-number={}\nrelease-pr-url={}\nrelease-branch={}\nnotes-file={notes_path}\n",
            self.outcome == ReleaseOutcome::Released,
            self.next_version.as_deref().unwrap_or_default(),
            self.tag.as_deref().unwrap_or_default(),
            self.release_url.as_deref().unwrap_or_default(),
            self.pull_request_number.map(|number| number.to_string()).unwrap_or_default(),
            self.pull_request_url.as_deref().unwrap_or_default(),
            self.release_branch.as_deref().unwrap_or_default(),
        )
    }
}

#[derive(Debug)]
struct Analysis {
    branch: String,
    head_sha: String,
    current_version: String,
    current: Version,
    commits: Vec<ConventionalCommit>,
    truncated: bool,
}

#[derive(Debug)]
struct PreparedRelease {
    branch: String,
    head_sha: String,
    next_version: Version,
    tag: String,
    plan: versioning::VersionRewritePlan,
}

#[derive(Debug, Clone)]
pub struct ReleasePublisher {
    github: GitHubClient,
}

impl ReleasePublisher {
    #[must_use]
    pub const fn new(github: GitHubClient) -> Self {
        Self { github }
    }

    pub fn release(&self, options: &ReleaseOptions) -> Result<ReleaseReport> {
        self.github.ensure_token()?;
        if options.create_pr {
            validate_release_branch(&options.release_branch)?;
        }
        let analysis = self.analyze(options)?;
        let bump = options.bump.or_else(|| conventional::required_bump(&analysis.commits));
        let mut report = initial_report(&analysis, bump);

        let Some(bump_level) = bump else {
            return Ok(report);
        };

        let next_version = conventional::bump_version(&analysis.current, bump_level);
        let next = next_version.to_string();
        let tag = format!("{}{next}", options.tag_prefix);
        report.notes =
            Some(conventional::release_notes(&tag, &analysis.commits, analysis.truncated));
        report.next_version = Some(next);
        report.tag = Some(tag.clone());

        if self
            .github
            .reference_sha(&options.owner, &options.repo, &format!("tags/{tag}"))?
            .is_some()
        {
            report.outcome = ReleaseOutcome::SkippedTagExists;
            return Ok(report);
        }

        let plan = versioning::plan_version_rewrite(&options.repo_root, &next_version.to_string())?;
        report.files_updated = plan.file_updates.iter().map(|update| update.file.clone()).collect();

        if options.dry_run {
            report.outcome = ReleaseOutcome::DryRun;
            return Ok(report);
        }

        let prepared = PreparedRelease {
            branch: analysis.branch,
            head_sha: analysis.head_sha,
            next_version,
            tag,
            plan,
        };
        self.publish(options, &prepared, &mut report)?;
        Ok(report)
    }

    fn analyze(&self, options: &ReleaseOptions) -> Result<Analysis> {
        let owner = &options.owner;
        let repo = &options.repo;
        let branch = match options.base_branch.as_deref().map(str::trim) {
            Some(branch) if !branch.is_empty() => branch.to_owned(),
            _ => self.github.default_branch(owner, repo)?,
        };
        let head_sha = self.github.branch_head_sha(owner, repo, &branch)?;

        let current_version = versioning::current_version(&options.repo_root)?;
        let current = Version::parse(&current_version).with_context(|| {
            format!("invalid current version '{current_version}' in Cargo.toml")
        })?;

        let last_tag = self.github.latest_semver_tag(owner, repo, &options.tag_prefix)?;
        let range = match &last_tag {
            Some(tag) => {
                self.github.compare_commits(owner, repo, &tag.name, &head_sha, MAX_COMPARE_PAGES)?
            }
            None => self.github.list_commits(owner, repo, &head_sha, MAX_FIRST_RELEASE_PAGES)?,
        };

        Ok(Analysis {
            branch,
            head_sha,
            current_version,
            current,
            commits: conventional::classify_commits(&range.commits),
            truncated: range.truncated,
        })
    }

    /// Publish the prepared release. The cheap head re-read gives a clear
    /// skip; the fast-forward-only ref update is the authoritative
    /// compare-and-swap against a branch that advanced mid-run.
    fn publish(
        &self,
        options: &ReleaseOptions,
        prepared: &PreparedRelease,
        report: &mut ReleaseReport,
    ) -> Result<()> {
        let commit_sha = self.build_commit(options, prepared)?;

        let current_head =
            self.github.branch_head_sha(&options.owner, &options.repo, &prepared.branch)?;
        if current_head != prepared.head_sha {
            report.outcome = ReleaseOutcome::SkippedRace;
            return Ok(());
        }
        report.commit_sha = Some(commit_sha.clone());

        if options.create_pr {
            return self.publish_pull_request(options, prepared, &commit_sha, report);
        }

        if !self.github.update_ref_fast_forward(
            &options.owner,
            &options.repo,
            &format!("heads/{}", prepared.branch),
            &commit_sha,
        )? {
            report.outcome = ReleaseOutcome::SkippedRace;
            return Ok(());
        }

        self.finalize(options, prepared, &commit_sha, report)
    }

    fn publish_pull_request(
        &self,
        options: &ReleaseOptions,
        prepared: &PreparedRelease,
        commit_sha: &str,
        report: &mut ReleaseReport,
    ) -> Result<()> {
        let owner = &options.owner;
        let repo = &options.repo;
        let branch_ref = format!("heads/{}", options.release_branch);
        self.update_release_branch(owner, repo, &branch_ref, commit_sha)?;

        let title = format!("chore(release): {}", prepared.tag);
        let notes = report.notes.clone().unwrap_or_default();
        let body = format!(
            "Automated release update for `{}`.\n\nThis PR updates the package version from `{}` to `{}`. Merging it into `{}` allows the release workflow to publish the tag and GitHub release.\n\n{}\n\n<!-- automated-release-branch: {} -->",
            prepared.tag,
            report.current_version,
            prepared.next_version,
            prepared.branch,
            notes,
            options.release_branch,
        );
        let pull_request = self.upsert_release_pull_request(
            owner,
            repo,
            &options.release_branch,
            &prepared.branch,
            &title,
            &body,
            report,
        )?;
        report.pull_request_number = Some(pull_request.number);
        report.pull_request_url = Some(pull_request.url);
        report.release_branch = Some(options.release_branch.clone());
        Ok(())
    }

    fn update_release_branch(
        &self,
        owner: &str,
        repo: &str,
        branch_ref: &str,
        commit_sha: &str,
    ) -> Result<()> {
        if self.github.reference_sha(owner, repo, branch_ref)?.is_some() {
            self.github.update_ref(owner, repo, branch_ref, commit_sha, true)
        } else {
            self.github.create_ref(owner, repo, branch_ref, commit_sha)
        }
    }

    fn upsert_release_pull_request(
        &self,
        owner: &str,
        repo: &str,
        head: &str,
        base: &str,
        title: &str,
        body: &str,
        report: &mut ReleaseReport,
    ) -> Result<crate::github::PullRequestInfo> {
        let existing = self.github.find_open_pull_request(owner, repo, head, base)?;
        if let Some(existing) = existing {
            let updated =
                self.github.update_pull_request(owner, repo, existing.number, title, body)?;
            report.outcome = ReleaseOutcome::PullRequestUpdated;
            Ok(updated)
        } else {
            let created = self.github.create_pull_request(owner, repo, title, body, head, base)?;
            report.outcome = ReleaseOutcome::PullRequestCreated;
            Ok(created)
        }
    }

    fn build_commit(&self, options: &ReleaseOptions, prepared: &PreparedRelease) -> Result<String> {
        let owner = &options.owner;
        let repo = &options.repo;
        let repo_root = options.repo_root.canonicalize().with_context(|| {
            format!("failed to resolve repository root '{}'", options.repo_root.display())
        })?;

        let base_tree_sha = self.github.commit_tree_sha(owner, repo, &prepared.head_sha)?;
        let mut tree_entries = Vec::new();
        for update in &prepared.plan.file_updates {
            let path = remote::relative_repository_path(&repo_root, &update.file)?;
            let blob_sha = self.github.create_blob(owner, repo, &update.updated_content)?;
            tree_entries.push(TreeEntry { path, sha: blob_sha });
        }
        let tree_sha = self.github.create_tree(owner, repo, &base_tree_sha, &tree_entries)?;

        let message =
            options.commit_message.replace("{version}", &prepared.next_version.to_string());
        self.github.create_commit(owner, repo, &message, &tree_sha, &prepared.head_sha)
    }

    fn finalize(
        &self,
        options: &ReleaseOptions,
        prepared: &PreparedRelease,
        commit_sha: &str,
        report: &mut ReleaseReport,
    ) -> Result<()> {
        let owner = &options.owner;
        let repo = &options.repo;
        let tag_target = match options.tag_style {
            TagStyle::Annotated => self.github.create_annotated_tag(
                owner,
                repo,
                &prepared.tag,
                &format!("Release {}", prepared.tag),
                commit_sha,
            )?,
            TagStyle::Lightweight => commit_sha.to_owned(),
        };
        self.github.create_ref(owner, repo, &format!("tags/{}", prepared.tag), &tag_target)?;

        if options.update_major_alias {
            let alias = format!("{}{}", options.tag_prefix, prepared.next_version.major);
            let alias_ref = format!("tags/{alias}");
            if self.github.reference_sha(owner, repo, &alias_ref)?.is_some() {
                self.github.update_ref(owner, repo, &alias_ref, commit_sha, true)?;
            } else {
                self.github.create_ref(owner, repo, &alias_ref, commit_sha)?;
            }
            report.major_alias = Some(alias);
        }

        let notes = report.notes.clone().unwrap_or_default();
        let release = self.github.create_release(
            owner,
            repo,
            &prepared.tag,
            &format!("Release {}", prepared.tag),
            &notes,
            commit_sha,
        )?;
        report.release_url = Some(release.url);
        report.outcome = ReleaseOutcome::Released;
        Ok(())
    }
}

fn initial_report(analysis: &Analysis, bump: Option<BumpLevel>) -> ReleaseReport {
    ReleaseReport {
        outcome: ReleaseOutcome::SkippedNoReleasableChanges,
        current_version: analysis.current_version.clone(),
        next_version: None,
        bump,
        tag: None,
        major_alias: None,
        commit_sha: None,
        release_url: None,
        pull_request_number: None,
        pull_request_url: None,
        release_branch: None,
        notes: None,
        commits_analyzed: analysis.commits.len(),
        commit_range_truncated: analysis.truncated,
        files_updated: Vec::new(),
    }
}

fn validate_release_branch(branch: &str) -> Result<()> {
    if branch != AUTOMATED_RELEASE_BRANCH_PREFIX
        && !branch.starts_with(&format!("{AUTOMATED_RELEASE_BRANCH_PREFIX}/"))
    {
        anyhow::bail!(
            "automated release branch '{branch}' must use the reserved '{AUTOMATED_RELEASE_BRANCH_PREFIX}/' prefix"
        );
    }
    Ok(())
}

// Tests live in a sibling file to keep this module within the repository's
// file-size lint budget; they remain `super::`-scoped unit tests.
#[cfg(test)]
#[path = "release_tests.rs"]
#[allow(clippy::significant_drop_tightening)]
mod tests;