Go version
1.22.4
Output of go env
in your module/workspace:
GO111MODULE=''
GOARCH='amd64'
GOBIN='/home/martin/.local/gobin'
GOCACHE='/home/martin/.cache/go/cache'
GOENV='/home/martin/.config/go/env'
GOEXE=''
GOEXPERIMENT=''
GOFLAGS='-modcacherw'
GOHOSTARCH='amd64'
GOHOSTOS='linux'
GOINSECURE=''
GOMODCACHE='/home/martin/.cache/go/pkg/mod'
GONOPROXY=''
GONOSUMDB=''
GOOS='linux'
GOPATH='/home/martin/.cache/go'
GOPRIVATE=''
GOPROXY='https://proxy.golang.org,direct'
GOROOT='/usr/lib/go'
GOSUMDB='sum.golang.org'
GOTMPDIR='/home/martin/.cache/go/tmp'
GOTOOLCHAIN='auto'
GOTOOLDIR='/usr/lib/go/pkg/tool/linux_amd64'
GOVCS=''
GOVERSION='go1.22.4'
GCCGO='gccgo'
GOAMD64='v1'
AR='ar'
CC='cc'
CXX='c++'
CGO_ENABLED='1'
GOMOD='/home/martin/testtmp/go.mod'
GOWORK=''
CGO_CFLAGS='-O2 -g'
CGO_CPPFLAGS=''
CGO_CXXFLAGS='-O2 -g'
CGO_FFLAGS='-O2 -g'
CGO_LDFLAGS='-O2 -g'
PKG_CONFIG='pkg-config'
GOGCCFLAGS='-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -ffile-prefix-map=/home/martin/.cache/go/tmp/go-build3133883126=/tmp/go-build -gno-record-gcc-switches'
Setup:
% mkdir tmp
% go mod init testtemp
% cat test_test.go
package main
import (
"fmt"
"os"
"testing"
)
func TestTest(t *testing.T) {
fmt.Println(t.TempDir())
fmt.Println(t.TempDir())
os.Chdir("./tmp")
fmt.Println(t.TempDir())
}
This runs fine:
% go test
/tmp/TestTest731866446/001
/tmp/TestTest731866446/002
/tmp/TestTest731866446/003
But when setting TMPDIR to ./tmp it stops working after the os.Chdir() call:
% TMPDIR=./tmp go test
./tmp/TestTest4094023708/001
./tmp/TestTest4094023708/002
--- FAIL: TestTest (0.00s)
test_test.go:13: TempDir: stat ./tmp: no such file or directory
FAIL
exit status 1
FAIL test 0.002s
It needs to be the full path:
% TMPDIR=/home/martin/testtmp/tmp go test
/home/martin/testtmp/tmp/TestTest2010017600/001
/home/martin/testtmp/tmp/TestTest2010017600/002
/home/martin/testtmp/tmp/TestTest2010017600/003
PASS
ok test 0.002s
Context: I have some filesystem-specific code that's sensitive to the current directory, so I need to change it. I have ./tmp mounted as a XFS image to test that it works on that, in addition to ext4.
I can just use the full path of course, but it's fairly long and annoying, and "it works fine, except in this one specific case" is rather confusing. And should be easy enough to fix with filepath.Abs() call.
Comment From: gabyhelp
Similar Issues
- https://github.com/golang/go/issues/23264
- https://github.com/golang/go/issues/19695
- https://github.com/golang/go/issues/40853
- https://github.com/golang/go/issues/50644
- https://github.com/golang/go/issues/61585
(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)
Comment From: seankhliao
I'd say this is working as intended. You want TMPDIR to be relative to the current directory, and it stays relative to your working directory.
TMPDIR=$(pwd)/tmp
isn't that much to type out.