Skip to content

Commit

Permalink
embed: treat uninitialized FS as empty
Browse files Browse the repository at this point in the history
As described in the FS documentation.

This prevents http.FS and other clients from panicking when the
go:embed directive is missing.

For #43682
Related #43698

Change-Id: Iecf26d229a099e55d24670c3119cd6c6d17ecc6e
Reviewed-on: https://go-review.googlesource.com/c/go/+/283852
Run-TryBot: Jay Conrod <jayconrod@google.com>
TryBot-Result: Go Bot <gobot@golang.org>
Trust: Jay Conrod <jayconrod@google.com>
Reviewed-by: Bryan C. Mills <bcmills@google.com>
  • Loading branch information
Jay Conrod committed Jan 19, 2021
1 parent d047c91 commit ca5774a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/embed/embed.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,9 @@ func (f FS) lookup(name string) *file {
if name == "." {
return dotFile
}
if f.files == nil {
return nil
}

// Binary search to find where name would be in the list,
// and then check if name is at that position.
Expand All @@ -261,6 +264,9 @@ func (f FS) lookup(name string) *file {

// readDir returns the list of files corresponding to the directory dir.
func (f FS) readDir(dir string) []file {
if f.files == nil {
return nil
}
// Binary search to find where dir starts and ends in the list
// and then return that slice of the list.
files := *f.files
Expand Down
17 changes: 17 additions & 0 deletions src/embed/internal/embedtest/embed_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,20 @@ func TestHidden(t *testing.T) {
testDir(t, star, "testdata/.hidden",
"fortune.txt", "more/") // but not .more or _more
}

func TestUninitialized(t *testing.T) {
var uninitialized embed.FS
testDir(t, uninitialized, ".")
f, err := uninitialized.Open(".")
if err != nil {
t.Fatal(err)
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
t.Fatal(err)
}
if !fi.IsDir() {
t.Errorf("in uninitialized embed.FS, . is not a directory")
}
}

0 comments on commit ca5774a

Please sign in to comment.