Resolve a template to its ID, supporting: - org/name form - slug or display name match (case-insensitive) across all memberships
(ctx context.Context, client *codersdk.Client, templateArg string)
| 317 | // - org/name form |
| 318 | // - slug or display name match (case-insensitive) across all memberships |
| 319 | func resolveTemplateID(ctx context.Context, client *codersdk.Client, templateArg string) (uuid.UUID, error) { |
| 320 | orgPart := "" |
| 321 | namePart := templateArg |
| 322 | if slash := strings.IndexByte(templateArg, '/'); slash > 0 && slash < len(templateArg)-1 { |
| 323 | orgPart = templateArg[:slash] |
| 324 | namePart = templateArg[slash+1:] |
| 325 | } |
| 326 | |
| 327 | resolveInOrg := func(orgID uuid.UUID) (codersdk.Template, bool, error) { |
| 328 | if t, err := client.TemplateByName(ctx, orgID, namePart); err == nil { |
| 329 | return t, true, nil |
| 330 | } |
| 331 | tpls, err := client.TemplatesByOrganization(ctx, orgID) |
| 332 | if err != nil { |
| 333 | return codersdk.Template{}, false, nil |
| 334 | } |
| 335 | for _, t := range tpls { |
| 336 | if strings.EqualFold(t.Name, namePart) || strings.EqualFold(t.DisplayName, namePart) { |
| 337 | return t, true, nil |
| 338 | } |
| 339 | } |
| 340 | return codersdk.Template{}, false, nil |
| 341 | } |
| 342 | |
| 343 | if orgPart != "" { |
| 344 | org, err := client.OrganizationByName(ctx, orgPart) |
| 345 | if err != nil { |
| 346 | return uuid.Nil, xerrors.Errorf("get organization %q: %w", orgPart, err) |
| 347 | } |
| 348 | t, found, err := resolveInOrg(org.ID) |
| 349 | if err != nil { |
| 350 | return uuid.Nil, err |
| 351 | } |
| 352 | if !found { |
| 353 | return uuid.Nil, xerrors.Errorf("template %q not found in organization %q", namePart, orgPart) |
| 354 | } |
| 355 | return t.ID, nil |
| 356 | } |
| 357 | |
| 358 | orgs, err := client.OrganizationsByUser(ctx, codersdk.Me) |
| 359 | if err != nil { |
| 360 | return uuid.Nil, xerrors.Errorf("get organizations: %w", err) |
| 361 | } |
| 362 | var ( |
| 363 | foundTpl codersdk.Template |
| 364 | foundOrgs []string |
| 365 | ) |
| 366 | for _, org := range orgs { |
| 367 | if t, found, err := resolveInOrg(org.ID); err == nil && found { |
| 368 | if len(foundOrgs) == 0 { |
| 369 | foundTpl = t |
| 370 | } |
| 371 | foundOrgs = append(foundOrgs, org.Name) |
| 372 | } |
| 373 | } |
| 374 | switch len(foundOrgs) { |
| 375 | case 0: |
| 376 | return uuid.Nil, xerrors.Errorf("template %q not found in your organizations", namePart) |
no test coverage detected