From 2e7511cd182c9196c259ca480cb1dba33838d039 Mon Sep 17 00:00:00 2001 From: vilmibm Date: Wed, 5 Aug 2020 12:01:47 -0500 Subject: [PATCH] add helpers to config type for hosts --- internal/config/config_type.go | 37 +++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/internal/config/config_type.go b/internal/config/config_type.go index 85e5c0d4a..523430c54 100644 --- a/internal/config/config_type.go +++ b/internal/config/config_type.go @@ -4,7 +4,9 @@ import ( "bytes" "errors" "fmt" + "sort" + "github.com/cli/cli/internal/ghinstance" "gopkg.in/yaml.v3" ) @@ -14,6 +16,8 @@ const defaultGitProtocol = "https" type Config interface { Get(string, string) (string, error) Set(string, string, string) error + UnsetHost(string) + Hosts() ([]string, error) Aliases() (*AliasConfig, error) Write() error } @@ -29,7 +33,7 @@ type HostConfig struct { // This type implements a low-level get/set config that is backed by an in-memory tree of Yaml // nodes. It allows us to interact with a yaml-based config programmatically, preserving any -// comments that were present when the yaml waas parsed. +// comments that were present when the yaml was parsed. type ConfigMap struct { Root *yaml.Node } @@ -236,6 +240,20 @@ func (c *fileConfig) Set(hostname, key, value string) error { } } +func (c *fileConfig) UnsetHost(hostname string) { + if hostname == "" { + return + } + + hostsEntry, err := c.FindEntry("hosts") + if err != nil { + return + } + + cm := ConfigMap{hostsEntry.ValueNode} + cm.RemoveEntry(hostname) +} + func (c *fileConfig) configForHost(hostname string) (*HostConfig, error) { hosts, err := c.hostEntries() if err != nil { @@ -357,6 +375,23 @@ func (c *fileConfig) hostEntries() ([]*HostConfig, error) { return hostConfigs, nil } +// Hosts returns a list of all known hostnames configred in hosts.yml +func (c *fileConfig) Hosts() ([]string, error) { + entries, err := c.hostEntries() + if err != nil { + return nil, err + } + + hostnames := []string{} + for _, entry := range entries { + hostnames = append(hostnames, entry.Host) + } + + sort.SliceStable(hostnames, func(i, j int) bool { return hostnames[i] == ghinstance.Default() }) + + return hostnames, nil +} + func (c *fileConfig) makeConfigForHost(hostname string) *HostConfig { hostRoot := &yaml.Node{Kind: yaml.MappingNode} hostCfg := &HostConfig{