Skip to content

Commit 2f22337

Browse files
authored
Fix broken when no commits and default branch is not master (#18423)
* Fix broken when no commits and default branch is not master * Fix IsEmpty check * Improve codes
1 parent 781ad8a commit 2f22337

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

modules/git/repo.go

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -79,16 +79,21 @@ func InitRepository(repoPath string, bare bool) error {
7979

8080
// IsEmpty Check if repository is empty.
8181
func (repo *Repository) IsEmpty() (bool, error) {
82-
var errbuf strings.Builder
83-
if err := NewCommand("log", "-1").RunInDirPipeline(repo.Path, nil, &errbuf); err != nil {
84-
if strings.Contains(errbuf.String(), "fatal: bad default revision 'HEAD'") ||
85-
strings.Contains(errbuf.String(), "fatal: your current branch 'master' does not have any commits yet") {
86-
return true, nil
87-
}
82+
var errbuf, output strings.Builder
83+
if err := NewCommandContext(repo.Ctx, "rev-list", "--all", "--count", "--max-count=1").RunWithContext(&RunContext{
84+
Timeout: -1,
85+
Dir: repo.Path,
86+
Stdout: &output,
87+
Stderr: &errbuf,
88+
}); err != nil {
8889
return true, fmt.Errorf("check empty: %v - %s", err, errbuf.String())
8990
}
9091

91-
return false, nil
92+
c, err := strconv.Atoi(strings.TrimSpace(output.String()))
93+
if err != nil {
94+
return true, fmt.Errorf("check empty: convert %s to count failed: %v", output.String(), err)
95+
}
96+
return c == 0, nil
9297
}
9398

9499
// CloneRepoOptions options when clone a repository

0 commit comments

Comments
 (0)