github.com/myhau/pulumi/pkg/v3@v3.70.2-0.20221116134521-f2775972e587/backend/state/stacks.go (about)

     1  // Copyright 2016-2018, Pulumi Corporation.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package state
    16  
    17  import (
    18  	"context"
    19  
    20  	"github.com/pulumi/pulumi/pkg/v3/backend"
    21  	"github.com/pulumi/pulumi/sdk/v3/go/common/workspace"
    22  )
    23  
    24  // CurrentStack reads the current stack and returns an instance connected to its backend provider.
    25  func CurrentStack(ctx context.Context, backend backend.Backend) (backend.Stack, error) {
    26  	w, err := workspace.New()
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  
    31  	stackName := w.Settings().Stack
    32  	if stackName == "" {
    33  		return nil, nil
    34  	}
    35  
    36  	ref, err := backend.ParseStackReference(stackName)
    37  	if err != nil {
    38  		return nil, err
    39  	}
    40  
    41  	return backend.GetStack(ctx, ref)
    42  }
    43  
    44  // SetCurrentStack changes the current stack to the given stack name.
    45  func SetCurrentStack(name string) error {
    46  	// Switch the current workspace to that stack.
    47  	w, err := workspace.New()
    48  	if err != nil {
    49  		return err
    50  	}
    51  
    52  	w.Settings().Stack = name
    53  	return w.Save()
    54  }