Skip to content

Commit aa95bd9

Browse files
committed
Replaced regexp in ExtractValuesFromTemplate function and updated usage
1 parent 34fe666 commit aa95bd9

File tree

5 files changed

+59
-8
lines changed

5 files changed

+59
-8
lines changed

doc/en/usage.md

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,9 +247,21 @@ all its features and available functions in this [documentation](https://pkg.go.
247247

248248
Accessing Data:
249249

250-
In a template, data is accessed using `.`(the object or value passed to the template)
250+
In a template, data is accessed using `.` (the object or value passed to the template)
251251
and the field name, for example: `{{ .var }}`.
252252

253+
> **Important**: only the following characters are allowed in variable names:
254+
>
255+
> - letters from any alphabet (Unicode category L*).
256+
> - numbers (Unicode category Nd), but not as the first character.
257+
> - the underscore character `_`.
258+
>
259+
> Any other characters — spaces, periods, hyphens, quotation marks, punctuation marks,
260+
etc. — cannot be used in the name itself.
261+
>
262+
> If you need to access a variable whose name is considered invalid,
263+
refer to it using the `index` function, specifying the variable name in quotation marks, for example, `{{ index . "field-with-dash" }}`.
264+
253265
Function calls:
254266

255267
- direct call: `{{ upper .name }}`.

doc/ru/usage.md

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,9 +253,21 @@ open_ai:
253253

254254
Доступ к данным:
255255

256-
Обращение к данным в шаблоне выполняется с помощью `.`(объект или значение, переданное шаблону)
256+
Обращение к данным в шаблоне выполняется с помощью `.` (объект или значение, переданное шаблону)
257257
и имени переменной, например, `{{ .var }}`.
258258

259+
> **Важно**: в именах переменных допустимы только следующие символы:
260+
>
261+
> - буквы любого алфавита (Unicode-категории L*).
262+
> - цифры (Unicode-категории Nd), но не первым символом.
263+
> - знак подчёркивания `_`.
264+
>
265+
> Любые другие символы — пробелы, точки, дефисы, кавычки, символы пунктуации
266+
и т.д. — в самом имени использовать нельзя.
267+
>
268+
> Если вам необходимо получить доступ к переменной, имя которой считается недопустимым,
269+
обращайтесь к ней через функцию `index`, указав имя переменной в кавычках, например `{{ index . "field-with-dash" }}`.
270+
259271
Вызовы функций:
260272

261273
- прямой вызов: `{{ upper .name }}`.

internal/generator/common/utils.go

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -361,12 +361,21 @@ func CtxClosed(ctx context.Context) bool {
361361
}
362362

363363
func ExtractValuesFromTemplate(template string) []string {
364-
re := regexp.MustCompile(`{{.*?\.([^\s|}]+).*?}}`)
365-
matches := re.FindAllStringSubmatch(template, -1)
364+
// regexp for templates like {{ .name }}
365+
reField := regexp.MustCompile(`{{\s*(?:\w+\s+)?\.([^\s"|}]+).*?}}`)
366+
matchesField := reField.FindAllStringSubmatch(template, -1)
366367

367-
values := make([]string, 0, len(matches))
368+
// regexp for templates like {{ index . "name-with-specific-symbols" }}
369+
reMapKey := regexp.MustCompile(`{{\s*index\s+\.\s+"([^"]+)".*?}}`)
370+
matchesMapKeys := reMapKey.FindAllStringSubmatch(template, -1)
368371

369-
for _, match := range matches {
372+
values := make([]string, 0, len(matchesField)+len(matchesMapKeys))
373+
374+
for _, match := range matchesField {
375+
values = append(values, match[1])
376+
}
377+
378+
for _, match := range matchesMapKeys {
370379
values = append(values, match[1])
371380
}
372381

internal/generator/common/utils_test.go

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -718,8 +718,23 @@ func TestExtractValuesFromTemplate(t *testing.T) {
718718
},
719719
{
720720
name: "Template with functions",
721-
template: "{{ upper .foo | lower }}@{{ .boo }}",
722-
expected: []string{"foo", "boo"},
721+
template: "{{ upper .foo | lower }}",
722+
expected: []string{"foo"},
723+
},
724+
{
725+
name: "Template with index function",
726+
template: `{{ index . foo }}.{{ index . "boo" }}`,
727+
expected: []string{"boo"},
728+
},
729+
{
730+
name: "Mixed template",
731+
template: `{{ index . "foo" }}.{{ lower .boo }}|{{.coo}}`,
732+
expected: []string{"boo", "coo", "foo"},
733+
},
734+
{
735+
name: "Field name in quotation marks",
736+
template: `{{ ."foo" }}`,
737+
expected: []string{},
723738
},
724739
{
725740
name: "Invalid template",

internal/generator/usecase/general/generator/value/string.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -486,6 +486,9 @@ func (g *StringGenerator) Value(number float64, rowValues map[string]any) (any,
486486
//nolint:cyclop
487487
func (g *StringGenerator) ValuesCount() float64 {
488488
if g.Template != "" {
489+
// Using `distinct` or `ordered` parameters with templates
490+
// is not possible, we cannot guarantee that these parameters
491+
// will be met, so we just need to return something other than 0.
489492
return 1.0
490493
}
491494

0 commit comments

Comments
 (0)