aboutsummaryrefslogtreecommitdiffstats
path: root/xtask/src/main.rs
blob: 76fca16ac1c640d1f035c83204be10dd41b7a5ba (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
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
//! See <https://github.com/matklad/cargo-xtask/>.
//!
//! This binary defines various auxiliary build commands, which are not
//! expressible with just `cargo`.
//!
//! This binary is integrated into the `cargo` command line by using an alias in
//! `.cargo/config`.

use std::path::{Path, PathBuf};
use std::{fs::File, process::Command};

use anyhow::{anyhow, bail, ensure, Context, Result};
use build_info::BuildInfo;
use bump::{Bump, Level};
use clap::{Parser, Subcommand};
use flate2::{write::GzEncoder, Compression};
use once_cell::sync::Lazy;
use semver::Version;
use tar::Builder;

mod bump;

const PKG_NAME: &str = "projectr";
const PKG_VER: &str = env!("CARGO_PKG_VERSION");
const PKG_INCLUDE: &[&str] = &[
    "bin/tmux-projectr",
    "CONTRIBUTING.md",
    "README.md",
    "LICENSE",
];

fn main() -> Result<()> {
    let cli = Cli::parse();

    match cli.command {
        Commands::OutDir => println!("{}", out_dir()?.display()),
        Commands::Version => match version(cli.pre_release) {
            Ok(v) => println!("{v}"),
            Err(_) => std::process::exit(1),
        },
        Commands::Dist => {
            let version = version(cli.pre_release)?;
            let targz = generate_tar_gz(version)?;
            println!("{}", targz.display());
        }
        Commands::Release { level } => {
            let Bump { prev, next } = release(level, cli.pre_release)?;

            println!("Bumped version: {prev} -> {next}");
            println!();
            println!("Create release commit:");
            println!("git commit -m 'chore: release projectr version {next}'");
            println!();
            println!("Create release tag:");
            println!("git shortlog v{prev}..HEAD | git tag -s v{next} --file -");
            println!();
            println!("Push refs:");
            println!("git push --follow-tags");
        }
    };

    Ok(())
}

#[derive(Debug, Clone, Parser)]
#[command(author, version, about)]
struct Cli {
    /// Disable version/git tag check and appends `-dev` to the version
    #[arg(short, long, global = true, required = false)]
    pre_release: bool,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Debug, Clone, Subcommand)]
enum Commands {
    /// Print the default value of OUT_DIR used by cargo when building the package.
    OutDir,

    /// Validate a git tag matching the package version exists and print version.
    Version,

    /// Generate distributable package.
    Dist,

    /// Automation for create a new release.
    Release {
        /// Level of version bump.
        #[arg(required = false)]
        level: bump::Level,
    },
}

fn version(pre_release: bool) -> Result<String> {
    use build_info::VersionControl::Git;

    let BuildInfo {
        version_control: Some(Git(git)),
        ..
    } = build_info() else {
        bail!("Failed to get version control info.");
    };

    if pre_release {
        Ok(format!("{PKG_VER}-dev"))
    } else if git.tags.contains(&format!("v{PKG_VER}")) {
        Ok(PKG_VER.to_owned())
    } else {
        Err(anyhow!("Failed to find git tag matching package version."))
    }
}

fn out_dir() -> Result<PathBuf> {
    RELEASE_DIR
        .join("build")
        .read_dir()
        .context("Failed to read build directory.")?
        .flatten()
        .filter_map(|d| {
            d.file_name()
                .to_str()?
                .starts_with(PKG_NAME)
                .then(|| d.path().join("invoked.timestamp"))
                .filter(|p| p.exists())
        })
        .reduce(|acc, path_buf| {
            std::cmp::max_by_key(path_buf, acc, |p| {
                p.metadata()
                    .and_then(|m| m.modified())
                    .unwrap_or(std::time::SystemTime::UNIX_EPOCH)
            })
        })
        .map(|p| p.with_file_name("out"))
        .filter(|o| o.exists())
        .context("Failed to find `out` directory for latest build")
}

fn generate_tar_gz(version: String) -> Result<PathBuf> {
    let target = build_info::format!("{}", $.target.triple);
    let dist_pkg = DIST_DIR.join(format!("{PKG_NAME}-v{version}-{target}.tar.gz"));

    let binary = build_binary()?;
    ensure!(binary.exists(), "Failed to find package binary",);

    let _ = std::fs::remove_dir_all(&*DIST_DIR);
    std::fs::create_dir_all(&*DIST_DIR)?;

    let tar_gz = File::create(&dist_pkg)?;
    let enc = GzEncoder::new(tar_gz, Compression::default());
    let mut tar = Builder::new(enc);

    tar.append_path_with_name(binary, PathBuf::from("bin").join(PKG_NAME))?;
    tar.append_dir_all(".", out_dir()?)?;
    PKG_INCLUDE.iter().try_for_each(|p| tar.append_path(p))?;

    tar.into_inner()?.finish()?;

    Ok(dist_pkg)
}

fn build_binary() -> Result<PathBuf> {
    let status = Command::new("cargo")
        .arg("build")
        .arg("--release")
        .arg(format!("--package={PKG_NAME}"))
        .status()
        .context("Failed to invoke `cargo build`")?;

    anyhow::ensure!(status.success(), "Cargo returned an error");

    let mut binary = RELEASE_DIR.join(PKG_NAME);
    if cfg!(windows) {
        binary.set_extension("exe");
    };

    if let Err(e) = Command::new("strip").arg(&binary).status() {
        eprintln!("Failed to strip the binary: {}", e)
    }

    Ok(binary)
}

pub fn release(level: Level, pre_release: bool) -> Result<Bump> {
    let prev = PKG_VER.parse().unwrap_or_else(|_| Version::new(0, 1, 0));
    let mut next = level.bump(&prev);

    if pre_release {
        next.pre = semver::Prerelease::new("dev")?
    }

    let bump = Bump { next, prev };

    bump.bump_file("./Cargo.toml", bump::cargo)?;
    bump.bump_file("./README.md", bump::replace)?;
    bump.bump_file("./CHANGELOG.md", bump::changelog)?;
    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", bump::vsc_pkgbuild)?;

    let cargo_update = Command::new("cargo")
        .arg("update")
        .arg("--workspace")
        .status()?;
    anyhow::ensure!(cargo_update.success(), "Failed to update cargo lockfile");

    let git_added = Command::new("git")
        .arg("add")
        .arg("./Cargo.lock")
        .status()?;
    anyhow::ensure!(git_added.success(), "Failed to add Cargo.lock to git");

    Ok(bump)
}

static PROJECT_ROOT: Lazy<PathBuf> = Lazy::new(|| {
    let dir = std::env::current_dir().unwrap_or_else(|_| {
        Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap()
            .to_path_buf()
    });

    dir.ancestors()
        .find(|p| p.join(".git").is_dir())
        .unwrap_or(&dir)
        .to_path_buf()
});
static DIST_DIR: Lazy<PathBuf> = Lazy::new(|| PROJECT_ROOT.join("target").join("dist"));
static RELEASE_DIR: Lazy<PathBuf> = Lazy::new(|| PROJECT_ROOT.join("target").join("release"));

build_info::build_info!(fn build_info);