Skip to content

Commit

Permalink
Merge pull request #1255 from hashicorp/issue1143-loop-int64-type
Browse files Browse the repository at this point in the history
fix loop to work with different int types
  • Loading branch information
eikenb committed Aug 12, 2019
2 parents 9e45d49 + 94ded09 commit ba332ca
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 7 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
35 changes: 35 additions & 0 deletions template/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1249,6 +1249,41 @@ 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 }}`,
},
&ExecuteInput{
Brain: NewBrain(),
},
"012",
false,
},
{
"helper_join",
&NewTemplateInput{
Expand Down

0 comments on commit ba332ca

Please sign in to comment.