From e2513ad03a2dc3edb932ed7b6cd4ecce51aa18a4 Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 20 Nov 2026 17:59:04 +0000 Subject: [PATCH] Avoid panicking when startup working directory is unavailable --- macaron.go | 9 +++------ macaron_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/macaron.go b/macaron.go index f36bb8e..3b1460b 100644 --- a/macaron.go +++ b/macaron.go @@ -280,7 +280,8 @@ var ( Env = DEV envLock sync.Mutex - // Path of work directory. + // Root is the working directory at startup. It is empty if the directory + // could not be determined. Root string // Flash applies to current request. @@ -309,11 +310,7 @@ func safeEnv() string { func init() { setENV(os.Getenv("MACARON_ENV")) - var err error - Root, err = os.Getwd() - if err != nil { - panic("error getting work directory: " + err.Error()) - } + Root, _ = os.Getwd() } // SetConfig sets data sources for configuration. diff --git a/macaron_test.go b/macaron_test.go index 3add528..89e1d27 100644 --- a/macaron_test.go +++ b/macaron_test.go @@ -19,12 +19,43 @@ import ( "net/http" "net/http/httptest" "os" + "os/exec" + "runtime" "testing" "time" . "github.com/smartystreets/goconvey/convey" ) +func TestInitWithDeletedWorkingDirectory(t *testing.T) { + if runtime.GOOS != "linux" { + t.Skip("requires removing the working directory of a running process") + } + const childEnv = "MACARON_TEST_DELETED_CWD" + if os.Getenv(childEnv) == "1" { + if _, err := os.Getwd(); err == nil { + t.Fatal("expected os.Getwd to fail in the deleted directory") + } + if Root != "" { + t.Fatalf("Root = %q; want empty when os.Getwd fails", Root) + } + return + } + + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + // Delete the directory after the shell enters it, then run package initialization again. + cmd := exec.Command("sh", "-c", `rmdir "$1" && exec "$2" -test.run '^TestInitWithDeletedWorkingDirectory$'`, "sh", dir, exe) + cmd.Dir = dir + cmd.Env = append(cmd.Environ(), childEnv+"=1") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("test process failed to start from a deleted working directory: %v\n%s", err, out) + } +} + func Test_Version(t *testing.T) { Convey("Get version", t, func() { So(Version(), ShouldEqual, _VERSION)