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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
#[derive(Clone, Debug)]
pub struct Hooks {
    root: std::path::PathBuf,
}

impl Hooks {
    pub fn new(hook_root: impl Into<std::path::PathBuf>) -> Self {
        Self {
            root: hook_root.into(),
        }
    }

    pub fn with_repo(repo: &git2::Repository) -> Result<Self, git2::Error> {
        let config = repo.config()?;
        let root = config
            .get_path("core.hooksPath")
            .unwrap_or_else(|_| repo.path().join("hooks"));
        Ok(Self::new(root))
    }

    pub fn root(&self) -> &std::path::Path {
        &self.root
    }

    pub fn find_hook(&self, _repo: &git2::Repository, name: &str) -> Option<std::path::PathBuf> {
        let mut hook_path = self.root().join(name);
        if is_executable(&hook_path) {
            return Some(hook_path);
        }

        if !std::env::consts::EXE_SUFFIX.is_empty() {
            hook_path.set_extension(std::env::consts::EXE_SUFFIX);
            if is_executable(&hook_path) {
                return Some(hook_path);
            }
        }

        // Technically, we should check `advice.ignoredHook` and warn users if the hook is present
        // but not executable.  Supporting this in the future is why we accept `repo`.

        None
    }

    pub fn run_hook(
        &self,
        repo: &git2::Repository,
        name: &str,
        args: &[&str],
        stdin: Option<&[u8]>,
        env: &[(&str, &str)],
    ) -> Result<i32, std::io::Error> {
        let hook_path = if let Some(hook_path) = self.find_hook(repo, name) {
            hook_path
        } else {
            return Ok(0);
        };
        let bin_name = hook_path
            .file_name()
            .expect("find_hook always returns a bin name")
            .to_str()
            .expect("find_hook always returns a utf-8 bin name");

        let path = {
            let mut path_components: Vec<std::path::PathBuf> =
                vec![std::fs::canonicalize(self.root())?];
            if let Some(path) = std::env::var_os(std::ffi::OsStr::new("PATH")) {
                path_components.extend(std::env::split_paths(&path));
            }
            std::env::join_paths(path_components)
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?
        };

        let sh_path = crate::utils::git_sh().ok_or_else(|| {
            std::io::Error::new(std::io::ErrorKind::NotFound, "No `sh` for running hooks")
        })?;

        // From `githooks(5)`:
        // > Before Git invokes a hook, it changes its working directory to either $GIT_DIR in a bare
        // > repository or the root of the working tree in a non-bare repository. An exception are
        // > hooks triggered during a push (pre-receive, update, post-receive, post-update,
        // > push-to-checkout) which are always executed in $GIT_DIR.
        let cwd = if PUSH_HOOKS.contains(&name) {
            repo.path()
        } else {
            repo.workdir().unwrap_or_else(|| repo.path())
        };

        let mut cmd = std::process::Command::new(sh_path);
        cmd.arg("-c")
            .arg(format!("{} \"$@\"", bin_name))
            .arg(bin_name) // "$@" expands "$1" "$2" "$3" ... but we also must specify $0.
            .args(args)
            .env("PATH", path)
            .current_dir(cwd)
            // Technically, git maps stdout to stderr when running hooks
            .stdin(std::process::Stdio::piped());
        for (key, value) in env.iter().copied() {
            cmd.env(key, value);
        }
        let mut process = cmd.spawn()?;
        if let Some(stdin) = stdin {
            use std::io::Write;

            process.stdin.as_mut().unwrap().write_all(stdin)?;
        }
        let exit = process.wait()?;

        const SIGNAL_EXIT_CODE: i32 = 1;
        Ok(exit.code().unwrap_or(SIGNAL_EXIT_CODE))
    }

    /// Run `post-rewrite` hook as if called by `git rebase`
    ///
    /// The hook should be run after any automatic note copying (see "notes.rewrite.<command>" in
    /// git-config(1)) has happened, and thus has access to these notes.
    ///
    /// **changed_shas (old, new):**
    /// - For the squash and fixup operation, all commits that were squashed are listed as being rewritten to the squashed commit. This means
    ///   that there will be several lines sharing the same new-sha1.
    /// - The commits are must be listed in the order that they were processed by rebase.
    /// - `git` doesn't include entries for dropped commits
    pub fn run_post_rewrite_rebase(
        &self,
        repo: &git2::Repository,
        changed_oids: &[(git2::Oid, git2::Oid)],
    ) {
        let name = "post-rewrite";
        let command = "rebase";
        let args = [command];
        let mut stdin = String::new();
        for (old_oid, new_oid) in changed_oids {
            use std::fmt::Write;
            writeln!(stdin, "{} {}", old_oid, new_oid).expect("Always writeable");
        }

        match self.run_hook(repo, name, &args, Some(stdin.as_bytes()), &[]) {
            Ok(0) => {}
            Ok(code) => {
                log::trace!("Hook `{}` failed with code {}", name, code);
            }
            Err(err) => {
                log::trace!("Hook `{}` failed with {}", name, err);
            }
        }
    }

    /// Run `reference-transaction` hook to signal that all reference updates have been queued to the transaction.
    ///
    /// **changed_refs (old, new, name):**
    /// - `name` is the full name of the ref
    /// - `old` is zeroed out when force updating the reference regardless of its current value or
    ///   when the reference is to be created anew
    pub fn run_reference_transaction<'t>(
        &'t self,
        repo: &'t git2::Repository,
        changed_refs: &'t [(git2::Oid, git2::Oid, &'t str)],
    ) -> Result<ReferenceTransaction<'_>, std::io::Error> {
        self.run_reference_transaction_prepare(repo, changed_refs)?;

        Ok(ReferenceTransaction {
            hook: self,
            repo,
            changed_refs,
        })
    }

    /// Run `reference-transaction` hook to signal that all reference updates have been queued to the transaction.
    ///
    /// **changed_refs (old, new, name):**
    /// - `name` is the full name of the ref
    /// - `old` is zeroed out when force updating the reference regardless of its current value or
    ///   when the reference is to be created anew
    ///
    /// On success, call either
    /// - `run_reference_transaction_committed`
    /// - `run_reference_transaction_aborted`.
    ///
    /// On failure, the transaction is considered aborted
    pub fn run_reference_transaction_prepare(
        &self,
        repo: &git2::Repository,
        changed_refs: &[(git2::Oid, git2::Oid, &str)],
    ) -> Result<(), std::io::Error> {
        let name = "reference-transaction";
        let state = "prepare";
        let args = [state];
        let mut stdin = String::new();
        for (old_oid, new_oid, ref_name) in changed_refs {
            use std::fmt::Write;
            writeln!(stdin, "{} {} {}", old_oid, new_oid, ref_name).expect("Always writeable");
        }

        let code = self.run_hook(repo, name, &args, Some(stdin.as_bytes()), &[])?;
        if code == 0 {
            Ok(())
        } else {
            log::trace!("Hook `{}` failed with code {}", name, code);
            Err(std::io::Error::new(
                std::io::ErrorKind::Interrupted,
                format!("`{}` hook failed with code {}", name, code),
            ))
        }
    }

    /// Run `reference-transaction` hook to signal that all reference updates have been applied
    ///
    /// **changed_refs (old, new, name):**
    /// - `name` is the full name of the ref
    /// - `old` is zeroed out when force updating the reference regardless of its current value or
    ///   when the reference is to be created anew
    pub fn run_reference_transaction_committed(
        &self,
        repo: &git2::Repository,
        changed_refs: &[(git2::Oid, git2::Oid, &str)],
    ) {
        let name = "reference-transaction";
        let state = "committed";
        let args = [state];
        let mut stdin = String::new();
        for (old_oid, new_oid, ref_name) in changed_refs {
            use std::fmt::Write;
            writeln!(stdin, "{} {} {}", old_oid, new_oid, ref_name).expect("Always writeable");
        }

        match self.run_hook(repo, name, &args, Some(stdin.as_bytes()), &[]) {
            Ok(0) => {}
            Ok(code) => {
                log::trace!("Hook `{}` failed with code {}", name, code);
            }
            Err(err) => {
                log::trace!("Hook `{}` failed with {}", name, err);
            }
        }
    }

    /// Run `reference-transaction` hook to signal that no changes have been made
    ///
    /// **changed_refs (old, new, name):**
    /// - `name` is the full name of the ref
    /// - `old` is zeroed out when force updating the reference regardless of its current value or
    ///   when the reference is to be created anew
    pub fn run_reference_transaction_aborted(
        &self,
        repo: &git2::Repository,
        changed_refs: &[(git2::Oid, git2::Oid, &str)],
    ) {
        let name = "reference-transaction";
        let state = "aborted";
        let args = [state];
        let mut stdin = String::new();
        for (old_oid, new_oid, ref_name) in changed_refs {
            use std::fmt::Write;
            writeln!(stdin, "{} {} {}", old_oid, new_oid, ref_name).expect("Always writeable");
        }

        match self.run_hook(repo, name, &args, Some(stdin.as_bytes()), &[]) {
            Ok(0) => {}
            Ok(code) => {
                log::trace!("Hook `{}` failed with code {}", name, code);
            }
            Err(err) => {
                log::trace!("Hook `{}` failed with {}", name, err);
            }
        }
    }
}

pub struct ReferenceTransaction<'t> {
    hook: &'t Hooks,
    repo: &'t git2::Repository,
    changed_refs: &'t [(git2::Oid, git2::Oid, &'t str)],
}

impl<'t> ReferenceTransaction<'t> {
    pub fn committed(self) {
        let Self {
            hook,
            repo,
            changed_refs,
        } = self;
        hook.run_reference_transaction_committed(repo, changed_refs);
    }

    pub fn aborted(self) {
        let Self {
            hook,
            repo,
            changed_refs,
        } = self;
        hook.run_reference_transaction_aborted(repo, changed_refs);
    }
}

impl<'t> Drop for ReferenceTransaction<'t> {
    fn drop(&mut self) {
        self.hook
            .run_reference_transaction_aborted(self.repo, self.changed_refs);
    }
}

const PUSH_HOOKS: &[&str] = &[
    "pre-receive",
    "update",
    "post-receive",
    "post-update",
    "push-to-checkout",
];

#[cfg(unix)]
fn is_executable(path: &std::path::Path) -> bool {
    use std::os::unix::fs::PermissionsExt;

    let metadata = match path.metadata() {
        Ok(metadata) => metadata,
        Err(_) => return false,
    };
    let permissions = metadata.permissions();
    metadata.is_file() && permissions.mode() & 0o111 != 0
}

#[cfg(not(unix))]
fn is_executable(path: &std::path::Path) -> bool {
    path.is_file()
}