Skip to content

Commit

Permalink
fix loop to work with different int types
Browse files Browse the repository at this point in the history
`loop` when passed a scrach or $variable that contained an int as the
function was typed to only take int64. This changes it more like the
other functions that takes a interface{} and type switches/converts it
using reflect. Made it handle integer strings while I was at it.

Fixes #1143
  • Loading branch information
eikenb committed Aug 12, 2019
1 parent 769bbbb commit 94ded09
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 8 deletions.
37 changes: 30 additions & 7 deletions template/funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -697,16 +697,39 @@ func indent(spaces int, s string) (string, error) {
// print(i)
// }
//
func loop(ints ...int64) (<-chan int64, error) {
var start, stop int64
switch len(ints) {
func loop(ifaces ...interface{}) (<-chan int64, error) {

to64 := func(i interface{}) (int64, error) {
v := reflect.ValueOf(i)
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32:
return int64(v.Int()), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32:
return int64(v.Uint()), nil
case reflect.String:
return parseInt(v.String())
}
return 0, fmt.Errorf("loop: bad argument type: %T", i)
}

var i1, i2 interface{}
switch len(ifaces) {
case 1:
start, stop = 0, ints[0]
i1, i2 = 0, ifaces[0]
case 2:
start, stop = ints[0], ints[1]
i1, i2 = ifaces[0], ifaces[1]
default:
return nil, fmt.Errorf("loop: wrong number of arguments, expected 1 or 2"+
", but got %d", len(ints))
return nil, fmt.Errorf("loop: wrong number of arguments, expected "+
"1 or 2, but got %d", len(ifaces))
}

start, err := to64(i1)
if err != nil {
return nil, err
}
stop, err := to64(i2)
if err != nil {
return nil, err
}

ch := make(chan int64)
Expand Down
25 changes: 24 additions & 1 deletion template/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1249,11 +1249,34 @@ func TestTemplate_Execute(t *testing.T) {
"012",
false,
},
{
"helper_loop_start",
&NewTemplateInput{
Contents: `{{ range loop 1 3 }}1{{ end }}`,
},
&ExecuteInput{
Brain: NewBrain(),
},
"11",
false,
},
{
"helper_loop_text",
&NewTemplateInput{
Contents: `{{ range loop 1 "3" }}1{{ end }}`,
},
&ExecuteInput{
Brain: NewBrain(),
},
"11",
false,
},
{
// GH-1143
"helper_loop_var",
&NewTemplateInput{
Contents: `{{$n := 3 }}{{ range $i := loop $n }}{{ $i }}{{ end }}`,
Contents: `{{$n := 3 }}` +
`{{ range $i := loop $n }}{{ $i }}{{ end }}`,
},
&ExecuteInput{
Brain: NewBrain(),
Expand Down

0 comments on commit 94ded09

Please sign in to comment.