pub struct PreCommitContext { /* private fields */ }
Expand description
Represents the API entrypoint of the git pre-commit hook. It carries the list of the staged files and the project root path. Note that staged file paths are all relative to the project root path.
Implementations§
Source§impl PreCommitContext
impl PreCommitContext
Sourcepub fn from_git_diff(project_root: impl Into<PathBuf>) -> Result<Self>
pub fn from_git_diff(project_root: impl Into<PathBuf>) -> Result<Self>
Creates the git pre-commit context acquiring the staged files via running
git diff
in project_root
.
The project_root
is expected to contain the .git
dir
(see locate_project_root
function for more on that).
The staged files are stored in PreCommitContext
as paths relative
to project_root
.
Sourcepub fn staged_files(&self) -> impl Iterator<Item = &Path>
pub fn staged_files(&self) -> impl Iterator<Item = &Path>
Returns an iterator over all the files staged for the commit.
Sourcepub fn retain_staged_files(&mut self, f: impl FnMut(&Path) -> bool)
pub fn retain_staged_files(&mut self, f: impl FnMut(&Path) -> bool)
Accepts a function predicate that accepts a relative path to the staged
file and returns false
if the given file should be removed from this
PreCommitContext
Sourcepub fn touched_crates(&self) -> HashSet<String>
pub fn touched_crates(&self) -> HashSet<String>
Returns the names of the crates that contain Self::staged_rust_files()
.
Warning: this heuristically looks for Cargo.toml
files and
searches for name = "
substring in them to get the crate name
(i.e. it doesn’t really parse them properly, but this works 99% of the
time and lets us save on a full-fledged toml parser dependency).
This heuristic may be relaxed in the future, and it shouldn’t be considered a
breaking change.
Sourcepub fn staged_rust_files(&self) -> impl Iterator<Item = &Path>
pub fn staged_rust_files(&self) -> impl Iterator<Item = &Path>
Returns an iterator over all staged files with .rs
extension.
Sourcepub fn rustfmt(&self) -> Result<()>
pub fn rustfmt(&self) -> Result<()>
Runs cargo fmt
against the Self::touched_crates()
Sourcepub fn stage_new_changes(&self) -> Result<()>
pub fn stage_new_changes(&self) -> Result<()>
Pushes the changes introduced to staged files in the working tree
to the git index. It is important to call this function once you’ve
modified some staged files (e.g. via Self::rustfmt()
)