Daniel A. White
Daniel A. White

Reputation: 190943

Skip commit if no files are changed in git2/libgit2

I'm using the git2 crate which wraps libgit2.

I'm adding files to the index whether or not they are changed to stage them for committing.

If there are no files changed in the repo, when I commit, I get an empty commit, that I'd like to avoid. I thought calling index.is_empty() would indicate no changes, but I have a count returned from index.len().

I'd be fine resetting the index or avoid adding files to the index if they are unchanged.

How can I avoid inserting an empty commit? I know the git CLI has support for this, and can disable it with --allow-empty.

Upvotes: 1

Views: 233

Answers (1)

Daniel A. White
Daniel A. White

Reputation: 190943

I can iterate through the index entries and look for ones that have not changed by calling status_file against the Repository

let repo: Repository = ...;
let index: Index = ...;
let changed_files = index
    .iter()
    .flat_map(|e| String::from_utf8(e.path))
    .map(|e| PathBuf::from(OsString::from(e)))
    .flat_map(|p| repo.status_file(&p))
    .any(|s| s != Status::CURRENT);

Upvotes: 1

Related Questions