4
4
"errors"
5
5
"fmt"
6
6
"os"
7
+ "slices"
8
+ "strings"
7
9
8
10
"github.com/coder/coder/v2/cli/clibase"
9
11
"github.com/coder/coder/v2/cli/cliui"
@@ -22,6 +24,7 @@ func (r *RootCmd) organizations() *clibase.Cmd {
22
24
},
23
25
Children : []* clibase.Cmd {
24
26
r .currentOrganization (),
27
+ r .switchOrganization (),
25
28
},
26
29
}
27
30
@@ -52,13 +55,44 @@ func (r *RootCmd) switchOrganization() *clibase.Cmd {
52
55
),
53
56
Options : clibase.OptionSet {},
54
57
Handler : func (inv * clibase.Invocation ) error {
58
+ orgArg := inv .Args [0 ]
55
59
conf := r .createConfig ()
60
+ orgs , err := client .OrganizationsByUser (inv .Context (), codersdk .Me )
61
+ if err != nil {
62
+ return fmt .Errorf ("failed to get organizations: %w" , err )
63
+ }
64
+
56
65
// If the user passes an empty string, we want to remove the organization
57
- if inv . Args [ 0 ] == "" {
66
+ if orgArg == "" {
58
67
err := conf .Organization ().Delete ()
59
68
if err != nil && ! errors .Is (err , os .ErrNotExist ) {
60
69
return fmt .Errorf ("failed to unset organization: %w" , err )
61
70
}
71
+ } else {
72
+ index := slices .IndexFunc (orgs , func (org codersdk.Organization ) bool {
73
+ return org .Name == orgArg || org .ID .String () == orgArg
74
+ })
75
+ if index < 0 {
76
+ names := make ([]string , 0 , len (orgs ))
77
+ for _ , org := range orgs {
78
+ names = append (names , org .Name )
79
+ }
80
+
81
+ // Using this error for better error message formatting
82
+ err := & codersdk.Error {
83
+ Response : codersdk.Response {
84
+ Message : fmt .Sprintf ("Organization %q not found." , orgArg ),
85
+ Detail : "Ensure the organization argument is correct and you are a member of it." ,
86
+ },
87
+ Helper : fmt .Sprintf ("Valid organizations you can switch to: %q" , strings .Join (names , ", " )),
88
+ }
89
+ return err
90
+ }
91
+
92
+ err := conf .Organization ().Write (orgs [index ].ID .String ())
93
+ if err != nil {
94
+ return fmt .Errorf ("failed to write organization to config file: %w" , err )
95
+ }
62
96
}
63
97
64
98
return nil
0 commit comments