resolveRemoteURL resolves the best git remote URL to use for a given directory. It first tries the 'origin' remote for backward compatibility. If 'origin' is not configured but exactly one other remote exists, that remote is used instead. Returns the remote URL, the remote name used, and any error.
(dir string)
| 152 | // Returns the remote URL, the remote name used, and any error. |
| 153 | // dir may be empty to use the current working directory. |
| 154 | func resolveRemoteURL(dir string) (string, string, error) { |
| 155 | gitArgs := func(args ...string) *exec.Cmd { |
| 156 | if dir != "" { |
| 157 | return exec.Command("git", append([]string{"-C", dir}, args...)...) |
| 158 | } |
| 159 | return exec.Command("git", args...) |
| 160 | } |
| 161 | |
| 162 | // First try 'origin' for backward compatibility |
| 163 | if output, err := gitArgs("config", "--get", "remote.origin.url").Output(); err == nil { |
| 164 | url := strings.TrimSpace(string(output)) |
| 165 | if url != "" { |
| 166 | gitLog.Print("Using 'origin' remote") |
| 167 | return url, "origin", nil |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | // Fall back: list all remotes |
| 172 | output, err := gitArgs("remote").Output() |
| 173 | if err != nil { |
| 174 | return "", "", fmt.Errorf("failed to list git remotes: %w", err) |
| 175 | } |
| 176 | |
| 177 | remoteNames := strings.Fields(strings.TrimSpace(string(output))) |
| 178 | if len(remoteNames) == 0 { |
| 179 | return "", "", errors.New("no git remotes configured") |
| 180 | } |
| 181 | if len(remoteNames) > 1 { |
| 182 | return "", "", fmt.Errorf("multiple git remotes configured (%s), no 'origin' remote found", strings.Join(remoteNames, ", ")) |
| 183 | } |
| 184 | |
| 185 | // Exactly one remote — use it |
| 186 | remoteName := remoteNames[0] |
| 187 | urlOutput, err := gitArgs("config", "--get", "remote."+remoteName+".url").Output() |
| 188 | if err != nil { |
| 189 | return "", "", fmt.Errorf("failed to get URL for remote %q: %w", remoteName, err) |
| 190 | } |
| 191 | |
| 192 | url := strings.TrimSpace(string(urlOutput)) |
| 193 | gitLog.Printf("No 'origin' remote found; using single configured remote %q", remoteName) |
| 194 | return url, remoteName, nil |
| 195 | } |
| 196 | |
| 197 | // getHostFromOriginRemote returns the hostname of the git remote. |
| 198 | // It prefers the 'origin' remote for backward compatibility. If 'origin' is not |