Skip to content
This repository has been archived by the owner on Jun 25, 2022. It is now read-only.

Commit

Permalink
add support for adding box by var or const (#60)
Browse files Browse the repository at this point in the history
  • Loading branch information
Nemo12 authored and markbates committed Apr 13, 2018
1 parent f2c6d7a commit 7f40749
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 4 deletions.
28 changes: 28 additions & 0 deletions builder/visitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,16 @@ func (v *visitor) evalSelector(expr *ast.CallExpr, sel *ast.SelectorExpr) error
for _, e := range expr.Args {
switch at := e.(type) {
case *ast.Ident:
switch at.Obj.Kind {
case ast.Var:
if as, ok := at.Obj.Decl.(*ast.AssignStmt); ok {
v.addVariable(as)
}
case ast.Con:
if vs, ok := at.Obj.Decl.(*ast.ValueSpec); ok {
v.addConstant(vs)
}
}
return v.evalIdent(at)
case *ast.BasicLit:
v.addBox(at.Value)
Expand All @@ -218,3 +228,21 @@ func (v *visitor) addBox(b string) {
b = strings.Replace(b, "\"", "", -1)
v.Boxes = append(v.Boxes, b)
}

func (v *visitor) addVariable(as *ast.AssignStmt) error {
if len(as.Rhs) == 1 {
if bs, ok := as.Rhs[0].(*ast.BasicLit); ok {
v.addBox(bs.Value)
}
}
return nil
}

func (v *visitor) addConstant(vs *ast.ValueSpec) error {
if len(vs.Values) == 1 {
if bs, ok := vs.Values[0].(*ast.BasicLit); ok {
v.addBox(bs.Value)
}
}
return nil
}
4 changes: 2 additions & 2 deletions builder/visitor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ func Test_Visitor(t *testing.T) {

r.Equal("example", v.Package)
r.Len(v.Errors, 0)
r.Len(v.Boxes, 5)
r.Equal([]string{"./assets", "./bar", "./foo", "./sf", "./templates"}, v.Boxes)
r.Len(v.Boxes, 7)
r.Equal([]string{"./assets", "./bar", "./constant", "./foo", "./sf", "./templates", "./variable"}, v.Boxes)
}
Empty file added example/constant/constant.html
Empty file.
19 changes: 17 additions & 2 deletions example/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,26 @@ import (

var a = packr.NewBox("./foo")

const constString = "./constant"

type S struct{}

func (S) f(packr.Box) {}

func init() {
// packr.NewBox("../idontexists")

b := "./baz"
packr.NewBox(b) // won't work, no variables allowed, only strings
b := "./variable"
packr.NewBox(b)

packr.NewBox(constString)

// Cannot work from a function
packr.NewBox(strFromFunc())

// This variable should not be added
fromFunc := strFromFunc()
packr.NewBox(fromFunc)

foo("/templates", packr.NewBox("./templates"))
packr.NewBox("./assets")
Expand All @@ -25,4 +36,8 @@ func init() {
s.f(packr.NewBox("./sf"))
}

func strFromFunc() string {
return "./fromFunc"
}

func foo(s string, box packr.Box) {}
Empty file added example/variable/variable.html
Empty file.

0 comments on commit 7f40749

Please sign in to comment.