Skip to content

Commit 16269d5

Browse files
authored
internal/civisibility: ensure git permissions before extracting git info (#2974)
1 parent 591c40e commit 16269d5

File tree

1 file changed

+42
-0
lines changed
  • internal/civisibility/utils

1 file changed

+42
-0
lines changed

internal/civisibility/utils/git.go

+42
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,20 @@ func getLocalGitData() (localGitData, error) {
172172
return gitData, errors.New("git executable not found")
173173
}
174174

175+
// Ensure we have permissions to read the git directory
176+
if currentDir, err := os.Getwd(); err == nil {
177+
if gitDir, err := getParentGitFolder(currentDir); err == nil && gitDir != "" {
178+
log.Debug("civisibility.git: setting permissions to git folder: %s", gitDir)
179+
if out, err := execGitString(telemetry.NotSpecifiedCommandsType, "config", "--global", "--add", "safe.directory", gitDir); err != nil {
180+
log.Debug("civisibility.git: error while setting permissions to git folder: %s\n%s\n%s", gitDir, err.Error(), out)
181+
}
182+
} else {
183+
log.Debug("civisibility.git: error getting the parent git folder.")
184+
}
185+
} else {
186+
log.Debug("civisibility.git: error getting the current working directory.")
187+
}
188+
175189
// Extract the absolute path to the Git directory
176190
log.Debug("civisibility.git: getting the absolute path to the Git directory")
177191
out, err := execGitString(telemetry.NotSpecifiedCommandsType, "rev-parse", "--absolute-git-dir")
@@ -446,3 +460,31 @@ func CreatePackFiles(commitsToInclude []string, commitsToExclude []string) []str
446460

447461
return packFiles
448462
}
463+
464+
// getParentGitFolder searches from the given directory upwards to find the nearest .git directory.
465+
func getParentGitFolder(innerFolder string) (string, error) {
466+
if innerFolder == "" {
467+
return "", nil
468+
}
469+
470+
dir := innerFolder
471+
for {
472+
gitDirPath := filepath.Join(dir, ".git")
473+
info, err := os.Stat(gitDirPath)
474+
if err == nil && info.IsDir() {
475+
return gitDirPath, nil
476+
}
477+
if err != nil && !os.IsNotExist(err) {
478+
return "", err
479+
}
480+
481+
parentDir := filepath.Dir(dir)
482+
// If we've reached the root directory, stop the loop.
483+
if parentDir == dir {
484+
break
485+
}
486+
dir = parentDir
487+
}
488+
489+
return "", nil
490+
}

0 commit comments

Comments
 (0)