Skip to content

fix(compiler): create task.dir before running dynamic (sh:) vars#2800

Open
SAY-5 wants to merge 1 commit intogo-task:mainfrom
SAY-5:fix-dir-mkdir-dynamic-var-1001
Open

fix(compiler): create task.dir before running dynamic (sh:) vars#2800
SAY-5 wants to merge 1 commit intogo-task:mainfrom
SAY-5:fix-dir-mkdir-dynamic-var-1001

Conversation

@SAY-5
Copy link
Copy Markdown

@SAY-5 SAY-5 commented Apr 17, 2026

Fixes #1001.

Problem

A tasks dir: is documented as being created on demand:

dir — Directory which this task should run. Defaults to the current working directory. If the directory does not exist, Task creates it.

but dynamic variables (sh:) are compiled before the tasks mkdir step runs. So this Taskfile:

test-dir:
  dir: does-not-exist
  cmds:
    - echo {{.TEST}}
  vars:
    TEST:
      sh: cat ../exist.txt

aborts with a cryptic chdir error:

task: Command "cat ../exist.txt" failed: chdir /…/does-not-exist: no such file or directory

even though running the same command inside cmds: works fine, because mkdir runs before runCommand for normal commands but after variable compilation.

Fix

Compiler.HandleDynamicVar now creates dir with 0o755 (the same permissions Executor.mkdir uses at task.go:311) before calling execext.RunCommand. Dynamic variables and cmds now see the same filesystem state, and the documented dir: semantics hold for both.

if dir != "" {
    if _, err := os.Stat(dir); os.IsNotExist(err) {
        if err := os.MkdirAll(dir, 0o755); err != nil {
            return "", fmt.Errorf(...)
        }
    }
}

No behaviour change when the directory already exists; no behaviour change for tasks without sh: vars.

Signed off per DCO.

A task's 'dir:' is documented as being created on demand, but dynamic
variables (sh:) compile before the task's mkdir runs. With a
non-existent dir, the shell exec aborts with:

    task: Command "cat ../exist.txt" failed: chdir
    /path/does-not-exist: no such file or directory

even though the same command inside cmds: works fine because mkdir
runs first.

Create the directory (same 0o755 perms as the main task.mkdir uses)
in HandleDynamicVar before launching the shell, so sh: variables and
cmds: see the same filesystem state.

Fixes go-task#1001

Signed-off-by: Sai Asish Y <say.apm35@gmail.com>
Copy link
Copy Markdown
Contributor

@trulede trulede left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the wrong approach to solve this problem. A non-existent path should cause an error, not just create the directory regardless.

The problem needs to be solved elsewhere in the code base.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

dir does not create a directory in some cases

2 participants