From d6951213ce710f68184df56d6d7d4a3d4e3e4c8b Mon Sep 17 00:00:00 2001 From: WindSoilder Date: Sun, 20 Sep 2026 14:50:18 +0800 Subject: [PATCH] fix background task with module usage --- modules/background_task/README.md | 3 +++ modules/background_task/task.nu | 25 +++++++++++++++++-------- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/modules/background_task/README.md b/modules/background_task/README.md index a43bc36d1..4d092814d 100644 --- a/modules/background_task/README.md +++ b/modules/background_task/README.md @@ -67,6 +67,9 @@ task spawn { foo bar } ``` + +If you spawn the task with `--working-directory`, make sure any relative imports are valid from that directory. + ## Troubleshooting - On some setups (e.g. NixOS with `nu` installed as a binary in user's `$HOME`), `sh` (which `pueue` delegates tasks to run) might fail to find `nu` in the `$PATH`. In this case hard-coding the location of your nu binary in the `task spawn` function definition in `task.nu` can solve the issue. diff --git a/modules/background_task/task.nu b/modules/background_task/task.nu index ffd4d65db..3fa6cdfa5 100644 --- a/modules/background_task/task.nu +++ b/modules/background_task/task.nu @@ -47,6 +47,14 @@ export def spawn [ $args = ($args | prepend ["--label" $label]) } + # Keep the generated script outside the task's working directory, but add that + # directory to Nu's include path so relative `use`/`source` statements inside + # the closure still resolve as they did at `task spawn` time. + let task_working_directory = if $working_directory != null { + $working_directory + } else { + $env.PWD + } let source_path = mktemp --tmpdir --suffix "-nu-task" ( @@ -57,7 +65,7 @@ export def spawn [ ) | save --force $source_path - (pueue add --print-task-id ...$args $"nu --config '($nu.config-path)' --env-config '($nu.env-path)' ($source_path)") + (pueue add --print-task-id ...$args $"nu --config '($nu.config-path)' --env-config '($nu.env-path)' -I '($task_working_directory)' '($source_path)'") } # Remove tasks from the queue. @@ -317,13 +325,14 @@ export def log [ --detailed (-d) # Include all fields, don't simplify output. ] { def resolve-nu-task [cmd: string] { - if ($cmd starts-with "nu") and ($cmd ends-with "-nu-task") { - let path = ($cmd | str trim | split row " " | last) - if ($path | path exists) { - open --raw $path | str trim | nu-highlight - } else { - $cmd - } + let nu_task_path = ( + $cmd + | parse --regex "^nu(?: .*?)? '?(.+?-nu-task)'?$" + | get -o 0.capture0 + ) + + if $nu_task_path != null and ($nu_task_path | path exists) { + open --raw $nu_task_path | str trim | nu-highlight } else { $cmd }