Skip to content

Commit 401e5c8

Browse files
authored
Fix broken when no commits and default branch is not master (#18422)
* Fix broken when no commits and default branch is not master * Fix IsEmpty check * Improve codes * Add timeout
1 parent 668718c commit 401e5c8

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

modules/git/repo.go

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -79,16 +79,22 @@ func InitRepository(ctx context.Context, 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 := NewCommandContext(repo.Ctx, "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").
84+
RunWithContext(&RunContext{
85+
Timeout: -1,
86+
Dir: repo.Path,
87+
Stdout: &output,
88+
Stderr: &errbuf,
89+
}); err != nil {
8890
return true, fmt.Errorf("check empty: %v - %s", err, errbuf.String())
8991
}
9092

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

94100
// CloneRepoOptions options when clone a repository

0 commit comments

Comments
 (0)