| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package cache |
| 6 |
|
| 7 |
import ( |
| 8 |
"go/ast" |
| 9 |
"go/build/constraint" |
| 10 |
"go/parser" |
| 11 |
"go/token" |
| 12 |
"slices" |
| 13 |
) |
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
func isStandaloneFile(src []byte, standaloneTags []string) bool { |
| 19 |
f, err := parser.ParseFile(token.NewFileSet(), "", src, parser.PackageClauseOnly|parser.ParseComments) |
| 20 |
if err != nil { |
| 21 |
return false |
| 22 |
} |
| 23 |
|
| 24 |
if f.Name == nil || f.Name.Name != "main" { |
| 25 |
return false |
| 26 |
} |
| 27 |
|
| 28 |
found := false |
| 29 |
walkConstraints(f, func(c constraint.Expr) bool { |
| 30 |
if tag, ok := c.(*constraint.TagExpr); ok { |
| 31 |
if slices.Contains(standaloneTags, tag.Tag) { |
| 32 |
found = true |
| 33 |
return false |
| 34 |
} |
| 35 |
} |
| 36 |
return true |
| 37 |
}) |
| 38 |
|
| 39 |
return found |
| 40 |
} |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
func walkConstraints(file *ast.File, f func(constraint.Expr) bool) { |
| 45 |
for _, cg := range file.Comments { |
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
if cg.Pos() > file.Name.Pos() { |
| 50 |
continue |
| 51 |
} |
| 52 |
for _, comment := range cg.List { |
| 53 |
if c, err := constraint.Parse(comment.Text); err == nil { |
| 54 |
if !f(c) { |
| 55 |
return |
| 56 |
} |
| 57 |
} |
| 58 |
} |
| 59 |
} |
| 60 |
} |