Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Feature post release hook #438

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ pub struct Config {
pub pre_release_replacements: Option<Vec<Replace>>,
pub post_release_replacements: Option<Vec<Replace>>,
pub pre_release_hook: Option<Command>,
pub post_release_hook: Option<Command>,
Person-93 marked this conversation as resolved.
Show resolved Hide resolved
pub tag_message: Option<String>,
pub tag_prefix: Option<String>,
pub tag_name: Option<String>,
Expand Down Expand Up @@ -77,6 +78,7 @@ impl Config {
pre_release_replacements: Some(empty.pre_release_replacements().to_vec()),
post_release_replacements: Some(empty.post_release_replacements().to_vec()),
pre_release_hook: empty.pre_release_hook().cloned(),
post_release_hook: empty.post_release_hook().cloned(),
tag_message: Some(empty.tag_message().to_owned()),
tag_prefix: None, // Skipping, its location dependent
tag_name: Some(empty.tag_name().to_owned()),
Expand Down Expand Up @@ -149,6 +151,9 @@ impl Config {
if let Some(pre_release_hook) = source.pre_release_hook.as_ref() {
self.pre_release_hook = Some(pre_release_hook.to_owned());
}
if let Some(post_release_hook) = source.post_release_hook.as_ref() {
self.post_release_hook = Some(post_release_hook.to_owned());
}
if let Some(tag_message) = source.tag_message.as_deref() {
self.tag_message = Some(tag_message.to_owned());
}
Expand Down Expand Up @@ -271,6 +276,10 @@ impl Config {
self.pre_release_hook.as_ref()
}

pub fn post_release_hook(&self) -> Option<&Command> {
self.post_release_hook.as_ref()
}

pub fn tag_message(&self) -> &str {
self.tag_message
.as_deref()
Expand Down
23 changes: 22 additions & 1 deletion src/release.rs
Original file line number Diff line number Diff line change
Expand Up @@ -662,7 +662,28 @@ fn release_packages<'m>(
}
}

// STEP 7: git push
// STEP 7: post-release hook
for pkg in pkgs {
if let (Some(post_rel_hook), Some(_)) =
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@epage, I think this if statement isn't checking the right thing. I don't know what it should be checking. Can you advise?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The tests are not doing a version bump and most of actions are only on version bump.

(pkg.config.post_release_hook(), pkg.version.as_ref())
{
let cwd = pkg.package_root;
let post_rel_hook = post_rel_hook.args();
log::debug!("Calling post-release hook: {:?}", post_rel_hook);
let envs = maplit::btreemap! {
OsStr::new("RELEASE_TAG") => OsStr::new(pkg.tag.as_ref().expect("post-release hook with no tag")),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OsStr::new("DRY_RUN") => OsStr::new(if dry_run { "true" } else { "false" }),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How come a lot of the pre-release variables were removed?

};
// we use dry_run environmental variable to run the script
// so here we set dry_run=false and always execute the command.
if !cmd::call_with_env(post_rel_hook, envs, cwd, false)? {
log::error!("Post release hook failed. Aborting. CHANGES NOT ROLLED BACK.",);
return Ok(107);
}
}
}

// STEP 8: git push
if ws_config.push() {
let mut shared_refs = HashSet::new();
for pkg in pkgs {
Expand Down
1 change: 1 addition & 0 deletions tests/post-release-hook/crate/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
target
7 changes: 7 additions & 0 deletions tests/post-release-hook/crate/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions tests/post-release-hook/crate/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[package]
name = "post-release-hook-crate"
version = "1.2.3"
edition = "2021"
publish = false
2 changes: 2 additions & 0 deletions tests/post-release-hook/crate/release.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
push = false
post-release-hook = ["cargo", "run"]
9 changes: 9 additions & 0 deletions tests/post-release-hook/crate/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
use std::env;

fn main() {
eprintln!("START_ENV_VARS");
for (key, value) in env::vars_os() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we ensure these are sorted, we can use snapboxs built-in snapshot testing

We'd just define the following and snapbox's asserter will take the ... and treat it as a multi-line wildcard.

START_ENV_VARS
...
DRY_RUN=true
...
RELEASE_TAG=post-release-hook-ws-a-v42.42.42
...
END_ENV_VARS

eprintln!("{}={}", key.to_string_lossy(), value.to_string_lossy());
}
eprintln!("END_ENV_VARS");
}
132 changes: 132 additions & 0 deletions tests/post-release-hook/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
use assert_fs::prelude::*;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd prefer this to be tests/post-release-hook.rs

use assert_fs::TempDir;
use maplit::hashset;
use std::collections::HashSet;
use std::env;
use std::fmt::Debug;
use std::path::Path;
use std::process::{Command, Stdio};
use std::str::Lines;

#[test]
fn krate() {
let root = Path::new("tests/post-release-hook/crate")
.canonicalize()
.unwrap();
let expected = hashset! {
EnvVar::new("RELEASE_TAG", "v1.2.3"),
EnvVar::new("DRY_RUN", "true"),
};
let output = run_cargo_release(root.as_path());
let mut output = output.lines();
let actual = read_env_var_dump(&mut output).expect("missing env var dump");
assert!(
actual.is_superset(&expected),
"not all expected env vars are present and matching\n{expected:#?}"
);
}

#[test]
fn workspace() {
let ws_root = Path::new("tests/post-release-hook/workspace")
.canonicalize()
.unwrap();
let expected = vec![
hashset! {
EnvVar::new("RELEASE_TAG", "post-release-hook-ws-a-v42.42.42"),
EnvVar::new("DRY_RUN", "true"),
},
hashset! {
EnvVar::new("RELEASE_TAG", "post-release-hook-ws-b-v420.420.420"),
EnvVar::new("DRY_RUN", "true"),
},
];
let output = run_cargo_release(ws_root.as_path());
let mut output = output.lines();
let mut actual = Vec::new();
while let Some(vars) = read_env_var_dump(&mut output) {
actual.push(vars);
}
for expected in expected {
assert!(actual.iter().any(|actual| actual.is_superset(&expected)));
}
}

fn run_cargo_release(dir: &Path) -> String {
let temp = TempDir::new().unwrap();
temp.copy_from(dir, &["**"]).unwrap();

git(temp.path(), &["init"]);
git(temp.path(), &["add", "."]);
git(
temp.path(),
&["commit", "--message", "this is a commit message"],
);

let mut cargo = env::var_os("CARGO").map_or_else(|| Command::new("cargo"), Command::new);
let output = cargo
.stderr(Stdio::piped())
.args(["run", "--manifest-path"])
.arg(Path::new(PROJECT_ROOT).join("Cargo.toml"))
.args(["--", "release", "-vv"])
.current_dir(&temp)
.spawn()
.unwrap()
.wait_with_output()
.unwrap();

temp.close().unwrap();
Comment on lines +55 to +78
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you have reusable fixture initialization, I'd recommend splitting that out into a dedicated function and have each test call cargo-release in its own way. This will make it easier to add new test cases in the future


if !output.status.success() {
panic!("cargo release exited with {}", output.status);
}
let output = String::from_utf8(output.stderr).unwrap();
eprintln!("{output}");
output
}
Comment on lines +55 to +86
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use snapbox::cmd::Command and snapbox::cmd::cargo_bin!


fn git(dir: &Path, args: &[&str]) {
assert!(Command::new("git")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

snapbox::cmd::Command might be a good option

.args(args)
.current_dir(dir)
.spawn()
.unwrap()
.wait()
.unwrap()
.success());
}

fn read_env_var_dump(lines: &mut Lines) -> Option<HashSet<EnvVar>> {
let mut variables = HashSet::new();
loop {
if lines.next()?.trim() == "START_ENV_VARS" {
break;
}
}
loop {
let line = lines.next().expect("missing end of env var dump").trim();
if line == "END_ENV_VARS" {
return Some(variables);
}

let (key, value) = line.split_once('=').unwrap();
variables.insert(EnvVar::new(key, value));
}
}

#[derive(Debug, Eq, PartialEq, Hash)]
struct EnvVar {
key: String,
value: String,
}

impl EnvVar {
fn new(key: &str, value: &str) -> Self {
Self {
key: key.to_owned(),
value: value.to_owned(),
}
}
}

const PROJECT_ROOT: &str = concat!(env!("CARGO_MANIFEST_DIR"));
1 change: 1 addition & 0 deletions tests/post-release-hook/workspace/.gitignore
11 changes: 11 additions & 0 deletions tests/post-release-hook/workspace/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions tests/post-release-hook/workspace/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[workspace]
members = ["a", "b"]
5 changes: 5 additions & 0 deletions tests/post-release-hook/workspace/a/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[package]
name = "post-release-hook-ws-a"
version = "42.42.42"
edition = "2021"
publish = false
1 change: 1 addition & 0 deletions tests/post-release-hook/workspace/a/src
5 changes: 5 additions & 0 deletions tests/post-release-hook/workspace/b/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[package]
name = "post-release-hook-ws-b"
version = "420.420.420"
edition = "2021"
publish = false
1 change: 1 addition & 0 deletions tests/post-release-hook/workspace/b/src
1 change: 1 addition & 0 deletions tests/post-release-hook/workspace/release.toml