| 84 | } |
| 85 | |
| 86 | func (m MultiAccount) Do(c *config.Config) error { |
| 87 | hostnames, err := c.Keys(hostsKey) |
| 88 | // [github.com, github.localhost] |
| 89 | // We wouldn't expect to have a hosts key when this is the first time anyone |
| 90 | // is logging in with the CLI. |
| 91 | var keyNotFoundError *config.KeyNotFoundError |
| 92 | if errors.As(err, &keyNotFoundError) { |
| 93 | return nil |
| 94 | } |
| 95 | if err != nil { |
| 96 | return CowardlyRefusalError{errors.New("couldn't get hosts configuration")} |
| 97 | } |
| 98 | |
| 99 | // If there are no hosts then it doesn't matter whether we migrate or not, |
| 100 | // so lets avoid any confusion and say there's no migration required. |
| 101 | if len(hostnames) == 0 { |
| 102 | return nil |
| 103 | } |
| 104 | |
| 105 | // Otherwise let's get to the business of migrating! |
| 106 | for _, hostname := range hostnames { |
| 107 | tokenSource, err := getToken(c, hostname) |
| 108 | // If no token existed for this host we'll remove the entry from the hosts file |
| 109 | // by deleting it and moving on to the next one. |
| 110 | if errors.Is(err, noTokenError) { |
| 111 | // The only error that can be returned here is the key not existing, which |
| 112 | // we know can't be true. |
| 113 | _ = c.Remove(append(hostsKey, hostname)) |
| 114 | continue |
| 115 | } |
| 116 | // For any other error we'll error out |
| 117 | if err != nil { |
| 118 | return CowardlyRefusalError{fmt.Errorf("couldn't find oauth token for %q: %w", hostname, err)} |
| 119 | } |
| 120 | |
| 121 | username, err := getUsername(c, hostname, tokenSource.token, m.Transport) |
| 122 | if err != nil { |
| 123 | issueURL := "https://github.com/cli/cli/issues/8441" |
| 124 | return CowardlyRefusalError{fmt.Errorf("couldn't get user name for %q please visit %s for help: %w", hostname, issueURL, err)} |
| 125 | } |
| 126 | |
| 127 | if err := migrateConfig(c, hostname, username); err != nil { |
| 128 | return CowardlyRefusalError{fmt.Errorf("couldn't migrate config for %q: %w", hostname, err)} |
| 129 | } |
| 130 | |
| 131 | if err := migrateToken(hostname, username, tokenSource); err != nil { |
| 132 | return CowardlyRefusalError{fmt.Errorf("couldn't migrate oauth token for %q: %w", hostname, err)} |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | return nil |
| 137 | } |
| 138 | |
| 139 | func getToken(c *config.Config, hostname string) (tokenSource, error) { |
| 140 | if token, _ := c.Get(append(hostsKey, hostname, "oauth_token")); token != "" { |