MCPcopy
hub / github.com/cli/cli / switchRun

Function switchRun

pkg/cmd/auth/switch/switch.go:77–177  ·  view source on GitHub ↗
(opts *SwitchOptions)

Source from the content-addressed store, hash-verified

75type candidates []hostUser
76
77func 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

Callers 2

TestSwitchRunFunction · 0.85
NewCmdSwitchFunction · 0.85

Calls 15

AuthTokenWriteableFunction · 0.92
ContainsMethod · 0.80
CanPromptMethod · 0.80
ColorSchemeMethod · 0.80
FailureIconMethod · 0.80
BoldMethod · 0.80
SuccessIconMethod · 0.80
ConfigMethod · 0.65
AuthenticationMethod · 0.65
HostsMethod · 0.65
ErrorfMethod · 0.65
UsersForHostMethod · 0.65

Tested by 1

TestSwitchRunFunction · 0.68