Skip to content

Commit

Permalink
feat: don't generate .cargo_vcs_info.json if git repro has no commit
Browse files Browse the repository at this point in the history
  • Loading branch information
linyihai committed Aug 8, 2024
1 parent ab4ab66 commit 37cda2d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 26 deletions.
25 changes: 14 additions & 11 deletions src/cargo/ops/cargo_package.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,7 @@ struct VcsInfo {

#[derive(Serialize)]
struct GitVcsInfo {
#[serde(skip_serializing_if = "Option::is_none")]
sha1: Option<String>,
sha1: String,
/// Indicate whether or not the Git worktree is dirty.
#[serde(skip_serializing_if = "std::ops::Not::not")]
dirty: bool,
Expand Down Expand Up @@ -744,10 +743,12 @@ fn check_repo_state(
.and_then(|p| p.to_str())
.unwrap_or("")
.replace("\\", "/");
return Ok(Some(VcsInfo {
git: git(p, src_files, &repo, &opts)?,
path_in_vcs,
}));
let Some(git) = git(p, src_files, &repo, &opts)? else {
// If the git repo lacks essensial field like `sha1`, and since this field exists from the beginning,
// then don't generate the corresponding file in order to maintain consistency with past behavior.
return Ok(None);
};
return Ok(Some(VcsInfo { git, path_in_vcs }));
}
}
gctx.shell().verbose(|shell| {
Expand All @@ -773,7 +774,7 @@ fn check_repo_state(
src_files: &[PathBuf],
repo: &git2::Repository,
opts: &PackageOpts<'_>,
) -> CargoResult<GitVcsInfo> {
) -> CargoResult<Option<GitVcsInfo>> {
// This is a collection of any dirty or untracked files. This covers:
// - new/modified/deleted/renamed/type change (index or worktree)
// - untracked files (which are "new" worktree files)
Expand All @@ -800,14 +801,16 @@ fn check_repo_state(
.collect();
let dirty = !dirty_src_files.is_empty();
if !dirty || opts.allow_dirty {
// Must check whetherthe repo has no commit firstly, otherwise `revparse_single` would fail on bare commit repo.
// Due to lacking the `sha1` field, it's better not record the `GitVcsInfo` for consistency.
if repo.is_empty()? {
return Ok(GitVcsInfo { sha1: None, dirty });
return Ok(None);
}
let rev_obj = repo.revparse_single("HEAD")?;
Ok(GitVcsInfo {
sha1: Some(rev_obj.id().to_string()),
Ok(Some(GitVcsInfo {
sha1: rev_obj.id().to_string(),
dirty,
})
}))
} else {
anyhow::bail!(
"{} files in the working directory contain changes that were \
Expand Down
17 changes: 2 additions & 15 deletions tests/testsuite/package.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1279,21 +1279,8 @@ fn issue_14354_allowing_dirty_bare_commit() {
validate_crate_contents(
f,
"foo-0.1.0.crate",
&[
".cargo_vcs_info.json",
"Cargo.toml",
"Cargo.toml.orig",
"src/lib.rs",
],
&[(
".cargo_vcs_info.json",
r#"{
"git": {
"dirty": true
},
"path_in_vcs": ""
}"#,
)],
&["Cargo.toml", "Cargo.toml.orig", "src/lib.rs"],
&[],
);
}

Expand Down

0 comments on commit 37cda2d

Please sign in to comment.