From 3c51625c7152abca7e035fae15fc6807ca21cc86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Pedersen?= Date: Fri, 30 Dec 2022 11:10:49 +0100 Subject: [PATCH] Make readFile return nil when file not found (note) Fixes #9620 --- tpl/os/integration_test.go | 26 ++++++++++++++++++++++++++ tpl/os/os.go | 7 ++++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/tpl/os/integration_test.go b/tpl/os/integration_test.go index fe1bb3d6e..d08374f8f 100644 --- a/tpl/os/integration_test.go +++ b/tpl/os/integration_test.go @@ -49,3 +49,29 @@ START:|{{ range $entry := $entries }}{{ if not $entry.IsDir }}{{ $entry.Name }}| START:|config.toml|myproject.txt|:END: `) } + +// Issue 9620 +func TestReadFileNotExists(t *testing.T) { + t.Parallel() + + files := ` +-- config.toml -- +-- layouts/index.html -- +{{ $fi := (readFile "doesnotexist") }} +{{ if $fi }}Failed{{ else }}OK{{ end }} + + + ` + + b := hugolib.NewIntegrationTestBuilder( + hugolib.IntegrationTestConfig{ + T: t, + TxtarString: files, + NeedsOsFS: true, + }, + ).Build() + + b.AssertFileContent("public/index.html", ` +OK +`) +} diff --git a/tpl/os/os.go b/tpl/os/os.go index e7fd05939..4c7089779 100644 --- a/tpl/os/os.go +++ b/tpl/os/os.go @@ -22,6 +22,7 @@ import ( "path/filepath" "github.com/bep/overlayfs" + "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/deps" "github.com/spf13/afero" "github.com/spf13/cast" @@ -101,7 +102,11 @@ func (ns *Namespace) ReadFile(i any) (string, error) { s = ns.deps.PathSpec.RelPathify(s) } - return readFile(ns.readFileFs, s) + s, err = readFile(ns.readFileFs, s) + if err != nil && herrors.IsNotExist(err) { + return "", nil + } + return s, err } // ReadDir lists the directory contents relative to the configured WorkingDir.