From c7908c9bfcfb713c88e23186bcaefcf76401216a Mon Sep 17 00:00:00 2001 From: Quim Muntal Diaz Date: Thu, 21 May 2020 17:19:19 +0200 Subject: [PATCH] support const expressions --- parser/source.go | 29 ++++++++++++++++++++++++++--- pkging/pkgtest/testdata/ref/main.go | 6 +++++- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/parser/source.go b/parser/source.go index 184cb1c..be58036 100644 --- a/parser/source.go +++ b/parser/source.go @@ -33,16 +33,39 @@ func (p *ParsedSource) Parse() error { return p.err } -func (p *ParsedSource) value(node ast.Node) (string, error) { - var s string +func (p *ParsedSource) valueIdent(node *ast.Ident) (s string) { + s = node.Name + if node.Obj.Kind != ast.Con { + return + } + // As per ast package a Con object is always a *ValueSpec, + // but double-checking to avoid panics + if x, ok := node.Obj.Decl.(*ast.ValueSpec); ok { + // The const var can be defined inline with other vars, + // as in `const a, b = "a", "b"`. + for i, v := range x.Names { + if v.Name == node.Name { + s = p.valueNode(x.Values[i]) + break + } + } + } + return +} +func (p *ParsedSource) valueNode(node ast.Node) string { + var s string switch x := node.(type) { case *ast.BasicLit: s = x.Value case *ast.Ident: - s = x.Name + s = p.valueIdent(x) } + return s +} +func (p *ParsedSource) value(node ast.Node) (string, error) { + s := p.valueNode(node) return strconv.Unquote(s) } diff --git a/pkging/pkgtest/testdata/ref/main.go b/pkging/pkgtest/testdata/ref/main.go index d3e41a3..a266161 100644 --- a/pkging/pkgtest/testdata/ref/main.go +++ b/pkging/pkgtest/testdata/ref/main.go @@ -18,12 +18,16 @@ func main() { } } +const ( + unused, pathAsset = "", "/assets" +) + func run() error { if err := actions.WalkTemplates(os.Stdout); err != nil { return err } - err := pkger.Walk("/assets", func(path string, info os.FileInfo, err error) error { + err := pkger.Walk(pathAsset, func(path string, info os.FileInfo, err error) error { if err != nil { return err }