summaryrefslogtreecommitdiff
path: root/internal/localrepos/localrepos.go
blob: 6200539c6b8e9cc37d9dbb86f282feb51666651e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package localrepos

import (
	"os"
	"path/filepath"
)

// ListLocalRepos returns directory names in workDir that contain a .git path.
// The .git path may be either a directory or a file (for worktree layouts).
func ListLocalRepos(workDir string) ([]string, error) {
	return listLocalRepos(workDir, false)
}

// ListLocalReposWithGitDir returns directory names in workDir that contain
// a .git directory.
func ListLocalReposWithGitDir(workDir string) ([]string, error) {
	return listLocalRepos(workDir, true)
}

func listLocalRepos(workDir string, requireGitDir bool) ([]string, error) {
	entries, err := os.ReadDir(workDir)
	if err != nil {
		return nil, err
	}

	repositories := make([]string, 0, len(entries))
	for _, entry := range entries {
		if !entry.IsDir() {
			continue
		}

		gitDir := filepath.Join(workDir, entry.Name(), ".git")
		if info, err := os.Stat(gitDir); err == nil {
			if !requireGitDir || info.IsDir() {
				repositories = append(repositories, entry.Name())
			}
		}
	}

	return repositories, nil
}