gunk-dev/the-valley

repodir.go

source6a6791929c36main's published tip history
5.4 KiB
1package cmd
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "path/filepath"
8 "sort"
9 "strings"
10 "sync"
11
12 "the-valley/flow/internal/config"
13 "the-valley/flow/internal/git"
14 "the-valley/flow/internal/location"
15 "the-valley/flow/internal/project"
16)
17
18// registryUnlessConflict is the project registry for a command that goes on
19// without one it can't read, nil then, but not past a registry at both its
20// names: that is an error naming both, since going on would silently read
21// neither.
22func registryUnlessConflict() (*project.Registry, error) {
23 reg, err := project.Load()
24 var conflict *location.ConflictError
25 if errors.As(err, &conflict) {
26 return nil, err
27 }
28 return reg, nil
29}
30
31// errNoTargetRepo is returned when there is nothing to resolve: no repo was
32// requested and the current directory is not a checkout.
33var errNoTargetRepo = errors.New("not inside a git repository and no target repo given")
34
35// repoDirCache memoizes resolveRepoDir per repo reference. Resolution can clone
36// or fetch, so a command that needs the directory more than once (merging a
37// queue of PRs from the same repo, say) only pays for it once per process.
38var (
39 repoDirMu sync.Mutex
40 repoDirCache = map[string]string{}
41)
42
43// resolveRepoDir returns a local git repository directory for repoRef
44// ("owner/repo", a full GitHub URL, or a registered project name), cloning it
45// under worktree_base/.repos when no local checkout exists. It mirrors how
46// 'klaus launch' finds a repo, so commands that need a checkout work from
47// anywhere — including a klaus session workspace that is not itself a clone.
48//
49// Use existingRepoDir instead when a checkout is merely nice to have: this
50// function may clone, which is far too much work for, say, reading config.
51func resolveRepoDir(ctx context.Context, repoRef string) (string, error) {
52 repoDirMu.Lock()
53 defer repoDirMu.Unlock()
54 if dir, ok := repoDirCache[repoRef]; ok {
55 return dir, nil
56 }
57 dir, err := resolveRepoDirUncached(ctx, repoRef)
58 if err != nil {
59 return "", err
60 }
61 repoDirCache[repoRef] = dir
62 return dir, nil
63}
64
65func resolveRepoDirUncached(ctx context.Context, repoRef string) (string, error) {
66 if dir := existingRepoDir(repoRef); dir != "" {
67 return dir, nil
68 }
69 if repoRef == "" {
70 return "", errNoTargetRepo
71 }
72
73 owner, repo, cloneURL, err := git.ParseRepoRef(repoRef)
74 if err != nil {
75 return "", err
76 }
77 cwdRoot, _ := git.RepoRoot()
78 cfg, err := config.Load(cwdRoot)
79 if err != nil {
80 return "", fmt.Errorf("could not load configuration: %w", err)
81 }
82 cloneDir := filepath.Join(cfg.WorktreeBase, ".repos", owner, repo)
83 if err := git.NewExecClient().EnsureClone(ctx, cloneURL, cloneDir); err != nil {
84 return "", fmt.Errorf("cloning %s: %w", repoRef, err)
85 }
86 return cloneDir, nil
87}
88
89// existingRepoDir returns a local checkout of repoRef that already exists, or
90// "" when none does. It never clones or fetches.
91//
92// An empty repoRef means "whatever repo the current directory is in". A
93// non-empty one matches the current checkout only when their origins agree, and
94// otherwise falls back to a registered project.
95func existingRepoDir(repoRef string) string {
96 cwdRoot, _ := git.RepoRoot() // "" outside a checkout
97 if repoRef == "" {
98 return cwdRoot
99 }
100 wantSlug := repoSlug(repoRef)
101 // The current checkout counts only when it is demonstrably the requested
102 // repo. A bare project name never matches it: the name says nothing about
103 // which remote this checkout points at.
104 if cwdRoot != "" && wantSlug != "" && strings.EqualFold(repoSlugForDir(cwdRoot), wantSlug) {
105 return cwdRoot
106 }
107 return registeredProjectDir(repoRef, wantSlug)
108}
109
110// registeredProjectDir returns the local path of a registered project that
111// holds the requested repo, or "" when none does. A project matches when its
112// origin remote resolves to the same owner/repo slug. When a project's origin
113// is not a GitHub URL (a local path, say), its name is matched against the repo
114// portion of the reference instead — but a project whose origin points at a
115// different GitHub repo is never matched by name.
116func registeredProjectDir(repoRef, wantSlug string) string {
117 reg, err := project.Load()
118 if err != nil || reg == nil {
119 return ""
120 }
121 projects := reg.List()
122
123 names := make([]string, 0, len(projects))
124 for name := range projects {
125 names = append(names, name)
126 }
127 sort.Strings(names) // deterministic pick when several projects match by name
128
129 shortName := repoRef
130 if _, after, found := strings.Cut(git.CleanGitHubRef(repoRef), "/"); found {
131 shortName = after
132 }
133
134 var nameMatch string
135 for _, name := range names {
136 dir := projects[name]
137 slug := repoSlugForDir(dir)
138 if wantSlug != "" && strings.EqualFold(slug, wantSlug) {
139 return dir
140 }
141 if slug == "" && name == shortName && nameMatch == "" {
142 nameMatch = dir
143 }
144 }
145 return nameMatch
146}
147
148// repoSlug normalizes a repo reference to "owner/repo", or "" when it has no
149// owner (a bare project name) or cannot be parsed.
150func repoSlug(ref string) string {
151 if ref == "" || !strings.Contains(git.CleanGitHubRef(ref), "/") {
152 return ""
153 }
154 owner, repo, err := git.SplitRepoRef(ref)
155 if err != nil {
156 return ""
157 }
158 return owner + "/" + repo
159}
160
161// repoSlugForDir returns the "owner/repo" slug of a checkout's origin remote,
162// or "" when the directory is not a repo or its origin is not a GitHub URL.
163func repoSlugForDir(dir string) string {
164 if dir == "" {
165 return ""
166 }
167 remote := gitRemoteURL(dir)
168 if remote == "" {
169 return ""
170 }
171 return repoSlug(remote)
172}