| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 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. |
| 22 | func 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. |
| 33 | var 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. |
| 38 | var ( |
| 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. |
| 51 | func 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 | |
| 65 | func resolveRepoDirUncached(ctx context.Context, repoRef string) (string, error) { |
| 66 | if dir, err := existingRepoDir(repoRef); err != nil || dir != "" { |
| 67 | return dir, err |
| 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. A project registry at both |
| 95 | // its names is an error naming both: going on would silently read neither. |
| 96 | func existingRepoDir(repoRef string) (string, error) { |
| 97 | cwdRoot, _ := git.RepoRoot() // "" outside a checkout |
| 98 | if repoRef == "" { |
| 99 | return cwdRoot, nil |
| 100 | } |
| 101 | wantSlug := repoSlug(repoRef) |
| 102 | // The current checkout counts only when it is demonstrably the requested |
| 103 | // repo. A bare project name never matches it: the name says nothing about |
| 104 | // which remote this checkout points at. |
| 105 | if cwdRoot != "" && wantSlug != "" && strings.EqualFold(repoSlugForDir(cwdRoot), wantSlug) { |
| 106 | return cwdRoot, nil |
| 107 | } |
| 108 | return registeredProjectDir(repoRef, wantSlug) |
| 109 | } |
| 110 | |
| 111 | // registeredProjectDir returns the local path of a registered project that |
| 112 | // holds the requested repo, or "" when none does. A project matches when its |
| 113 | // origin remote resolves to the same owner/repo slug. When a project's origin |
| 114 | // is not a GitHub URL (a local path, say), its name is matched against the repo |
| 115 | // portion of the reference instead — but a project whose origin points at a |
| 116 | // different GitHub repo is never matched by name. A registry that can't be |
| 117 | // read has no project, but one at both its names is an error. |
| 118 | func registeredProjectDir(repoRef, wantSlug string) (string, error) { |
| 119 | reg, err := project.Load() |
| 120 | var conflict *location.ConflictError |
| 121 | if errors.As(err, &conflict) { |
| 122 | return "", err |
| 123 | } |
| 124 | if err != nil || reg == nil { |
| 125 | return "", nil |
| 126 | } |
| 127 | projects := reg.List() |
| 128 | |
| 129 | names := make([]string, 0, len(projects)) |
| 130 | for name := range projects { |
| 131 | names = append(names, name) |
| 132 | } |
| 133 | sort.Strings(names) // deterministic pick when several projects match by name |
| 134 | |
| 135 | shortName := repoRef |
| 136 | if _, after, found := strings.Cut(git.CleanGitHubRef(repoRef), "/"); found { |
| 137 | shortName = after |
| 138 | } |
| 139 | |
| 140 | var nameMatch string |
| 141 | for _, name := range names { |
| 142 | dir := projects[name] |
| 143 | slug := repoSlugForDir(dir) |
| 144 | if wantSlug != "" && strings.EqualFold(slug, wantSlug) { |
| 145 | return dir, nil |
| 146 | } |
| 147 | if slug == "" && name == shortName && nameMatch == "" { |
| 148 | nameMatch = dir |
| 149 | } |
| 150 | } |
| 151 | return nameMatch, nil |
| 152 | } |
| 153 | |
| 154 | // repoSlug normalizes a repo reference to "owner/repo", or "" when it has no |
| 155 | // owner (a bare project name) or cannot be parsed. |
| 156 | func repoSlug(ref string) string { |
| 157 | if ref == "" || !strings.Contains(git.CleanGitHubRef(ref), "/") { |
| 158 | return "" |
| 159 | } |
| 160 | owner, repo, err := git.SplitRepoRef(ref) |
| 161 | if err != nil { |
| 162 | return "" |
| 163 | } |
| 164 | return owner + "/" + repo |
| 165 | } |
| 166 | |
| 167 | // repoSlugForDir returns the "owner/repo" slug of a checkout's origin remote, |
| 168 | // or "" when the directory is not a repo or its origin is not a GitHub URL. |
| 169 | func repoSlugForDir(dir string) string { |
| 170 | if dir == "" { |
| 171 | return "" |
| 172 | } |
| 173 | remote := gitRemoteURL(dir) |
| 174 | if remote == "" { |
| 175 | return "" |
| 176 | } |
| 177 | return repoSlug(remote) |
| 178 | } |