summaryrefslogtreecommitdiffstats
path: root/xtask/src/release.rs
blob: b53c838480ad53dec91ddeb7be324e3222e32207 (plain)
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
use std::process::{Command, Stdio};

use anyhow::Result;
use clap::{Args, Subcommand};
use semver::Version;

use self::bump::{Bump, Level};

mod bump;

#[derive(Debug, Clone, Args)]
pub struct Release {
    #[command(subcommand)]
    step: Option<Step>,

    /// Level of version bump version.
    #[arg(global = true, required = false)]
    level: bump::Level,

    /// Options passed to git commit.
    #[arg(global = true, last = true)]
    git_commit_args: Vec<String>,
}

impl Release {
    pub fn run(self) -> Result<()> {
        match self.step {
            Some(step) => step.run(),
            None => {
                let bump = Step::bump(self.level)?;

                println!("Bumped version: {bump}");

                Ok(())
            }
        }
    }
}

#[derive(Debug, Clone, Subcommand)]
pub enum Step {
    /// Bump version in package files and commit changes.
    Bump {
        #[arg(from_global)]
        level: bump::Level,
    },

    /// Make a release commit.
    Commit {
        #[arg(from_global)]
        git_commit_args: Vec<String>,
    },

    /// Create git tag for release.
    Tag {
        #[arg(from_global)]
        level: bump::Level,
    },
}

impl Step {
    pub fn run(self) -> Result<()> {
        match self {
            Step::Bump { level } => {
                let bump = Self::bump(level)?;
                println!("Bumped version: {bump}");
            }
            Step::Commit { git_commit_args } => Self::commit(git_commit_args)?,
            Step::Tag { level } => {
                let stdout = Command::new("git")
                    .arg("describe")
                    .arg("--abbrev=0")
                    .output()?
                    .stdout;

                let prev = std::str::from_utf8(&stdout)?.parse()?;
                let next = level.bump(&prev);
                Self::tag(prev, next)?;
            }
        };

        Ok(())
    }

    pub fn bump(level: Level) -> Result<Bump> {
        let mut bump = Bump::from(level);

        bump.bump_file("./Cargo.toml", bump::replace_cargo)?;
        bump.bump_file("./README.md", bump::replace)?;
        bump.bump_file("./pkg/archlinux/projectr/PKGBUILD", bump::replace)?;
        bump.bump_file("./pkg/archlinux/projectr-bin/PKGBUILD", bump::replace)?;
        bump.bump_file("./pkg/archlinux/projectr-git/PKGBUILD", |buf, _| {
            let stdout = std::process::Command::new("git")
                .arg("describe")
                .arg("--long")
                .arg("--abbrev=7")
                .output()?
                .stdout;

            let pkgver = std::str::from_utf8(&stdout)?
                .trim()
                .trim_start_matches('v')
                .replacen("-g", ".g", 1)
                .replacen('-', "-r", 1)
                .replace('-', ".");

            if let Some(from) = buf.lines().find(|l| l.starts_with("pkgver=")) {
                Ok(buf.replace(from, &format!("pkgver={pkgver}")))
            } else {
                Ok(buf)
            }
        })?;

        bump.bump_file("./CHANGELOG.md", |buf, Bump { version: _, next }| {
            let date = chrono::Utc::now().format("%Y-%m-%d");
            Ok(buf
                .replace(
                    "## [Unreleased]",
                    &format!(
                        "## [Unreleased]\n\n\
                        ## [{next}] - {date}"
                    ),
                )
                .replace(
                    "[Unreleased]: https://git.sr.ht/~tobyvin/projectr/log/HEAD",
                    &format!(
                        "[Unreleased]: https://git.sr.ht/~tobyvin/projectr/log/HEAD\n\
                        [{next}]: https://git.sr.ht/~tobyvin/projectr/log/v{next}"
                    ),
                ))
        })?;

        Ok(bump)
    }

    pub fn commit(git_commit_args: Vec<String>) -> Result<()> {
        let git_commit = Command::new("git")
            .arg("commit")
            .args(git_commit_args)
            .status()?;

        anyhow::ensure!(git_commit.success(), "Failed to commit changes");

        Ok(())
    }

    pub fn tag(from: Version, to: Version) -> Result<String> {
        let tag_name = format!("v{}", to);

        let shortlog_child = Command::new("git")
            .arg("shortlog")
            .arg(format!("v{}..HEAD", from))
            .arg("--abbrev=7")
            .stdout(Stdio::piped())
            .spawn()?;

        let git_commit = Command::new("git")
            .arg("tag")
            .arg("-s")
            .arg(&tag_name)
            .arg("--file")
            .arg("-")
            .stdin(Stdio::from(shortlog_child.stdout.unwrap())) // Pipe through.
            .status()?;

        anyhow::ensure!(git_commit.success(), "Failed to commit changes");

        Ok(tag_name)
    }
}