support embedding via embed.FS

We already added support for "//go:embed" with string and []byte,
by not obfuscating the "embed" import path.

However, embed.FS was still failing:

	> garble build
	[stderr]
	# test/main
	:13: go:embed cannot apply to var of type embed.WtKNvwbN

The compiler detects the type by matching its name to exactly "embed.FS",
so don't obfuscate the name "FS" either.

While at it, ensure that the embed code behaves the same with "go build".

Updates #349.
pull/351/head
Daniel Martí 3 years ago committed by Andrew LeFevre
parent 680e5624e9
commit e2ddce75a7

@ -1190,6 +1190,14 @@ func (tf *transformer) transformGo(file *ast.File) *ast.File {
return true // could be a Go plugin API
}
if pkg.Path() == "embed" {
// The Go compiler needs to detect types such as embed.FS.
// That will fail if we change the import path or type name.
// Leave it as is.
// Luckily, the embed package just declares the FS type.
return true
}
// We don't want to obfuscate this object.
if tf.ignoreObjects[obj] {
return true

@ -5,6 +5,12 @@ garble build
exec ./main
cmp stdout main.stdout
[short] stop # no need to verify this with -short
go build
exec ./main
cmp stdout main.stdout
-- go.mod --
module test/main
@ -14,18 +20,44 @@ go 1.16
package main
import (
_ "embed"
"embed"
"fmt"
"io/fs"
)
//go:embed test.txt
var x string
//go:embed embed-string.txt
var embedStr string
//go:embed embed-dir
var embedDir embed.FS
func main() {
fmt.Printf("%q\n", x)
fmt.Printf("%q\n", embedStr)
fs.WalkDir(embedDir, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
fmt.Printf("%s: %v\n", path, err)
return nil
}
if !d.IsDir() {
body, err := fs.ReadFile(embedDir, path)
if err != nil {
fmt.Printf("%s: %v\n", path, err)
return nil
}
fmt.Printf("%s: %q\n", path, body)
}
return nil
})
}
-- test.txt --
test content
-- embed-string.txt --
string content
-- embed-dir/file1.txt --
file1 content
-- embed-dir/file2.txt --
file2 content
-- main.stdout --
"test content\n"
"string content\n"
embed-dir/file1.txt: "file1 content\n"
embed-dir/file2.txt: "file2 content\n"

Loading…
Cancel
Save