resolveGitConfigPath returns the absolute path to the git config for a repo rooted at path, or "" if none exists. Handles both the common case (.git is a directory) and the git-worktree case (.git is a file with `gitdir: `).
(path string)
| 465 | // (.git is a directory) and the git-worktree case (.git is a file with |
| 466 | // `gitdir: <path>`). |
| 467 | func resolveGitConfigPath(path string) string { |
| 468 | gitPath := filepath.Join(path, ".git") |
| 469 | info, err := os.Stat(gitPath) |
| 470 | if err != nil { |
| 471 | return "" |
| 472 | } |
| 473 | if info.IsDir() { |
| 474 | return filepath.Join(gitPath, "config") |
| 475 | } |
| 476 | // Worktree: .git is a file of the form "gitdir: <relative-or-absolute>". |
| 477 | data, err := os.ReadFile(gitPath) |
| 478 | if err != nil { |
| 479 | return "" |
| 480 | } |
| 481 | line := strings.TrimSpace(string(data)) |
| 482 | if !strings.HasPrefix(line, "gitdir:") { |
| 483 | return "" |
| 484 | } |
| 485 | target := strings.TrimSpace(strings.TrimPrefix(line, "gitdir:")) |
| 486 | if !filepath.IsAbs(target) { |
| 487 | target = filepath.Join(path, target) |
| 488 | } |
| 489 | return filepath.Join(target, "config") |
| 490 | } |