@@ -94,6 +94,7 @@ func (r *RootCmd) Core() []*clibase.Cmd {
94
94
r .tokens (),
95
95
r .users (),
96
96
r .version (defaultVersionInfo ),
97
+ r .organizations (),
97
98
98
99
// Workspace Commands
99
100
r .autoupdate (),
@@ -698,14 +699,44 @@ func (r *RootCmd) createAgentClient() (*agentsdk.Client, error) {
698
699
}
699
700
700
701
// CurrentOrganization returns the currently active organization for the authenticated user.
701
- func CurrentOrganization (inv * clibase.Invocation , client * codersdk.Client ) (codersdk.Organization , error ) {
702
+ func CurrentOrganization (r * RootCmd , inv * clibase.Invocation , client * codersdk.Client ) (codersdk.Organization , error ) {
703
+ conf := r .createConfig ()
704
+ selected := ""
705
+ if conf .Organization ().Exists () {
706
+ org , err := conf .Organization ().Read ()
707
+ if err != nil {
708
+ return codersdk.Organization {}, fmt .Errorf ("read selected organization from config file %q: %w" , conf .Organization (), err )
709
+ }
710
+ selected = org
711
+ }
712
+
713
+ // Verify the org exists and the user is a member
702
714
orgs , err := client .OrganizationsByUser (inv .Context (), codersdk .Me )
703
715
if err != nil {
704
- return codersdk.Organization {}, nil
716
+ return codersdk.Organization {}, err
705
717
}
706
- // For now, we won't use the config to set this.
707
- // Eventually, we will support changing using "coder switch <org>"
708
- return orgs [0 ], nil
718
+
719
+ // User manually selected an organization
720
+ if selected != "" {
721
+ index := slices .IndexFunc (orgs , func (org codersdk.Organization ) bool {
722
+ return org .Name == selected || org .ID .String () == selected
723
+ })
724
+
725
+ if index < 0 {
726
+ return codersdk.Organization {}, xerrors .Errorf ("organization %q not found, are you sure you are a member of this organization?" , selected )
727
+ }
728
+ return orgs [index ], nil
729
+ }
730
+
731
+ // User did not select an organization, so use the default.
732
+ index := slices .IndexFunc (orgs , func (org codersdk.Organization ) bool {
733
+ return org .IsDefault
734
+ })
735
+ if index < 0 {
736
+ return codersdk.Organization {}, xerrors .Errorf ("unable to determine current organization. Use 'coder switch <org>' to select an organization to use" )
737
+ }
738
+
739
+ return orgs [index ], nil
709
740
}
710
741
711
742
func splitNamedWorkspace (identifier string ) (owner string , workspaceName string , err error ) {
0 commit comments