pulumi/cmd/init.go
Matt Ellis 8f076b7cb3 Argument validation for CLI commands
Previously, we were inconsistent on how we handled argument validation
in the CLI. Many commands used cobra.Command's Args property to
provide a validator if they took arguments, but commands which did not
rarely used cobra.NoArgs to indicate this.

This change does two things:

1. Introduce `cmdutil.ArgsFunc` which works like `cmdutil.RunFunc`, it
wraps an existing cobra type and lets us control the behavior when an
arguments validator fails.

2. Ensure every command sets the Args property with an instance of
cmdutil.ArgsFunc. The cmdutil package defines wrapers for all the
cobra validators we are using, to prevent us from having to spell out
`cmduitl.ArgsFunc(...)` everywhere.

Fixes #588
2017-11-29 16:10:53 -08:00

73 lines
1.6 KiB
Go

// Copyright 2016-2017, Pulumi Corporation. All rights reserved.
package cmd
import (
"fmt"
"os"
"github.com/pulumi/pulumi/pkg/util/cmdutil"
"github.com/pulumi/pulumi/pkg/workspace"
"github.com/spf13/cobra"
)
func newInitCmd() *cobra.Command {
var owner string
var name string
cmd := &cobra.Command{
Use: "init",
Short: "Initialize a new Pulumi repository",
Args: cmdutil.NoArgs,
Run: cmdutil.RunFunc(func(cmd *cobra.Command, args []string) error {
cwd, err := os.Getwd()
if err != nil {
return err
}
repo, err := workspace.GetRepository(cwd)
if err != nil && err != workspace.ErrNoRepository {
return err
}
if err == workspace.ErrNoRepository {
// No existing repository, so we'll need to create one
repo = workspace.NewRepository(cwd)
detectedOwner, detectedName, detectErr := detectOwnerAndName(cwd)
if detectErr != nil {
return detectErr
}
repo.Owner = detectedOwner
repo.Name = detectedName
}
// explicit command line arguments should overwrite any existing values
if owner != "" {
repo.Owner = owner
}
if name != "" {
repo.Name = name
}
err = repo.Save()
if err != nil {
return err
}
fmt.Printf("Initialized Pulumi repository in %s\n", repo.Root)
return nil
}),
}
cmd.PersistentFlags().StringVar(
&owner, "owner", "",
"Override the repository owner; default is taken from current Git repository or username")
cmd.PersistentFlags().StringVar(
&name, "name", "",
"Override the repository name; default is taken from current Git repository or current working directory")
return cmd
}