Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

embed, cmd/go: add support for embedded files #41191

Closed
rsc opened this issue Sep 2, 2020 · 131 comments
Closed

embed, cmd/go: add support for embedded files #41191

rsc opened this issue Sep 2, 2020 · 131 comments

Comments

@rsc
Copy link
Contributor

rsc commented Sep 2, 2020

In July, @bradfitz and I posted a draft design for embedded files. The doc links to a video, prototype code, and a Reddit discussion.

The feedback on that design has been overwhelmingly positive.

I propose to adopt the embedded files draft design for Go 1.16, with one addition, suggested in the discussion, to simplify the case of direct access to the bytes in a single embedded file.

As long as a file imports "embed" (import _ "embed" if necessary), it will be permitted to use //go:embed naming a single file (no glob patterns or directory matching allowed) to initialize a plain string or []byte variable:

//go:embed gopher.png
var gopherPNG []byte

The import is required to flag the file as containing //go:embed lines and needing processing. Goimports (and gopls etc) can be taught this rule and automatically add the import in any file with a //go:embed as needed.

The embedded files design depends on the file system interface draft design, which I've also proposed to adopt in #41190.

This issue is only about adopting the embedded files design, under the assumption that the file system interface design is also adopted. If this proposal is accepted before the file system interface design is, we'd simply wait for the file system interface design before starting to land changes.

@jimmyfrasche
Copy link
Member

Would it be an error to have a //go:embed directive without importing embed?

@rsc rsc changed the title embed, cmd/go: add support for embedded files proposal: embed, cmd/go: add support for embedded files Sep 2, 2020
@rsc
Copy link
Contributor Author

rsc commented Sep 2, 2020

@jimmyfrasche Yes, fifth-to-last bullet in list at https://go.googlesource.com/proposal/+/master/design/draft-embed.md#go_embed-directives.

@pierrec
Copy link

pierrec commented Sep 2, 2020

@rsc Maybe I have missed it in the draft, but I don't see the ability to embed a single file that you mention in your comment.
Also, would you be able to embed a single file as a const string as well?
Thanks for this great proposal.

@rsc
Copy link
Contributor Author

rsc commented Sep 2, 2020

@pierrec It's not in the draft doc (the "one addition" is the text in the comment above). Const strings can end up playing a role in deciding whether a program type checks, which would mean all type checkers would need to understand //go:embed'ed consts. In contrast, if we stick to vars, type checkers are none the wiser and can be left alone. Seems like we should probably stick to vars.

Is there a particular reason you wanted a const instead of a var? Using them should be about the same as far as efficiency. (References to const strings end up compiling to what amount to references to hidden vars anyway.)

@pierrec
Copy link

pierrec commented Sep 2, 2020

Thanks for the explanation. I tend to embed static assets as const strings at the moment this is why I asked. I am fine with vars too!

@earthboundkid
Copy link
Contributor

Interesting, so I could do something like:

//go:embed version.txt
var Version string

And potentially even have a //go:generate comment to generate version.txt. That would cut out a large use case for makefiles/ldflags.

@earthboundkid
Copy link
Contributor

Is it an error if the file isn't found? If so, where technically is the error considered to occur? Link time?

@docmerlin
Copy link

Can we make sure that go:embed runs after go:generate so we can do things like easily generate versions, etc?

@tooolbox
Copy link

tooolbox commented Sep 2, 2020

Can we make sure that go:embed runs after go:generate so we can do things like easily generate versions, etc?

From my understanding,go:generate will occur with go generate while go:embed would happen with go build.

@rsc
Copy link
Contributor Author

rsc commented Sep 2, 2020

@carlmjohnson Yes, it is always an error to say //go:embed foo where foo does not exist.
The error happens when compiling the source file containing that line.
(If you were to remove foo after compiling that source file, you still wouldn't get to a link step - the go command would notice that the package needs rebuilding because foo was deleted.)

@tv42
Copy link

tv42 commented Sep 2, 2020

I think that this proposal is not complete without saying something about ETag.
https://old.reddit.com/r/golang/comments/hv96ny/qa_goembed_draft_design/fzi0pok/

@rsc
Copy link
Contributor Author

rsc commented Sep 2, 2020

@tv42, yes, we will make ETag work. I'm not sure what the shape of that is but we will.
(Also affirmed on #35950 (comment).)

@andig
Copy link
Contributor

andig commented Sep 3, 2020

TwoThree things I've noticed from working with mjibson/esc:

  • As go:embed doesn't need to generate go files for embedding as read-only filesystem, it would take away the pain of changing timestamps on the go:generateed files that defied git porcelain tests on CI- very nice
  • One thing I didn't find in the proposal but would need is the ability to live-reload the embedded files during development cycles. Using mjibson/esc I can currently do that instructing it to use the local filesystem (though it wouldn't pick up new files) and change the behaviour using build tags. I'm wondering what that could fit into the proposal?
  • Update Another thing I remember is that esc required to be able to transparently strip (parts of) the base path in order to e.g. export an assets folder as web root.

Afterthought: I guess the second point could be remedied in conjunction with the io/fs proposal where I would either use the embedded or the live filesystem for inclusion? Implement the path stripping as io/fs middleware?

@Merovius
Copy link
Contributor

Merovius commented Sep 3, 2020

@andig You can already strip prefixes when serving a filesystem over HTTP. I agree that the live-reloading can be done by a third party library wrapping an io/fs.

@andig
Copy link
Contributor

andig commented Sep 3, 2020

One more thing: if I understand correctly, embed will consider files locally to the package and forbids ... My current design has /assets and /server/ where the latter contains the server‘s code and today hosts the generated files. With this proposal the embed would need to move to the root folder as assets wouldn‘t be accessible from server. This imposes different accessibility constraints from normal imports. I was wondering if this is necessary for security reasons or if module-local embeds should be generally allowed.

@thomasf
Copy link

thomasf commented Sep 3, 2020

One more thing: if I understand correctly, embed will consider files locally to the package and forbids ... My current design has /assets and /server/ where the latter contains the server‘s code and today hosts the generated files. With this proposal the embed would need to move to the root folder as assets wouldn‘t be accessible from server. This imposes different accessibility constraints from normal imports. I was wondering if this is necessary for security reasons or if module-local embeds should be generally allowed.

You can create a emed.go file in your assets directory and make the assets available as it's own package to the rest of your program.

@tristanfisher
Copy link

Another explicit goal is to avoid a language change. To us, embedding static assets seems like a tooling issue, not a language issue.

Agreed. In my opinion, adding syntactical sugar in the language to support this tooling change is a language change. I'm sure this is obvious to others, but this is effectively comment-as-code.

I strongly feel that magic/sugar detracts from the simplicity and readability of the language; it is very easy to miss a magical comment that embeds a file. While a response to this could easily be "okay, then don't use it", this change means that a reviewer still has to be vigilant for others using this feature and has to remember that comments around variable declarations can break builds or fail at compile-time.

I believe this is going to add confusion, detract from language usability, and will result in opaque, large binaries without clear benefit (regarding the lattermost concern, this will even lead to an anti-pattern of re-building binaries due to plain file changes). If go mod allowed for a --withNonGoCodeAssets, I believe this would solve the needs of most developers that don't want to write more complex build pipelines (I assume end-user distribution is a smaller subset of the problem for users).

@rsc
Copy link
Contributor Author

rsc commented Sep 3, 2020

@tristanfisher, I understand your point about language vs tooling change. It's certainly near the line. The reason that I consider it more a tooling change is that the language spec is unaffected - whether a program is valid does not change, the type checking process does not change. All that changes is the initial value of that variable following the comment. In this way it is a bit like the linker's -X flag, which can set the initial value of a top-level var of type string. It's fine for us to disagree; I just wanted to make my definition clear and explain the distinction I'm making.

As for bloat, I guess we'll have to see, but I don't anticipate programs getting much larger than they already are. People already run tools that turn arbitrary files into Go code, check them into their repos, and make the compiler build them. The design removes some overhead from this process but does not enable anything new. Maybe people will abuse it now that it's easier to do, but on balance I don't expect that to be much of a problem. (And if some dependency embeds something so big that it bloats your binaries, you can always choose not to use that dependency.)

As for rebuilds due to plain file changes, the only files that can trigger rebuilds are the ones in your own top-level module, since dependencies are immutable. If you found rebuilds happening more often than you'd like, the only explanation is (1) you are embedding files and (2) you are modifying those files. You would be in complete control of doing something about either cause. (It would be another thing entirely if a dependency's choice of what to use was somehow forcing extra rebuilds or other expense on you. But that's not the case here.)

@tristanfisher
Copy link

@rsc I agree that it's okay for us to disagree and I appreciate your response. My feeling is that if it's included by default in the standard tooling and comments can lead to an implicit initialization of a variable, then it's a language change. Outside of that debate, I guess my icky feeling is around more directives as "magic" comments that need to be memorized by (human) code readers. This could be taken to the absurd conclusion of adding new features via block comments that get handled at build time.

That said, if this gets added to the ecosystem, I will be thankful that importing embed is required -- that's better than nothing as a "hey, head's up" when auditing code. I think go mod allowing for non .go would solve a majority of use cases (I imagine most people are going to glob files for webservers) and would also live entirely in tooling.

I think your point regarding the linker is a good one. It also helps explain my feelings on this: if the very end user (e.g. not someone that simply imports a package) is making the decision, there's no way to be surprised by blobs of non-code coming along for the ride. My concerns are born out of reviewing/pairing-on others' work and "tech-leady" responsibilities, which is why I felt the need to respond.

I think "we'll have to see" sums it up well (I'm more cynical about bloat/misuse).

@aykevl
Copy link

aykevl commented Sep 3, 2020

I will read through the draft design tonight, so far it looks good from the TinyGo perspective.

I just wanted to clarify one thing:

On the other hand, projects like TinyGo and U-root target systems with more RAM than disk or flash. For those projects, compressing assets and using incremental decompression at runtime could provide significant savings.

I don't know about U-root, but for TinyGo the main targets are microcontrollers which normally have far more flash than RAM (usually a factor of 8 or 16). A quick look at the draft design seems to suggest the idea is to keep the files in read-only memory, which would work fine for these targets: the embedded files can be read directly from flash. It would most likely not be desirable for TinyGo targets to decompress files at runtime.

@networkimprov
Copy link

The io/fs proposal on which this depends looks to be blocked on Readdir/FileInfo problems, under discussion in #41188 and previously #40352.

I've drafted an API to replace them in #41188 (comment)

@gopherbot
Copy link
Contributor

Change https://golang.org/cl/285213 mentions this issue: doc/go1.16: mention go/build changes

@codefromthecrypt
Copy link

Apologies for not finding the discussion about why go source are not allowed to be go:embed. This prevents serving a directory of example go projects via go:embed, and keeps folks pinned to alternatives some of which aren't really maintained anymore.. Can you clarify if serving source files as text is a never vs a not yet, and if the former why?

@ghost
Copy link

ghost commented Mar 24, 2021

Go source files are allowed.

package main

import (
	_ "embed"
	"fmt"
)

//go:embed main.go
var source string

func main() {
	fmt.Println(source)
}

@codefromthecrypt
Copy link

thanks, maybe the .go thing is was a red herring. It seems to be more about go.mod perhaps?

Ex. Given a directory like this:

data/extension/init/templates/tinygo/envoy.access_loggers/
data/extension/init/templates/tinygo/envoy.access_loggers/default
data/extension/init/templates/tinygo/envoy.access_loggers/default/go.mod
data/extension/init/templates/tinygo/envoy.access_loggers/default/go.sum
data/extension/init/templates/tinygo/envoy.access_loggers/default/.gitignore
data/extension/init/templates/tinygo/envoy.access_loggers/default/main.go
data/extension/init/templates/tinygo/envoy.access_loggers/default/main_test.go

and an accessor file data/extension/init/templates.go

--snip--
//go:embed templates/*
var templatesFs embed.FS
--snip--

go build will do this:

data/extension/init/templates.go:13:12: pattern templates/*: cannot embed directory templates/tinygo: contains no embeddable files

if I change to //go:embed templates/tinygo/envoy.access_loggers/* the error gets closer to the point:

data/extension/init/templates.go:13:12: pattern templates/tinygo/envoy.access_loggers/*: cannot embed directory templates/tinygo/envoy.access_loggers/default: in different module

If I then delete the go.mod out of that directory, it works. So, I guess more concisely it is about go.mod, not files ending in .go.

codefromthecrypt pushed a commit to tetratelabs/func-e that referenced this issue Mar 24, 2021
There's currently a glitch because go.mod isn't allowed in the go:embed
path.

Fixes #126
See golang/go#41191 (comment)
codefromthecrypt pushed a commit to tetratelabs/func-e that referenced this issue Mar 24, 2021
There's currently a glitch because go.mod isn't allowed in the go:embed
path.

Fixes #126
See golang/go#41191 (comment)
codefromthecrypt pushed a commit to tetratelabs/func-e that referenced this issue Mar 24, 2021
There's currently a glitch because go.mod isn't allowed in the go:embed
path.

Fixes #126
See golang/go#41191 (comment)

Signed-off-by: Adrian Cole <[email protected]>
@ghost
Copy link

ghost commented Mar 24, 2021

It's a bit surprising, but looks like it's intended:

// Gather all files in the named directory, stopping at module boundaries
// and ignoring files that wouldn't be packaged into a module.

if info.IsDir() {
if _, err := fsys.Stat(filepath.Join(path, "go.mod")); err == nil {
return filepath.SkipDir
}
return nil
}

codefromthecrypt pushed a commit to tetratelabs/func-e that referenced this issue Mar 24, 2021
This removes go.mod from the examples due to

golang/go#41191 (comment)

Signed-off-by: Adrian Cole <[email protected]>
@warmchang
Copy link

Go source files are allowed.

package main

import (
	_ "embed"
	"fmt"
)

//go:embed main.go
var source string

func main() {
	fmt.Println(source)
}

Matryoshka 😄

@codefromthecrypt
Copy link

@warmchang correct and sorry to not summarize back. The issue is go.mod not source files as I initially thought. It is being tracked here #45197

@Merovius
Copy link
Contributor

For future reference, to the next person starting to post here: This issue is closed. Comments might not get any audience. You are likely better served with alternatives:

  • If you are having issues with the embed feature, you should file a new issue instead (as @codefromthecrypt has done).
  • If you have comments or want to discuss aspects of it, a better alternative would be to post them to golang-nuts.

@golang golang locked and limited conversation to collaborators Mar 25, 2022
@rsc rsc moved this to Accepted in Proposals Aug 10, 2022
@rsc rsc added this to Proposals Aug 10, 2022
@rsc rsc removed this from Proposals Oct 19, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests