Skip to content

Commit

Permalink
fix: don't allow non-bare repositories to be initialized into non-emp…
Browse files Browse the repository at this point in the history
…ty directories. (#450)
  • Loading branch information
Byron committed Oct 17, 2022
1 parent bc5e3e4 commit f869b22
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 21 deletions.
37 changes: 18 additions & 19 deletions git-repository/src/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,26 +118,25 @@ pub fn into(
Options { bare, fs_capabilities }: Options,
) -> Result<git_discover::repository::Path, Error> {
let mut dot_git = directory.into();
if fs::read_dir(&dot_git)
.or_else(|err| {
if err.kind() == std::io::ErrorKind::NotFound {
fs::create_dir(&dot_git).and_then(|_| fs::read_dir(&dot_git))
} else {
Err(err)
}
})
.map_err(|err| Error::IoOpen {
source: err,
path: dot_git.clone(),
})?
.count()
!= 0
{
return Err(Error::DirectoryNotEmpty { path: dot_git });
}

if bare {
if fs::read_dir(&dot_git)
.or_else(|err| {
if err.kind() == std::io::ErrorKind::NotFound {
fs::create_dir(&dot_git).and_then(|_| fs::read_dir(&dot_git))
} else {
Err(err)
}
})
.map_err(|err| Error::IoOpen {
source: err,
path: dot_git.clone(),
})?
.count()
!= 0
{
return Err(Error::DirectoryNotEmpty { path: dot_git });
}
} else {
if !bare {
dot_git.push(DOT_GIT_DIR);

if dot_git.is_dir() {
Expand Down
8 changes: 6 additions & 2 deletions git-repository/tests/init/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,15 @@ mod non_bare {
}

#[test]
fn init_into_non_empty_directory_is_allowed() -> crate::Result {
fn init_into_non_empty_directory_is_not_allowed() -> crate::Result {
let tmp = tempfile::tempdir()?;
std::fs::write(tmp.path().join("existing.txt"), b"I was here before you")?;

git_repository::init(tmp.path())?;
assert!(git_repository::init(tmp.path())
.unwrap_err()
.to_string()
.starts_with("Refusing to initialize the non-empty directory as"));

Ok(())
}
}

0 comments on commit f869b22

Please sign in to comment.