gunk-dev/the-valley

repodir.go

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