parseVariadic determines if the token is a variadic placeholder, and if so, determines the index range (start/end) of args to use. Returns a boolean signaling whether a variadic placeholder was found, and the start and end indices.
(token Token, argCount int)
| 29 | // Returns a boolean signaling whether a variadic placeholder was found, |
| 30 | // and the start and end indices. |
| 31 | func parseVariadic(token Token, argCount int) (bool, int, int) { |
| 32 | if !strings.HasPrefix(token.Text, "{args[") { |
| 33 | return false, 0, 0 |
| 34 | } |
| 35 | if !strings.HasSuffix(token.Text, "]}") { |
| 36 | return false, 0, 0 |
| 37 | } |
| 38 | |
| 39 | argRange := strings.TrimSuffix(strings.TrimPrefix(token.Text, "{args["), "]}") |
| 40 | if argRange == "" { |
| 41 | caddy.Log().Named("caddyfile").Warn( |
| 42 | "Placeholder "+token.Text+" cannot have an empty index", |
| 43 | zap.String("file", token.File+":"+strconv.Itoa(token.Line)), zap.Strings("import_chain", token.imports)) |
| 44 | return false, 0, 0 |
| 45 | } |
| 46 | |
| 47 | start, end, found := strings.Cut(argRange, ":") |
| 48 | |
| 49 | // If no ":" delimiter is found, this is not a variadic. |
| 50 | // The replacer will pick this up. |
| 51 | if !found { |
| 52 | return false, 0, 0 |
| 53 | } |
| 54 | |
| 55 | // A valid token may contain several placeholders, and |
| 56 | // they may be separated by ":". It's not variadic. |
| 57 | // https://github.com/caddyserver/caddy/issues/5716 |
| 58 | if strings.Contains(start, "}") || strings.Contains(end, "{") { |
| 59 | return false, 0, 0 |
| 60 | } |
| 61 | |
| 62 | var ( |
| 63 | startIndex = 0 |
| 64 | endIndex = argCount |
| 65 | err error |
| 66 | ) |
| 67 | if start != "" { |
| 68 | startIndex, err = strconv.Atoi(start) |
| 69 | if err != nil { |
| 70 | caddy.Log().Named("caddyfile").Warn( |
| 71 | "Variadic placeholder "+token.Text+" has an invalid start index", |
| 72 | zap.String("file", token.File+":"+strconv.Itoa(token.Line)), zap.Strings("import_chain", token.imports)) |
| 73 | return false, 0, 0 |
| 74 | } |
| 75 | } |
| 76 | if end != "" { |
| 77 | endIndex, err = strconv.Atoi(end) |
| 78 | if err != nil { |
| 79 | caddy.Log().Named("caddyfile").Warn( |
| 80 | "Variadic placeholder "+token.Text+" has an invalid end index", |
| 81 | zap.String("file", token.File+":"+strconv.Itoa(token.Line)), zap.Strings("import_chain", token.imports)) |
| 82 | return false, 0, 0 |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | // bound check |
| 87 | if startIndex < 0 || startIndex > endIndex || endIndex > argCount { |
| 88 | caddy.Log().Named("caddyfile").Warn( |