diff --git a/internal/filepathext/filepathext.go b/internal/filepathext/filepathext.go index f2a1ba15a0..9154a55868 100644 --- a/internal/filepathext/filepathext.go +++ b/internal/filepathext/filepathext.go @@ -3,7 +3,8 @@ package filepathext import ( "os" "path/filepath" - "strings" + "regexp" + "slices" ) // SmartJoin joins two paths, but only if the second is not already an @@ -25,19 +26,14 @@ func IsAbs(path string) bool { return filepath.IsAbs(path) } -var knownAbsDirs = []string{ - ".ROOT_DIR", - ".TASKFILE_DIR", - ".USER_WORKING_DIR", -} +var ( + templateActionRE = regexp.MustCompile(`\{\{[^{}]*\}\}`) + // Use a Unicode-aware boundary so longer variable names remain relative. + specialDirRE = regexp.MustCompile(`\.(ROOT_DIR|TASKFILE_DIR|USER_WORKING_DIR)([^\pL\p{Nd}_]|$)`) +) func isSpecialDir(dir string) bool { - for _, d := range knownAbsDirs { - if strings.Contains(dir, d) { - return true - } - } - return false + return slices.ContainsFunc(templateActionRE.FindAllString(dir, -1), specialDirRE.MatchString) } // TryAbsToRel tries to convert an absolute path to relative based on the diff --git a/internal/filepathext/filepathext_test.go b/internal/filepathext/filepathext_test.go new file mode 100644 index 0000000000..e3bbd14b1b --- /dev/null +++ b/internal/filepathext/filepathext_test.go @@ -0,0 +1,47 @@ +package filepathext + +import ( + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestIsAbs(t *testing.T) { + t.Parallel() + + absolute, err := filepath.Abs("file.txt") + require.NoError(t, err) + + for _, test := range []struct { + path string + wantAbs bool + }{ + {"", false}, + {"project.ROOT_DIR/file.txt", false}, + {".TASKFILE_DIR/file.txt", false}, + {"project.USER_WORKING_DIR/file.txt", false}, + {"{{.PROJECT}}.ROOT_DIR{{.SUFFIX}}/file.txt", false}, + {"{{ .ROOT_DIR/file.txt", false}, + {"{{.PROJECT}}/file.txt", false}, + {"{{.ROOT_DIR_SUFFIX}}/file.txt", false}, + {"{{.ROOT_DIR2}}/file.txt", false}, + {"{{.ROOT_DIRsuffix}}/file.txt", false}, + {"{{.ROOT_DIR变量}}/file.txt", false}, + {absolute, true}, + {"{{.ROOT_DIR}}/file.txt", true}, + {"{{ .TASKFILE_DIR }}/file.txt", true}, + {"{{- .USER_WORKING_DIR -}}/file.txt", true}, + {"{{.ROOT_DIR|toSlash}}/file.txt", true}, + {"{{(.ROOT_DIR)}}/file.txt", true}, + {"{{.PROJECT}}/{{.ROOT_DIR}}/file.txt", true}, + {"{{\n.TASKFILE_DIR\n}}/file.txt", true}, + {`{{joinPath .ROOT_DIR "src"}}/file.txt`, true}, + } { + t.Run(test.path, func(t *testing.T) { + t.Parallel() + + require.Equal(t, test.wantAbs, IsAbs(test.path)) + }) + } +}