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