Skip to content

Commit

Permalink
language/go: add //go:embed all:<pattern> support (bazelbuild#1432)
Browse files Browse the repository at this point in the history
Co-authored-by: Michal Bicz <m@bicz.net>
  • Loading branch information
2 people authored and dilyevsky committed Mar 16, 2023
1 parent 7b7d98b commit de05e32
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 6 deletions.
16 changes: 11 additions & 5 deletions language/go/embed.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,24 +156,30 @@ func (er *embedResolver) resolve(embed fileEmbed) (list []string, err error) {
}
}()

glob := embed.path
all := strings.HasPrefix(embed.path, "all:")
if all {
glob = strings.TrimPrefix(embed.path, "all:")
}

// Check whether the pattern is valid at all.
if _, err := path.Match(embed.path, ""); err != nil || !validEmbedPattern(embed.path) {
if _, err := path.Match(glob, ""); err != nil || !validEmbedPattern(glob) {
return nil, fmt.Errorf("invalid pattern syntax")
}

// Match the pattern against each path in the tree. If the pattern matches a
// directory, we need to include each file in that directory, even if the file
// doesn't match the pattern separate, unless it is a hidden file (starting
// with . or _).
// doesn't match the pattern separate. By default, hidden files (starting
// with . or _) are excluded but all: prefix forces them to be included.
//
// For example, the pattern "*" matches "a", ".b", and "_c". If "a" is a
// directory, we would include "a/d", even though it doesn't match "*". We
// would not include "a/.e".
var visit func(*embeddableNode, bool)
visit = func(f *embeddableNode, add bool) {
convertedPath := filepath.ToSlash(f.path)
match, _ := path.Match(embed.path, convertedPath)
add = match || (add && !f.isHidden())
match, _ := path.Match(glob, convertedPath)
add = match || (add && (!f.isHidden() || all))
if !f.isDir() {
if add {
list = append(list, convertedPath)
Expand Down
1 change: 1 addition & 0 deletions language/go/testdata/embedsrcs/BUILD.want
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ go_library(
"m_gen.txt",
"m_static.txt",
"n_/static.txt",
"o_dir/_hidden.txt",
],
importpath = "example.com/repo/embedsrcs",
visibility = ["//visibility:public"],
Expand Down
2 changes: 1 addition & 1 deletion language/go/testdata/embedsrcs/embedsrcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ package embedsrcs

import "embed"

//go:embed *m_* n_/*
//go:embed *m_* n_/* all:o*
var fs embed.FS
2 changes: 2 additions & 0 deletions language/go/testdata/embedsrcs/o_dir/_hidden.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# o_dir/_hidden.txt should be embeded because o_dir overrides exclusion rule
# for hidden files with :all.

0 comments on commit de05e32

Please sign in to comment.