makeArgsReplacer prepares a Replacer which can replace non-variadic args placeholders in imported tokens.
(args []string)
| 96 | // makeArgsReplacer prepares a Replacer which can replace |
| 97 | // non-variadic args placeholders in imported tokens. |
| 98 | func makeArgsReplacer(args []string) *caddy.Replacer { |
| 99 | repl := caddy.NewEmptyReplacer() |
| 100 | repl.Map(func(key string) (any, bool) { |
| 101 | // TODO: Remove the deprecated {args.*} placeholder |
| 102 | // support at some point in the future |
| 103 | if matches := argsRegexpIndexDeprecated.FindStringSubmatch(key); len(matches) > 0 { |
| 104 | // What's matched may be a substring of the key |
| 105 | if matches[0] != key { |
| 106 | return nil, false |
| 107 | } |
| 108 | |
| 109 | value, err := strconv.Atoi(matches[1]) |
| 110 | if err != nil { |
| 111 | caddy.Log().Named("caddyfile").Warn( |
| 112 | "Placeholder {args." + matches[1] + "} has an invalid index") |
| 113 | return nil, false |
| 114 | } |
| 115 | if value >= len(args) { |
| 116 | caddy.Log().Named("caddyfile").Warn( |
| 117 | "Placeholder {args." + matches[1] + "} index is out of bounds, only " + strconv.Itoa(len(args)) + " argument(s) exist") |
| 118 | return nil, false |
| 119 | } |
| 120 | caddy.Log().Named("caddyfile").Warn( |
| 121 | "Placeholder {args." + matches[1] + "} deprecated, use {args[" + matches[1] + "]} instead") |
| 122 | return args[value], true |
| 123 | } |
| 124 | |
| 125 | // Handle args[*] form |
| 126 | if matches := argsRegexpIndex.FindStringSubmatch(key); len(matches) > 0 { |
| 127 | // What's matched may be a substring of the key |
| 128 | if matches[0] != key { |
| 129 | return nil, false |
| 130 | } |
| 131 | |
| 132 | if strings.Contains(matches[1], ":") { |
| 133 | caddy.Log().Named("caddyfile").Warn( |
| 134 | "Variadic placeholder {args[" + matches[1] + "]} must be a token on its own") |
| 135 | return nil, false |
| 136 | } |
| 137 | value, err := strconv.Atoi(matches[1]) |
| 138 | if err != nil { |
| 139 | caddy.Log().Named("caddyfile").Warn( |
| 140 | "Placeholder {args[" + matches[1] + "]} has an invalid index") |
| 141 | return nil, false |
| 142 | } |
| 143 | if value >= len(args) { |
| 144 | caddy.Log().Named("caddyfile").Warn( |
| 145 | "Placeholder {args[" + matches[1] + "]} index is out of bounds, only " + strconv.Itoa(len(args)) + " argument(s) exist") |
| 146 | return nil, false |
| 147 | } |
| 148 | return args[value], true |
| 149 | } |
| 150 | |
| 151 | // Not an args placeholder, ignore |
| 152 | return nil, false |
| 153 | }) |
| 154 | return repl |
| 155 | } |