diff --git a/vscode/cli/internal/tea/config.go b/vscode/cli/internal/tea/config.go index 6483e37..228c28b 100644 --- a/vscode/cli/internal/tea/config.go +++ b/vscode/cli/internal/tea/config.go @@ -58,8 +58,9 @@ func load(path string) (*TeaConfig, error) { // LoginForHost returns the login in the tea config at `path` whose URL points at `host`, or `nil` when none does. // // Hosts are compared by hostname only, ignoring case, scheme, port and trailing slashes, so the host read from a git -// SSH remote still finds the login saved with the forge's web URL. A missing config file is not an error either, -// because the caller can still fall back to `GITEA_TOKEN`. +// SSH remote still finds the login saved with the forge's web URL. When several logins point at `host`, the one marked +// `default` wins, because that is the identity the user picked; otherwise the first. A missing config file is not an +// error either, because the caller can still fall back to `GITEA_TOKEN`. func LoginForHost(path, host string) (*TeaLogin, error) { cfg, err := load(path) if errors.Is(err, fs.ErrNotExist) { @@ -69,11 +70,18 @@ func LoginForHost(path, host string) (*TeaLogin, error) { return nil, err } want := strings.ToLower(host) + var first *TeaLogin for i := range cfg.Logins { u, perr := url.Parse(strings.TrimSpace(cfg.Logins[i].URL)) - if perr == nil && strings.ToLower(u.Hostname()) == want { + if perr != nil || strings.ToLower(u.Hostname()) != want { + continue + } + if cfg.Logins[i].Default { return &cfg.Logins[i], nil } + if first == nil { + first = &cfg.Logins[i] + } } - return nil, nil + return first, nil } diff --git a/vscode/cli/internal/tea/config_test.go b/vscode/cli/internal/tea/config_test.go index 9027f4f..e56ea96 100644 --- a/vscode/cli/internal/tea/config_test.go +++ b/vscode/cli/internal/tea/config_test.go @@ -67,3 +67,22 @@ func TestLoginForHostBadYAMLIsAnError(t *testing.T) { t.Fatal("tea config 解析失败应当报错") } } + +func TestLoginForHostPrefersDefaultAmongSameHost(t *testing.T) { + path := writeConfig(t, `logins: +- name: bot + url: https://gitea.example.com + token: tok-bot +- name: me + url: https://gitea.example.com/ + token: tok-me + default: true +`) + l, err := LoginForHost(path, "gitea.example.com") + if err != nil { + t.Fatalf("LoginForHost 出错: %v", err) + } + if l == nil || l.Name != "me" { + t.Fatalf("同一 host 有多条 login 时应取 default 那条,得到 %+v", l) + } +}