diff options
Diffstat (limited to 'xtask/src/pre_commit.rs')
-rw-r--r-- | xtask/src/pre_commit.rs | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/xtask/src/pre_commit.rs b/xtask/src/pre_commit.rs new file mode 100644 index 000000000..7984ba963 --- /dev/null +++ b/xtask/src/pre_commit.rs | |||
@@ -0,0 +1,36 @@ | |||
1 | //! pre-commit hook for code formatting. | ||
2 | |||
3 | use std::{fs, path::PathBuf}; | ||
4 | |||
5 | use anyhow::{bail, Result}; | ||
6 | |||
7 | use crate::{project_root, run, run_rustfmt, run_with_output, Mode}; | ||
8 | |||
9 | // FIXME: if there are changed `.ts` files, also reformat TypeScript (by | ||
10 | // shelling out to `npm fmt`). | ||
11 | pub fn run_hook() -> Result<()> { | ||
12 | run_rustfmt(Mode::Overwrite)?; | ||
13 | |||
14 | let diff = run_with_output("git diff --diff-filter=MAR --name-only --cached", ".")?; | ||
15 | |||
16 | let root = project_root(); | ||
17 | for line in String::from_utf8(diff.stdout)?.lines() { | ||
18 | run(&format!("git update-index --add {}", root.join(line).to_string_lossy()), ".")?; | ||
19 | } | ||
20 | |||
21 | Ok(()) | ||
22 | } | ||
23 | |||
24 | pub fn install_hook() -> Result<()> { | ||
25 | let hook_path: PathBuf = | ||
26 | format!("./.git/hooks/pre-commit{}", std::env::consts::EXE_SUFFIX).into(); | ||
27 | |||
28 | if hook_path.exists() { | ||
29 | bail!("Git hook already created"); | ||
30 | } | ||
31 | |||
32 | let me = std::env::current_exe()?; | ||
33 | fs::copy(me, hook_path)?; | ||
34 | |||
35 | Ok(()) | ||
36 | } | ||