(inv *serpent.Invocation, client *codersdk.Client)
| 1037 | } |
| 1038 | |
| 1039 | func (o *OrganizationContext) Selected(inv *serpent.Invocation, client *codersdk.Client) (codersdk.Organization, error) { |
| 1040 | // Fetch the set of organizations the user is a member of. |
| 1041 | orgs, err := client.OrganizationsByUser(inv.Context(), codersdk.Me) |
| 1042 | if err != nil { |
| 1043 | return codersdk.Organization{}, xerrors.Errorf("get organizations: %w", err) |
| 1044 | } |
| 1045 | |
| 1046 | // User manually selected an organization |
| 1047 | if o.FlagSelect != "" { |
| 1048 | index := slices.IndexFunc(orgs, func(org codersdk.Organization) bool { |
| 1049 | return org.Name == o.FlagSelect || org.ID.String() == o.FlagSelect |
| 1050 | }) |
| 1051 | if index >= 0 { |
| 1052 | return orgs[index], nil |
| 1053 | } |
| 1054 | |
| 1055 | // Not in membership list - try direct fetch. |
| 1056 | // This allows site-wide admins (e.g., Owners) to use orgs they aren't |
| 1057 | // members of. |
| 1058 | org, err := client.OrganizationByName(inv.Context(), o.FlagSelect) |
| 1059 | if err != nil { |
| 1060 | var names []string |
| 1061 | for _, org := range orgs { |
| 1062 | names = append(names, org.Name) |
| 1063 | } |
| 1064 | var sdkErr *codersdk.Error |
| 1065 | if errors.As(err, &sdkErr) && sdkErr.StatusCode() == http.StatusNotFound { |
| 1066 | return codersdk.Organization{}, xerrors.Errorf("organization %q not found, are you sure you are a member of this organization? "+ |
| 1067 | "Valid options for '--org=' are [%s].", o.FlagSelect, strings.Join(names, ", ")) |
| 1068 | } |
| 1069 | return codersdk.Organization{}, xerrors.Errorf("get organization %q: %w", o.FlagSelect, err) |
| 1070 | } |
| 1071 | return org, nil |
| 1072 | } |
| 1073 | |
| 1074 | if len(orgs) == 1 { |
| 1075 | return orgs[0], nil |
| 1076 | } |
| 1077 | |
| 1078 | // No org selected, and we are more than 1? Return an error. |
| 1079 | validOrgs := make([]string, 0, len(orgs)) |
| 1080 | for _, org := range orgs { |
| 1081 | validOrgs = append(validOrgs, org.Name) |
| 1082 | } |
| 1083 | |
| 1084 | return codersdk.Organization{}, xerrors.Errorf("Must select an organization with --org=<org_name>. Choose from: %s", strings.Join(validOrgs, ", ")) |
| 1085 | } |
| 1086 | |
| 1087 | func initAppearance(ctx context.Context, client *codersdk.Client) codersdk.AppearanceConfig { |
| 1088 | // best effort |
no test coverage detected