Skip to content

Commit

Permalink
fix: correctly identify empty repository when commiting
Browse files Browse the repository at this point in the history
The `is_empty` function exposed by libgit2 requires the default branch to be
"master". If a repository is created with a default branch not named master `is_empty`
will return false even when the repository is empty.

The fix is simply to try and access the HEAD of the repository. If the head
cant be accessed it means that the repository is still empty.

Closes #145
  • Loading branch information
Zshoham authored and oknozor committed Jan 26, 2022
1 parent cd847de commit c442f07
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
1 change: 1 addition & 0 deletions cog.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,5 @@ authors = [
{ signature = "Clément Poissonnier", username = "cpoissonnier" },
{ signature = "Luke Hsiao", username = "lukehsiao" },
{ signature = "Caleb Maclennan", username = "alerque" },
{ signature = "Zshoham", username = "Zshoham" }
]
21 changes: 20 additions & 1 deletion src/git/commit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ impl Repository {
let sig = self.0.signature()?;
let tree_id = self.0.index()?.write_tree()?;
let tree = self.0.find_tree(tree_id)?;
let is_empty = self.0.is_empty()?;
let is_empty = self.0.head().is_err();
let has_delta = self.get_diff(false).is_some();

if !is_empty && has_delta {
Expand Down Expand Up @@ -62,6 +62,25 @@ mod test {
Ok(())
}

#[sealed_test]
fn first_commit_custom_branch() {
// Arrange
run_cmd! {
git init -b main;
echo changes > file;
git add .;
}
.expect("could not initialize git repository");

let repo = Repository::open(".").expect("could not open git repository");

// Act
let oid = repo.commit("feat: a test commit");

// Assert
assert_that!(oid).is_ok();
}

#[sealed_test]
fn not_create_empty_commit() -> Result<()> {
// Arrange
Expand Down

0 comments on commit c442f07

Please sign in to comment.