Skip to content

Run git-hooks more correctly #2483

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

Merged
merged 64 commits into from
Apr 15, 2025
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
64 commits
Select commit Hold shift + click to select a range
2d90eb5
use /bin/sh for git-hooks
Joshix-1 Jan 15, 2025
6a4b9d6
update CHANGELOG.md
Joshix-1 Jan 15, 2025
8571406
fix escape bugs in hooks
Joshix-1 Jan 15, 2025
cba5142
simplify logic for running hooks on non-windows platforms
Joshix-1 Jan 15, 2025
7f70d52
invert if check
Joshix-1 Jan 15, 2025
bd61ad8
debug_assert
Joshix-1 Jan 15, 2025
c257d02
update CHANGELOG.md
Joshix-1 Jan 15, 2025
cde4bc1
Merge remote-tracking branch 'extrawurst/master' into git-hooks-shell…
Joshix-1 Mar 25, 2025
816e175
simplify build_shell_script_execution_command
Joshix-1 Mar 25, 2025
da71107
create build_shell_script_execution_command
Joshix-1 Mar 25, 2025
2b6d295
small refactorings
Joshix-1 Mar 25, 2025
ce9fc0e
add line
Joshix-1 Mar 25, 2025
04a31eb
execute hoooks directly and fallback to using sh
Joshix-1 Mar 25, 2025
8ba997d
rename function
Joshix-1 Mar 25, 2025
4f65b81
update commend
Joshix-1 Mar 25, 2025
58afb49
sh_command
Joshix-1 Mar 25, 2025
a6e71d3
refactor
Joshix-1 Mar 25, 2025
b79e5ce
name const
Joshix-1 Mar 25, 2025
177d9d8
update CHANGELOG
Joshix-1 Mar 25, 2025
e5e562e
add new test
Joshix-1 Mar 25, 2025
f397799
deindent
Joshix-1 Mar 25, 2025
dbd8fee
fix is_executable
Joshix-1 Mar 25, 2025
7c8b6bc
debug print
Joshix-1 Mar 25, 2025
1370a14
handle ENOEXEC
Joshix-1 Mar 25, 2025
65c5997
add debug print
Joshix-1 Mar 25, 2025
102e7fd
remove debug print
Joshix-1 Mar 25, 2025
26b8871
set different env var
Joshix-1 Mar 25, 2025
5327f4a
Revert "set different env var"
Joshix-1 Mar 25, 2025
11da04a
remove ansi clear from output
Joshix-1 Mar 25, 2025
cfdb196
fix typo
Joshix-1 Mar 25, 2025
08dce84
move ansi escape hack to impl From<git2_hooks::HookResult> for HookRe…
Joshix-1 Mar 25, 2025
b37817d
fix ansi clear
Joshix-1 Mar 25, 2025
a7fe9cb
try strip different
Joshix-1 Mar 25, 2025
a4e2f54
more trimming
Joshix-1 Mar 25, 2025
d25efdc
Revert "more trimming"
Joshix-1 Mar 25, 2025
caf83c8
weird hack only on windows
Joshix-1 Mar 25, 2025
f91aa10
revert stuff
Joshix-1 Mar 25, 2025
adeb50d
trim_ascii_end
Joshix-1 Mar 25, 2025
c5c1fe9
format assert
Joshix-1 Mar 26, 2025
c0a8996
move truncation
Joshix-1 Mar 26, 2025
3e4b3c2
debug
Joshix-1 Mar 26, 2025
4601892
Merge remote-tracking branch 'extrawurst/master' into git-hooks-shell…
Joshix-1 Mar 26, 2025
db60ac3
fix test
Joshix-1 Mar 26, 2025
5a1dfbd
fix windows
Joshix-1 Mar 26, 2025
94b9dc7
add missing argument
Joshix-1 Mar 26, 2025
f9ff366
add argument
Joshix-1 Mar 26, 2025
38a3484
remove hacks
Joshix-1 Mar 26, 2025
7b4903b
correctly escape single-quote if utf8
Joshix-1 Mar 26, 2025
0b3d2c0
less indentation
Joshix-1 Mar 26, 2025
a0b7503
test if string contains single-quote
Joshix-1 Mar 27, 2025
f58f550
replace single-quotes in string
Joshix-1 Mar 27, 2025
9b8a87e
add test with invalid utf8
Joshix-1 Mar 27, 2025
b54711f
Merge remote-tracking branch 'extrawurst/master' into git-hooks-shell…
Joshix-1 Mar 27, 2025
418d016
fix tests with invalid utf8
Joshix-1 Mar 27, 2025
f2d41fd
fix generating invalid utf8 ostring
Joshix-1 Mar 27, 2025
40179d5
remove dead_code
Joshix-1 Mar 27, 2025
16e150e
dereference
Joshix-1 Mar 27, 2025
2796f8f
try different string on windows
Joshix-1 Mar 27, 2025
ee8fcf9
only valid unicode paths are accepted on windows
Joshix-1 Mar 27, 2025
eaad1f3
remove unused import
Joshix-1 Mar 27, 2025
48922ce
revert returning error
Joshix-1 Mar 30, 2025
9649e84
test if string contains single-quote
Joshix-1 Mar 27, 2025
c74e762
make clippy happy
Joshix-1 Mar 30, 2025
b3cf0ae
Merge remote-tracking branch 'extrawurst/master' into git-hooks-shell…
Joshix-1 Apr 15, 2025
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## Unreleased
* execute git-hooks without shell (on *nix) [[@Joshix](https://github.com/Joshix-1)] ([#2483](https://github.com/extrawurst/gitui/pull/2483))

## [0.27.0] - 2024-01-14

Expand Down
13 changes: 10 additions & 3 deletions asyncgit/src/sync/hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,15 @@ pub fn hooks_prepare_commit_msg(

#[cfg(test)]
mod tests {
use git2::Repository;
use tempfile::TempDir;

use super::*;
use crate::sync::tests::repo_init;
use crate::sync::tests::repo_init_with_prefix;

fn repo_init() -> Result<(TempDir, Repository)> {
repo_init_with_prefix("gitui $# ")
}

#[test]
fn test_post_commit_hook_reject_in_subfolder() {
Expand Down Expand Up @@ -120,7 +127,7 @@ mod tests {
crate::sync::utils::repo_work_dir(repo_path).unwrap();

let hook = b"#!/bin/sh
echo $(pwd)
echo \"$(pwd)\"
exit 1
";

Expand All @@ -146,7 +153,7 @@ mod tests {
let root = repo.path().parent().unwrap();

let hook = b"#!/bin/sh
echo 'msg' > $1
echo 'msg' > \"$1\"
echo 'rejected'
exit 1
";
Expand Down
10 changes: 9 additions & 1 deletion asyncgit/src/sync/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,11 +144,19 @@ pub mod tests {

///
pub fn repo_init() -> Result<(TempDir, Repository)> {
repo_init_with_prefix("gitui")
}

///
#[inline]
pub fn repo_init_with_prefix(
prefix: &'static str,
) -> Result<(TempDir, Repository)> {
init_log();

sandbox_config_files();

let td = TempDir::new()?;
let td = TempDir::with_prefix(prefix)?;
let repo = Repository::init(td.path())?;
{
let mut config = repo.config()?;
Expand Down
112 changes: 62 additions & 50 deletions git2-hooks/src/hookspath.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use git2::Repository;
use crate::{error::Result, HookResult, HooksError};

use std::{
env,
ffi::OsStr,
path::{Path, PathBuf},
process::Command,
str::FromStr,
Expand Down Expand Up @@ -108,29 +108,45 @@ impl HookPaths {
/// see <https://git-scm.com/docs/githooks>
pub fn run_hook(&self, args: &[&str]) -> Result<HookResult> {
let hook = self.hook.clone();

let arg_str = format!("{:?} {}", hook, args.join(" "));
// Use -l to avoid "command not found" on Windows.
let bash_args =
vec!["-l".to_string(), "-c".to_string(), arg_str];

log::trace!("run hook '{:?}' in '{:?}'", hook, self.pwd);

let git_shell = find_bash_executable()
.or_else(find_default_unix_shell)
.unwrap_or_else(|| "bash".into());
let output = Command::new(git_shell)
.args(bash_args)
.with_no_window()
.current_dir(&self.pwd)
// This call forces Command to handle the Path environment correctly on windows,
// the specific env set here does not matter
// see https://github.com/rust-lang/rust/issues/37519
.env(
"DUMMY_ENV_TO_FIX_WINDOWS_CMD_RUNS",
"FixPathHandlingOnWindows",
let run_command = |command: &mut Command| {
command.current_dir(&self.pwd).with_no_window().output()
};
let output = if cfg!(windows) {
let command = {
let mut os_str = std::ffi::OsString::new();
os_str.push("'");
os_str.push(hook.as_os_str()); // TODO: this doesn't work if `hook` contains single-quotes
os_str.push("'");
os_str.push(" \"$@\"");
os_str
};
let shell_args = {
let mut shell_args = vec![
OsStr::new("-l"), // Use -l to avoid "command not found"
OsStr::new("-c"),
command.as_os_str(),
hook.as_os_str(),
];
shell_args.extend(args.iter().map(OsStr::new));
shell_args
};

run_command(
Command::new(sh_on_windows())
.args(shell_args)
// This call forces Command to handle the Path environment correctly on windows,
// the specific env set here does not matter
// see https://github.com/rust-lang/rust/issues/37519
.env(
"DUMMY_ENV_TO_FIX_WINDOWS_CMD_RUNS",
"FixPathHandlingOnWindows",
),
)
.output()?;
} else {
run_command(Command::new(&hook).args(args))
}?;

if output.status.success() {
Ok(HookResult::Ok { hook })
Expand All @@ -150,6 +166,30 @@ impl HookPaths {
}
}

/// Get the path to the sh.exe bundled with Git for Windows
fn sh_on_windows() -> PathBuf {
if cfg!(windows) {
Command::new("where.exe")
.arg("git")
.output()
.ok()
.map(|out| {
PathBuf::from(Into::<String>::into(
String::from_utf8_lossy(&out.stdout),
))
})
.as_deref()
.and_then(Path::parent)
.and_then(Path::parent)
.map(|p| p.join("usr/bin/sh.exe"))
.filter(|p| p.exists())
.unwrap_or_else(|| "sh".into())
} else {
debug_assert!(false, "should only be called on windows");
"sh".into()
}
}

#[cfg(unix)]
fn is_executable(path: &Path) -> bool {
use std::os::unix::fs::PermissionsExt;
Expand All @@ -168,40 +208,12 @@ fn is_executable(path: &Path) -> bool {
}

#[cfg(windows)]
/// windows does not consider bash scripts to be executable so we consider everything
/// windows does not consider shell scripts to be executable so we consider everything
/// to be executable (which is not far from the truth for windows platform.)
const fn is_executable(_: &Path) -> bool {
true
}

// Find bash.exe, and avoid finding wsl's bash.exe on Windows.
// None for non-Windows.
fn find_bash_executable() -> Option<PathBuf> {
if cfg!(windows) {
Command::new("where.exe")
.arg("git")
.output()
.ok()
.map(|out| {
PathBuf::from(Into::<String>::into(
String::from_utf8_lossy(&out.stdout),
))
})
.as_deref()
.and_then(Path::parent)
.and_then(Path::parent)
.map(|p| p.join("usr/bin/bash.exe"))
.filter(|p| p.exists())
} else {
None
}
}

// Find default shell on Unix-like OS.
fn find_default_unix_shell() -> Option<PathBuf> {
env::var_os("SHELL").map(PathBuf::from)
}

trait CommandExt {
/// The process is a console application that is being run without a
/// console window. Therefore, the console handle for the application is
Expand Down
10 changes: 5 additions & 5 deletions git2-hooks/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ exit 0

let hook = br#"#!/bin/sh
COMMIT_MSG="$(cat "$1")"
printf "$COMMIT_MSG" | sed 's/sth/shell_command/g' >"$1"
printf "$COMMIT_MSG" | sed 's/sth/shell_command/g' > "$1"
exit 0
"#;

Expand Down Expand Up @@ -499,7 +499,7 @@ sys.exit(1)
let (_td, repo) = repo_init();

let hook = b"#!/bin/sh
echo 'msg' > $1
echo 'msg' > \"$1\"
echo 'rejected'
exit 1
";
Expand All @@ -525,7 +525,7 @@ exit 1
let (_td, repo) = repo_init();

let hook = b"#!/bin/sh
echo 'msg' > $1
echo 'msg' > \"$1\"
exit 0
";

Expand Down Expand Up @@ -565,7 +565,7 @@ exit 0
let (_td, repo) = repo_init();

let hook = b"#!/bin/sh
echo msg:$2 > $1
echo \"msg:$2\" > \"$1\"
exit 0
";

Expand All @@ -589,7 +589,7 @@ exit 0
let (_td, repo) = repo_init();

let hook = b"#!/bin/sh
echo $2,$3 > $1
echo \"$2,$3\" > \"$1\"
echo 'rejected'
exit 2
";
Expand Down
Loading