pulumi/cmd/stack_ls.go

106 lines
2.3 KiB
Go
Raw Normal View History

2017-06-26 23:46:34 +02:00
// Copyright 2016-2017, Pulumi Corporation. All rights reserved.
package cmd
import (
"fmt"
2017-10-10 02:47:55 +02:00
"io/ioutil"
"os"
"path/filepath"
"strconv"
2017-10-10 02:47:55 +02:00
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/encoding"
"github.com/pulumi/pulumi/pkg/tokens"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/util/cmdutil"
)
func newStackLsCmd() *cobra.Command {
return &cobra.Command{
2017-09-23 00:29:24 +02:00
Use: "ls",
Short: "List all known stacks",
Run: cmdutil.RunFunc(func(cmd *cobra.Command, args []string) error {
currentStack, err := getCurrentStack()
if err != nil {
// If we couldn't figure out the current stack, just don't print the '*' later
// on instead of failing.
currentStack = tokens.QName("")
}
stacks, err := getStacks()
if err != nil {
return err
}
fmt.Printf("%-20s %-48s %-12s\n", "NAME", "LAST UPDATE", "RESOURCE COUNT")
for _, stack := range stacks {
_, _, snapshot, err := getStack(stack)
2017-10-10 02:47:55 +02:00
if err != nil {
continue
}
// Now print out the name, last deployment time (if any), and resources (if any).
lastDeploy := "n/a"
resourceCount := "n/a"
2017-10-10 02:47:55 +02:00
if snapshot != nil {
lastDeploy = snapshot.Time.String()
2017-10-10 02:47:55 +02:00
resourceCount = strconv.Itoa(len(snapshot.Resources))
}
display := stack.String()
if stack == currentStack {
display += "*" // fancify the current stack.
}
fmt.Printf("%-20s %-48s %-12s\n", display, lastDeploy, resourceCount)
}
return nil
}),
}
}
2017-10-10 02:47:55 +02:00
func getStacks() ([]tokens.QName, error) {
var stacks []tokens.QName
2017-10-10 02:47:55 +02:00
w, err := newWorkspace()
if err != nil {
return nil, err
}
// Read the stack directory.
path := w.StackPath("")
2017-10-10 02:47:55 +02:00
files, err := ioutil.ReadDir(path)
if err != nil && !os.IsNotExist(err) {
return nil, errors.Errorf("could not read stacks: %v", err)
2017-10-10 02:47:55 +02:00
}
for _, file := range files {
// Ignore directories.
if file.IsDir() {
continue
}
// Skip files without valid extensions (e.g., *.bak files).
stackfn := file.Name()
ext := filepath.Ext(stackfn)
2017-10-10 02:47:55 +02:00
if _, has := encoding.Marshalers[ext]; !has {
continue
}
// Read in this stack's information.
name := tokens.QName(stackfn[:len(stackfn)-len(ext)])
_, _, _, err := getStack(name)
2017-10-10 02:47:55 +02:00
if err != nil {
continue // failure reading the stack information.
2017-10-10 02:47:55 +02:00
}
stacks = append(stacks, name)
2017-10-10 02:47:55 +02:00
}
return stacks, nil
2017-10-10 02:47:55 +02:00
}