Skip to content
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
23 changes: 19 additions & 4 deletions src/hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,21 @@ impl Hook {
format!("proofline hook run {} \"$@\"", self.name())
}

/// `line()` guarded as `script()` guards it, to paste among another tool's
/// commands: without `exec` or `exit 0`, so the commands after it still run.
fn snippet(self) -> String {
let (name, action) = (self.name(), self.action());
format!(
"if command -v proofline >/dev/null 2>&1; then\n\
\x20 {} || exit $?\n\
else\n\
\x20 echo 'proofline is not on PATH, so Proofline did not review this {action}.' >&2\n\
\x20 if [ \"$(git config --get proofline.hook.{name}.onIncomplete)\" = block ]; then exit 1; fi\n\
fi",
self.line()
)
}

fn script(self) -> String {
let (name, action) = (self.name(), self.action());
format!(
Expand Down Expand Up @@ -155,10 +170,10 @@ pub(crate) async fn manage(args: HooksArgs) -> anyhow::Result<()> {
if let Some(path) = git::config(here, "core.hooksPath").await? {
for hook in selection.hooks() {
say(&format!(
"core.hooksPath is {}, so nothing was written. Add this line to its {} hook: {}",
"core.hooksPath is {}, so nothing was written. Add this to its {} hook:\n{}",
one_line(&path),
hook.name(),
hook.line()
hook.snippet()
));
}
return Ok(());
Expand Down Expand Up @@ -188,9 +203,9 @@ async fn install(dir: &Path, hook: Hook) -> anyhow::Result<()> {
path.display()
)),
Ok(_) => say(&format!(
"{} already exists, so it was left unchanged. Add this line to it: {}",
"{} already exists, so it was left unchanged. Add this to it:\n{}",
path.display(),
hook.line()
hook.snippet()
)),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
write_executable(&path, &script).await?;
Expand Down
98 changes: 98 additions & 0 deletions tests/hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,18 @@ impl Checkout {
self.git(&["rev-parse", "HEAD"]).await
}

async fn commit_on_path(&self, origin: &str, path: &std::ffi::OsStr) -> Output {
let mut command = Command::new("git");
command
.args(["commit", "-qm", "change"])
.env("PATH", path)
.env("PROOFLINE_BASE_URL", origin)
.env("PROOFLINE_ORGANIZATION_ID", ORG)
.env("PROOFLINE_TOKEN", TOKEN);
self.environment(&mut command);
command.output().await.unwrap()
}

async fn proofline(&self, origin: &str, args: &[&str], stdin: &str) -> Output {
let mut command = Command::new(env!("CARGO_BIN_EXE_proofline"));
command
Expand Down Expand Up @@ -316,6 +328,7 @@ async fn install_writes_only_its_own_scripts_and_uninstall_removes_only_them() {
.proofline(unused, &["hooks", "install", "--pre-push"], "")
.await;
assert!(stderr(&install).contains("proofline hook run pre-push \"$@\""));
assert!(stderr(&install).contains("if command -v proofline"));
let uninstall = checkout
.proofline(unused, &["hooks", "uninstall"], "")
.await;
Expand All @@ -328,10 +341,95 @@ async fn install_writes_only_its_own_scripts_and_uninstall_removes_only_them() {
let husky = checkout.proofline(unused, &["hooks", "install"], "").await;
assert!(husky.status.success(), "{}", stderr(&husky));
assert!(stderr(&husky).contains("proofline hook run pre-commit \"$@\""));
assert!(stderr(&husky).contains("if command -v proofline"));
assert!(!checkout.root().join(".husky").exists());
assert_eq!(read(&checkout.hook("pre-commit")), None);
}

/// A hooks path is committed, so its hook also runs where `proofline` is not on
/// PATH. Pasted among the hook's other commands, the advice applies the hook's
/// `onIncomplete` there, as the script `hooks install` writes does.
#[tokio::test]
async fn the_advice_for_a_hooks_path_applies_the_policy_when_proofline_is_not_on_path() {
let checkout = Checkout::new().await;
checkout.git(&["config", "core.hooksPath", ".husky"]).await;
let unused = "http://127.0.0.1:9";
let install = checkout
.proofline(unused, &["hooks", "install", "--pre-commit"], "")
.await;
assert!(install.status.success(), "{}", stderr(&install));
let text = stderr(&install);
let (_, advice) = text.split_once("hook:").expect(&text);
let advice = advice.trim();
let origin = serve(Uploads::default(), "SERIOUS", false).await;
let bin = Path::new(env!("CARGO_BIN_EXE_proofline")).parent().unwrap();
let ran = checkout.root().join(".git/ran");
tokio::fs::create_dir_all(checkout.root().join(".husky"))
.await
.unwrap();
// Ahead of another command, and last under `sh -e`, as Husky runs hooks.
let layouts = [
(format!("#!/bin/sh\n{advice}\necho ran > .git/ran\n"), true),
(format!("#!/bin/sh\nset -e\n{advice}\n"), false),
];
let mut change = 0;
for (hook, ends_in_command) in &layouts {
write_hook(&checkout.root().join(".husky/pre-commit"), hook);
for on_path in [false, true] {
for policy in ["warn", "block"] {
for key in ["mode", "onIncomplete"] {
let key = format!("proofline.hook.pre-commit.{key}");
checkout.git(&["config", &key, policy]).await;
}
change += 1;
let text = format!("fn main() {{ change({change}) }}\n");
tokio::fs::write(checkout.root().join("orders.rs"), text)
.await
.unwrap();
checkout.git(&["add", "orders.rs"]).await;
let _ = tokio::fs::remove_file(&ran).await;
let head = checkout.git(&["rev-parse", "HEAD"]).await;

let output = checkout
.commit_on_path(&origin, &path_without_proofline(on_path.then_some(bin)))
.await;
let case = format!("{hook:?}, on PATH: {on_path}, {policy}: {output:?}");
let committed = checkout.git(&["rev-parse", "HEAD"]).await != head;
// A missing Proofline applies `onIncomplete`; a present one its
// own exit, here `mode` over a SERIOUS finding.
assert_eq!(committed, policy == "warn", "{case}");
if *ends_in_command {
assert_eq!(ran.exists(), committed, "{case}");
}
assert_eq!(
stderr(&output).contains("proofline is not on PATH"),
!on_path,
"{case}"
);
}
}
}
}

/// The inherited PATH without any directory that holds `proofline`, after
/// `first` when given.
fn path_without_proofline(first: Option<&Path>) -> std::ffi::OsString {
let name = format!("proofline{}", std::env::consts::EXE_SUFFIX);
let inherited = std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())
.filter(|dir| !dir.join(&name).exists())
.collect::<Vec<_>>();
std::env::join_paths(first.map(Path::to_path_buf).into_iter().chain(inherited)).unwrap()
}

fn write_hook(path: &Path, text: &str) {
std::fs::write(path, text).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
}
}

#[tokio::test]
async fn the_exit_policy_blocks_only_on_request_and_never_reads_a_gap_as_clean() {
let checkout = Checkout::new().await;
Expand Down