From c663c5c5071060069a5c29fae36c1cff72ef523e Mon Sep 17 00:00:00 2001 From: Marco Molteni Date: Tue, 4 Jun 2019 18:58:22 +0200 Subject: [PATCH] When "dir:" attribute points to a non-existing dir, create it Closes #209 --- task.go | 9 +++++++ task_test.go | 26 +++++++++++++++++++ .../dir/explicit_doesnt_exist/Taskfile.yml | 8 ++++++ 3 files changed, 43 insertions(+) create mode 100644 testdata/dir/explicit_doesnt_exist/Taskfile.yml diff --git a/task.go b/task.go index 2df08c2c..1e5f430e 100644 --- a/task.go +++ b/task.go @@ -200,6 +200,15 @@ func (e *Executor) RunTask(ctx context.Context, call taskfile.Call) error { } } + // When using the dir: attribute it can happen that the directory doesn't exist. + // If so, we create it. + if _, err := os.Stat(t.Dir); os.IsNotExist(err) { + if err := os.MkdirAll(t.Dir, 0755); err != nil { + e.Logger.Errf("cannot make directory %v: %v", t.Dir, err) + return err + } + } + for i := range t.Cmds { if err := e.runCommand(ctx, t, call, i); err != nil { if err2 := e.statusOnError(t); err2 != nil { diff --git a/task_test.go b/task_test.go index 85887265..bb73b56a 100644 --- a/task_test.go +++ b/task_test.go @@ -611,3 +611,29 @@ func TestWhenDirAttributeAndDirExistsItRunsInThatDir(t *testing.T) { assert.Equal(t, expected, got, "Mismatch in the working directory") } +func TestWhenDirAttributeItCreatesMissingAndRunsInThatDir(t *testing.T) { + const expected = "createme" + const dir = "testdata/dir/explicit_doesnt_exist/" + const toBeCreated = dir + expected + const target = "whereami" + var out bytes.Buffer + e := &task.Executor{ + Dir: dir, + Stdout: &out, + Stderr: &out, + } + + // Ensure that the directory to be created doesn't actually exist. + _ = os.Remove(toBeCreated) + if _, err := os.Stat(toBeCreated); err == nil { + t.Errorf("Directory should not exist: %v", err) + } + assert.NoError(t, e.Setup()) + assert.NoError(t, e.Run(context.Background(), taskfile.Call{Task: target})) + + got := strings.TrimSuffix(filepath.Base(out.String()), "\n") + assert.Equal(t, expected, got, "Mismatch in the working directory") + + // Clean-up after ourselves only if no error. + _ = os.Remove(toBeCreated) +} diff --git a/testdata/dir/explicit_doesnt_exist/Taskfile.yml b/testdata/dir/explicit_doesnt_exist/Taskfile.yml new file mode 100644 index 00000000..1b6fb7d1 --- /dev/null +++ b/testdata/dir/explicit_doesnt_exist/Taskfile.yml @@ -0,0 +1,8 @@ +version: '2' + +tasks: + whereami: + dir: createme + cmds: + - pwd + silent: true