| 75 | type candidates []hostUser |
| 76 | |
| 77 | func switchRun(opts *SwitchOptions) error { |
| 78 | hostname := opts.Hostname |
| 79 | username := opts.Username |
| 80 | |
| 81 | cfg, err := opts.Config() |
| 82 | if err != nil { |
| 83 | return err |
| 84 | } |
| 85 | authCfg := cfg.Authentication() |
| 86 | |
| 87 | knownHosts := authCfg.Hosts() |
| 88 | if len(knownHosts) == 0 { |
| 89 | return fmt.Errorf("not logged in to any hosts") |
| 90 | } |
| 91 | |
| 92 | if hostname != "" { |
| 93 | if !slices.Contains(knownHosts, hostname) { |
| 94 | return fmt.Errorf("not logged in to %s", hostname) |
| 95 | } |
| 96 | |
| 97 | if username != "" { |
| 98 | knownUsers := cfg.Authentication().UsersForHost(hostname) |
| 99 | if !slices.Contains(knownUsers, username) { |
| 100 | return fmt.Errorf("not logged in to %s account %s", hostname, username) |
| 101 | } |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | var candidates candidates |
| 106 | |
| 107 | for _, host := range knownHosts { |
| 108 | if hostname != "" && host != hostname { |
| 109 | continue |
| 110 | } |
| 111 | hostActiveUser, err := authCfg.ActiveUser(host) |
| 112 | if err != nil { |
| 113 | return err |
| 114 | } |
| 115 | knownUsers := cfg.Authentication().UsersForHost(host) |
| 116 | for _, user := range knownUsers { |
| 117 | if username != "" && user != username { |
| 118 | continue |
| 119 | } |
| 120 | candidates = append(candidates, hostUser{host: host, user: user, active: user == hostActiveUser}) |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | if len(candidates) == 0 { |
| 125 | return errors.New("no accounts matched that criteria") |
| 126 | } else if len(candidates) == 1 { |
| 127 | hostname = candidates[0].host |
| 128 | username = candidates[0].user |
| 129 | } else if len(candidates) == 2 && |
| 130 | candidates[0].host == candidates[1].host { |
| 131 | // If there is a single host with two users, automatically switch to the |
| 132 | // inactive user without prompting. |
| 133 | hostname = candidates[0].host |
| 134 | username = candidates[0].user |