// Workspaces returns a list of names for the workspaces found on GCS. The default
// state is always returned as the first element in the slice.
352729
func (b *Backend) Workspaces() ([]string, error) {
	states := []string{backend.DefaultStateName}

	bucket := b.storageClient.Bucket(b.bucketName)
	objs := bucket.Objects(b.storageContext, &storage.Query{
		Delimiter: "/",
		Prefix:    b.prefix,
	})
	for {
		attrs, err := objs.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return nil, fmt.Errorf("querying Cloud Storage failed: %v", err)
		}

		name := path.Base(attrs.Name)
		if !strings.HasSuffix(name, stateFileSuffix) {
			continue
		}
		st := strings.TrimSuffix(name, stateFileSuffix)

		if st != backend.DefaultStateName {
			states = append(states, st)
		}
	}

	sort.Strings(states[1:])
	return states, nil
}
329835
func (b *Remote) workspaces() ([]string, error) {
	options := tfe.WorkspaceListOptions{}
	switch {
	case b.workspace != "":
		options.Search = tfe.String(b.workspace)
	case b.prefix != "":
		options.Search = tfe.String(b.prefix)
	}

	// Create a slice to contain all the names.
	var names []string

	for {
		wl, err := b.client.Workspaces.List(context.Background(), b.organization, options)
		if err != nil {
			return nil, err
		}

		for _, w := range wl.Items {
			if b.workspace != "" && w.Name == b.workspace {
				names = append(names, backend.DefaultStateName)
				continue
			}
			if b.prefix != "" && strings.HasPrefix(w.Name, b.prefix) {
				names = append(names, strings.TrimPrefix(w.Name, b.prefix))
			}
		}

		// Exit the loop when we've seen all pages.
		if wl.CurrentPage >= wl.TotalPages {
			break
		}

		// Update the page number to get the next page.
		options.PageNumber = wl.NextPage
	}

	// Sort the result so we have consistent output.
	sort.StringSlice(names).Sort()

	return names, nil
}
441450
func (v *Value) IncludeSpaces() []string {
	if v.Spaces == nil {
		return nil
	}
	return v.extractItems(*v.Spaces, true)
}
429309
func (s *StateStore) AllocsByNamespace(ws memdb.WatchSet, namespace string) (memdb.ResultIterator, error) {
	txn := s.db.Txn(false)
	return s.allocsByNamespaceImpl(ws, txn, namespace)
}
259449
func (env *maasEnviron) Spaces(ctx context.ProviderCallContext) ([]network.SpaceInfo, error) {
	if !env.usingMAAS2() {
		return env.spaces1(ctx)
	}
	return env.spaces2(ctx)
}
648923
func (api *subnetsAPI) AllSpaces() (params.SpaceResults, error) {
	if err := api.checkCanRead(); err != nil {
		return params.SpaceResults{}, err
	}

	var results params.SpaceResults

	spaces, err := api.backing.AllSpaces()
	if err != nil {
		return results, errors.Trace(err)
	}

	results.Results = make([]params.SpaceResult, len(spaces))
	for i, space := range spaces {
		// TODO(dimitern): Add a Tag() a method and use it here. Too
		// early to do it now as it will just complicate the tests.
		tag := names.NewSpaceTag(space.Name())
		results.Results[i].Tag = tag.String()
	}
	return results, nil
}
496110
func (s *statefulSetLister) StatefulSets(namespace string) StatefulSetNamespaceLister {
	return statefulSetNamespaceLister{indexer: s.indexer, namespace: namespace}
}
290134
func (c *UserController) ListSpaces(ctx *app.ListSpacesUserContext) error {
	client, err := newAuthClient(ctx, c.config, c.httpOptions...)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	res, err := client.ListResourcesUser(goasupport.ForwardContextRequestID(ctx), authservice.ListResourcesUserPath(), authorization.ResourceTypeSpace)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"err": err.Error(),
		}, "unable to get spaces with a role from the auth service")
		return jsonapi.JSONErrorResponse(ctx, errs.Wrap(err, "unable to get spaces with a role from the auth service"))
	}
	defer rest.CloseResponse(res)

	switch res.StatusCode {
	case 200:
	// OK
	case 401:
		return jsonapi.JSONErrorResponse(ctx, errors.NewUnauthorizedError(rest.ReadBody(res.Body)))
	default:
		return jsonapi.JSONErrorResponse(ctx, errors.NewInternalError(ctx, errs.Errorf("status: %s, body: %s", res.Status, rest.ReadBody(res.Body))))
	}

	spaces, err := client.DecodeUserResourcesList(res)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"err": err.Error(),
		}, "unable to decode spaces with a role from the auth service")
		return jsonapi.JSONErrorResponse(ctx, errs.Wrap(err, "unable to decode spaces with a role from the auth service"))
	}
	result, err := convertToUserSpaces(ctx, ctx.Request, c.db, spaces)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"err": err.Error(),
		}, "unable to returns spaces with a role from the auth service")
		return jsonapi.JSONErrorResponse(ctx, errs.Wrap(err, "unable to return spaces with a role from the auth service"))
	}
	return ctx.OK(result)
}
121733
func (c *CodebaseController) ListWorkspaces(ctx *app.ListWorkspacesCodebaseContext) error {
	_, err := login.ContextIdentity(ctx)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, goa.ErrUnauthorized(err.Error()))
	}
	var cb *codebase.Codebase
	err = application.Transactional(c.db, func(appl application.Application) error {
		cb, err = appl.Codebases().Load(ctx, ctx.CodebaseID)
		return err
	})
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error()))
	}
	ns, err := c.getCheNamespace(ctx)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error()))
	}
	cheClient, err := c.NewCheClient(ctx, ns)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error()))
	}
	workspaces, err := cheClient.ListWorkspaces(ctx, cb.URL)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"codebase_id": cb.ID,
			"err":         err,
		}, "unable fetch list of workspaces")
		return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error()))
	}

	var existingWorkspaces []*app.Workspace
	for _, workspace := range workspaces {
		codebaseRelatedLink := rest.AbsoluteURL(ctx.Request, fmt.Sprintf(app.CodebaseHref(cb.ID)))
		openLink := rest.AbsoluteURL(ctx.Request, fmt.Sprintf(app.CodebaseHref(cb.ID)+"/open/%v", workspace.Config.Name))

		ideLink := workspace.GetHrefByRelOfWorkspaceLink(che.IdeUrlRel)
		selfLink := workspace.GetHrefByRelOfWorkspaceLink(che.SelfLinkRel)

		existingWorkspaces = append(existingWorkspaces, &app.Workspace{
			Attributes: &app.WorkspaceAttributes{
				ID:          &workspace.ID,
				Name:        &workspace.Config.Name,
				Description: &workspace.Description,
				Status:      &workspace.Status,
			},
			Type: "workspaces",
			Links: &app.WorkspaceLinks{
				Open: &openLink,
				Self: &selfLink,
				Ide:  &ideLink,
			},
			Relationships: &app.WorkspaceRelations{
				Codebase: &app.RelationGeneric{
					Links: &app.GenericLinks{
						Related: &codebaseRelatedLink,
					},
					Meta: map[string]interface{}{"branch": getBranch(workspace.Config.Projects, cb.URL)},
				},
			},
		})
	}

	createLink := rest.AbsoluteURL(ctx.Request, app.CodebaseHref(cb.ID)+"/create")
	resp := &app.WorkspaceList{
		Data: existingWorkspaces,
		Links: &app.WorkspaceEditLinks{
			Create: &createLink,
		},
	}

	return ctx.OK(resp)
}
1028950
func (b *Builder) AllNamespaces(allNamespace bool) *Builder {
	if allNamespace {
		b.namespace = api.NamespaceAll
	}
	return b
}
613162
func (t *Template) GetAllAWSWorkSpacesWorkspaceResources() map[string]*resources.AWSWorkSpacesWorkspace {
	results := map[string]*resources.AWSWorkSpacesWorkspace{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case *resources.AWSWorkSpacesWorkspace:
			results[name] = resource
		}
	}
	return results
}
1203090
func (s *DescribeWorkspacesInput) SetWorkspaceIds(v []*string) *DescribeWorkspacesInput {
	s.WorkspaceIds = v
	return s
}
249670
func (a *AuthWithRoles) GetNamespaces() ([]services.Namespace, error) {
	if err := a.action(defaults.Namespace, services.KindNamespace, services.VerbList); err != nil {
		return nil, trace.Wrap(err)
	}
	if err := a.action(defaults.Namespace, services.KindNamespace, services.VerbRead); err != nil {
		return nil, trace.Wrap(err)
	}
	return a.authServer.GetNamespaces()
}
1343912
func (m *Meta) selectWorkspace(b backend.Backend) error {
	workspaces, err := b.Workspaces()
	if err != nil {
		if err == backend.ErrWorkspacesNotSupported {
			return nil
		}
		return fmt.Errorf("Failed to get migrated workspaces: %s", err)
	}

	if len(workspaces) == 0 {
		return fmt.Errorf(strings.TrimSpace(errBackendNoMigratedWorkspaces))
	}

	// Get the currently selected workspace.
	workspace := m.Workspace()

	// Check if any of the migrated workspaces match the selected workspace
	// and create a numbered list with migrated workspaces.
	var list strings.Builder
	for i, w := range workspaces {
		if w == workspace {
			return nil
		}
		fmt.Fprintf(&list, "%d. %s\n", i+1, w)
	}

	// If the selected workspace is not migrated, ask the user to select
	// a workspace from the list of migrated workspaces.
	v, err := m.UIInput().Input(context.Background(), &terraform.InputOpts{
		Id: "select-workspace",
		Query: fmt.Sprintf(
			"\n[reset][bold][yellow]The currently selected workspace (%s) is not migrated.[reset]",
			workspace),
		Description: fmt.Sprintf(
			strings.TrimSpace(inputBackendSelectWorkspace), list.String()),
	})
	if err != nil {
		return fmt.Errorf("Failed to select workspace: %s", err)
	}

	idx, err := strconv.Atoi(v)
	if err != nil || (idx < 1 || idx > len(workspaces)) {
		return fmt.Errorf("Failed to select workspace: input not a valid number")
	}

	return m.SetWorkspace(workspaces[idx-1])
}
749693
func (env *environ) Spaces(ctx context.ProviderCallContext) ([]network.SpaceInfo, error) {
	if err := env.checkBroken("Spaces"); err != nil {
		return []network.SpaceInfo{}, err
	}
	return []network.SpaceInfo{{
		Name:       "foo",
		ProviderId: network.Id("0"),
		Subnets: []network.SubnetInfo{{
			ProviderId:        network.Id("1"),
			AvailabilityZones: []string{"zone1"},
		}, {
			ProviderId:        network.Id("2"),
			AvailabilityZones: []string{"zone1"},
		}}}, {
		Name:       "Another Foo 99!",
		ProviderId: "1",
		Subnets: []network.SubnetInfo{{
			ProviderId:        network.Id("3"),
			AvailabilityZones: []string{"zone1"},
		}}}, {
		Name:       "foo-",
		ProviderId: "2",
		Subnets: []network.SubnetInfo{{
			ProviderId:        network.Id("4"),
			AvailabilityZones: []string{"zone1"},
		}}}, {
		Name:       "---",
		ProviderId: "3",
		Subnets: []network.SubnetInfo{{
			ProviderId:        network.Id("5"),
			AvailabilityZones: []string{"zone1"},
		}}}}, nil
}
622278
func (s *WorkspaceDirectory) SetWorkspaceCreationProperties(v *DefaultWorkspaceCreationProperties) *WorkspaceDirectory {
	s.WorkspaceCreationProperties = v
	return s
}
928084
func (r *Resolver) GetAllKeyspaces(ctx context.Context) ([]string, error) {
	keyspaces, err := r.topoServ.GetSrvKeyspaceNames(ctx, r.localCell)
	if err != nil {
		return nil, vterrors.Errorf(vtrpcpb.Code_UNKNOWN, "keyspace names fetch error: %v", err)
	}
	// FIXME(alainjobart) this should be unnecessary. The results
	// of ListDir are sorted, and that's the underlying topo code.
	// But the tests depend on this behavior now.
	sort.Strings(keyspaces)
	return keyspaces, nil
}