git2-rs
git2-rs copied to clipboard
Repository::is_empty() gives wrong answer for non-master initial branch
Summary
After initializing Git repository using a different initial branch name than master
, the function git2::Repository::is_empty()
will return false
, even though there are no commits in any branch.
Steps to reproduce
// src/main.rs
use std::path::Path;
use std::process::{Command, Stdio};
fn main() {
check_emptiness("main"); // will print repo is not empty
check_emptiness("master"); // will print repo is empty
}
fn check_emptiness(branch: &str) {
let dir = Path::new("/tmp/git2_test_dir").join(branch);
if dir.exists() {
std::fs::remove_dir_all(&dir).unwrap();
}
std::fs::create_dir_all(&dir).unwrap();
run_command(&["git", "init", "--initial-branch", branch], &dir);
let repo = git2::Repository::open(dir).unwrap();
println!("is repo empty for branch {}? {}", branch, repo.is_empty().unwrap());
let mut revision_walk = repo.revwalk().unwrap();
revision_walk.push_head().unwrap_err();
}
fn run_command(command_parts: &[&str], dir: &Path)
{
let mut command = Command::new(command_parts[0]);
command.args(&command_parts[1..]).current_dir(&dir).stdout(Stdio::null());
let status = command.status().unwrap();
assert!(status.success(), "Exit code was: {:?}", status.code());
}
// Cargo.toml
[package]
name = "git2-empty-repository-test"
version = "0.1.0"
edition = "2018"
[dependencies]
git2 = "0.13.17"
Configuration
OS: Manjaro 20.2.1 Git: 2.30.0 git2: 0.13.17 rustc: 1.49.0
Notes
If you try to initialize Git repository with just git init
, it will print a following warning:
hint: Using 'master' as the name for the initial branch. This default branch name
hint: is subject to change. To configure the initial branch name to use in all
hint: of your new repositories, which will suppress this warning, call:
hint:
hint: git config --global init.defaultBranch <name>
hint:
hint: Names commonly chosen instead of 'master' are 'main', 'trunk' and
hint: 'development'. The just-created branch can be renamed via this command:
hint:
hint: git branch -m <name>
This sounds like an issue that should be filed at https://github.com/libgit2/libgit2/issues. It looks like git_repository_is_empty
checks the init.defaultbranch
config value, which is not set when using the --initial-branch
option.