#git-hook #hook #git #rustfmt #formatter #pre-commit

devx-pre-commit

Utilities for creating git pre-commit hooks useful in rust projects

6 releases (breaking)

0.5.0 Jun 4, 2021
0.4.0 May 28, 2021
0.3.1 Sep 22, 2020
0.3.0 Aug 29, 2020
0.1.0 Aug 16, 2020

#1652 in Development tools

Download history 3378/week @ 2024-01-04 4268/week @ 2024-01-11 4871/week @ 2024-01-18 3475/week @ 2024-01-25 2553/week @ 2024-02-01 3303/week @ 2024-02-08 3377/week @ 2024-02-15 3869/week @ 2024-02-22 4747/week @ 2024-02-29 3501/week @ 2024-03-07 4190/week @ 2024-03-14 3649/week @ 2024-03-21 3720/week @ 2024-03-28 4850/week @ 2024-04-04 3447/week @ 2024-04-11 4489/week @ 2024-04-18

17,148 downloads per month

MIT/Apache

38KB
543 lines

devx-pre-commit

devx-pre-commit provides utilities for creating git pre-commit hooks.

In particular, there are convenient APIs for

  • Efficiently running rustfmt on crates with staged rust source files
  • Installing the current binary to .git/hooks/pre-commit

See the crate-level docs for more info.


lib.rs:

devx-pre-commit provides utilities for creating git pre-commit hooks.

In particular, there are convenient APIs for

  • Efficiently running rustfmt on crates with staged rust source files
  • Installing the current binary to .git/hooks/pre-commit

This crate is meant to be used only in dev environment, preferably with cargo-xtask setup. By having something like the code bellow in xtask binary crate you will be able to run the following command to install the git pre-commit hook and never bother running cargo fmt manually again:

cargo xtask install-pre-commit-hook

ℹ️ Note: This assumes there is an alias in .cargo/config:

[alias]
xtask = "run --package xtask --bin xtask --"

Example dev cli:

use devx_pre_commit::{PreCommitContext, locate_project_root};
use anyhow::Result;
use std::{ffi::OsStr, path::PathBuf};

fn run_hook() -> Result<()> {
    let mut ctx = PreCommitContext::from_git_diff(locate_project_root()?)?;

    // Optionally filter out the files you don't want to format
    ctx.retain_staged_files(|path| {
        path.components().all(|it| it.as_os_str() != OsStr::new("generated"))
    });

    // Run `cargo fmt` against the crates with staged rust source files
    ctx.rustfmt()?;

    // Stage all the changes potenitally introduced by rustfmt
    // It is super-important to call this method at the end of the hook
    ctx.stage_new_changes()?;
    Ok(())
}

fn main() -> Result<()> {
    if let Some(true) = std::env::args().next().map(|it| it.contains("pre-commit")) {
        return run_hook();
    }
    match std::env::args().nth(1).expect("No args").as_str() {
        "install-pre-commit-hook" => {
            devx_pre_commit::install_self_as_hook(&locate_project_root()?)?;
        }
        _ => {
            eprintln!("Hi, this is a dev cli, here are the available commands...");
        }
    }
    Ok(())
}

Dependencies

~295KB