Skip to content

Commit

Permalink
Set proper Kptfile name when running init in current dir
Browse files Browse the repository at this point in the history
  • Loading branch information
mortent committed Jul 15, 2020
1 parent 0e99151 commit 5f1a195
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 5 deletions.
15 changes: 10 additions & 5 deletions internal/cmdinit/cmdinit.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,17 @@ type Runner struct {
URL string
}

func (r *Runner) preRunE(c *cobra.Command, args []string) error {
if len(args) == 0 {
args = []string{"."}
}
func (r *Runner) preRunE(_ *cobra.Command, args []string) error {
if r.Name == "" {
r.Name = filepath.Base(args[0])
if len(args) == 0 || args[0] == "." {
path, err := os.Getwd()
if err != nil {
return errors.Errorf("can't lookup current directory: %v", err)
}
r.Name = filepath.Base(path)
} else {
r.Name = filepath.Base(args[0])
}
}
return nil
}
Expand Down
40 changes: 40 additions & 0 deletions internal/cmdinit/cmdinit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,46 @@ my description
`, string(b))
}

func TestCmd_currentDir(t *testing.T) {
d, err := ioutil.TempDir("", "kpt")
assert.NoError(t, err)
assert.NoError(t, os.Mkdir(filepath.Join(d, "my-pkg"), 0700))

packageDir := filepath.Join(d, "my-pkg")
currentDir, err := os.Getwd()
assert.NoError(t, err)
err = func() error {
nestedErr := os.Chdir(packageDir)
if nestedErr != nil {
return nestedErr
}
defer func() {
deferErr := os.Chdir(currentDir)
if deferErr != nil {
panic(deferErr)
}
}()

r := cmdinit.NewRunner("kpt")
r.Command.SetArgs([]string{".", "--description", "my description", "--tag", "app.kpt.dev/cockroachdb"})
return r.Command.Execute()
}()
assert.NoError(t, err)

// verify the contents
b, err := ioutil.ReadFile(filepath.Join(packageDir, "Kptfile"))
assert.NoError(t, err)
assert.Equal(t, `apiVersion: kpt.dev/v1alpha1
kind: Kptfile
metadata:
name: my-pkg
packageMetadata:
tags:
- app.kpt.dev/cockroachdb
shortDescription: my description
`, string(b))
}

// TestCmd_failExists verifies the command throws and error if the directory exists
func TestCmd_failNotExists(t *testing.T) {
d, err := ioutil.TempDir("", "kpt")
Expand Down

0 comments on commit 5f1a195

Please sign in to comment.