88 lines
2.6 KiB
Go
88 lines
2.6 KiB
Go
// Package tea reads the tea CLI config to find the Gitea login, and its token, for a given host.
|
|
//
|
|
// tea config typically lives at $HOME/.config/tea/config.yml. Older versions
|
|
// of tea (<v0.10) stored the token inline in the YAML; newer versions move
|
|
// tokens into a system keyring and only keep metadata in the file.
|
|
//
|
|
// We support the inline form here. If the token field is missing, callers
|
|
// fall back to the GITEA_TOKEN environment variable.
|
|
package tea
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"io/fs"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
// TeaLogin represents a single login entry in tea config.yml.
|
|
type TeaLogin struct {
|
|
Name string `yaml:"name"`
|
|
URL string `yaml:"url"`
|
|
Token string `yaml:"token"`
|
|
Default bool `yaml:"default"`
|
|
}
|
|
|
|
// TeaConfig is the top-level structure of tea config.yml.
|
|
type TeaConfig struct {
|
|
Logins []TeaLogin `yaml:"logins"`
|
|
}
|
|
|
|
// DefaultConfigPath returns the conventional path to tea's config.yml.
|
|
func DefaultConfigPath() (string, error) {
|
|
home, err := os.UserHomeDir()
|
|
if err != nil {
|
|
return "", fmt.Errorf("解析 home 目录失败: %w", err)
|
|
}
|
|
return filepath.Join(home, ".config", "tea", "config.yml"), nil
|
|
}
|
|
|
|
// load reads and parses the tea config file at the given path.
|
|
func load(path string) (*TeaConfig, error) {
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("读取 tea config %s 失败: %w", path, err)
|
|
}
|
|
var cfg TeaConfig
|
|
if err := yaml.Unmarshal(data, &cfg); err != nil {
|
|
return nil, fmt.Errorf("解析 tea config %s 失败: %w", path, err)
|
|
}
|
|
return &cfg, nil
|
|
}
|
|
|
|
// 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. 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 just means
|
|
// there is no login, so it returns `nil` rather than an error.
|
|
func LoginForHost(path, host string) (*TeaLogin, error) {
|
|
cfg, err := load(path)
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
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 {
|
|
continue
|
|
}
|
|
if cfg.Logins[i].Default {
|
|
return &cfg.Logins[i], nil
|
|
}
|
|
if first == nil {
|
|
first = &cfg.Logins[i]
|
|
}
|
|
}
|
|
return first, nil
|
|
}
|