Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ All notable changes to GoTTP will be documented in this file.
### Changed (breaking: result shape)
- **Top-level anonymous groups now match Python TTP's result shape**: a template whose top-level group has no `name` (an unnamed `<group>`, or a template with no group tags at all) used its list of matches as the *whole* per-input result list, so the result was one list level short (`[[{...},{...}]]` from `NewParser().Result()` instead of TTP's `[[[{...},{...}]]]`), every input after the first was dropped, and named groups next to the anonymous one were lost. Each input's result is now built the way TTP's `form_results` does it: the anonymous matches are that input's result, other top-level results in the same input are appended as one more item, and every input keeps its own entry. An unnamed `<group>` gives a list even for one match; a template without group tags is an implicit group named `_anonymous_` (as in TTP), so one match gives a dict. The same applies to `results="per_template"` and to the source-map path (`EnableSourceMap`), whose `per_template` result kept a literal `_anonymous_` key. The `table` formatter flattens the per-input lists into one table as before. Code that reads `result[0]` as a match dict for an anonymous-group template must now read `result[0][0]`. Source maps report `GroupName: "_anonymous_"` for the implicit group; `ParseStream` still reports an empty `groupPath` for it. (#62)

### Fixed
- **`strip`/`lstrip`/`rstrip` characters argument**: `strip("chars")` ignored its argument and only removed whitespace, and `lstrip`/`rstrip` weren't registered, so all three returned the value unchanged. They now behave like Python's `str.strip/lstrip/rstrip(chars)`: the argument is a set of characters removed from both ends, the start or the end, and without an argument they remove whitespace. The `chain()` fallback does the same. A quoted argument made only of the other quote character (`strip('"')`) also reached the function as an empty string; quote characters inside a quoted argument are now kept. (#35)

## [v0.1.13] - 2026-09-03

### Fixed
Expand Down
19 changes: 15 additions & 4 deletions internal/compiled/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -6533,8 +6533,7 @@ func parseArguments(argStr string, vars map[string]interface{}) []string {
}
// Include empty strings if they were quoted (e.g., '' or "")
if arg != "" || wasQuoted {
// Resolve variable if not quoted
arg = resolveVariable(arg, vars)
arg = resolveArgument(arg, wasQuoted, vars)
args = append(args, arg)
}
current.Reset()
Expand All @@ -6556,14 +6555,26 @@ func parseArguments(argStr string, vars map[string]interface{}) []string {
}
// Include empty strings if they were quoted (e.g., '' or "")
if arg != "" || wasQuoted {
// Resolve variable if not quoted
arg = resolveVariable(arg, vars)
arg = resolveArgument(arg, wasQuoted, vars)
args = append(args, arg)
}

return args
}

// resolveArgument resolves one parsed argument. A quoted argument has already
// lost its quotes, so quote characters left in it are content (strip('"')
// passes a double quote): only a vars lookup applies to it.
func resolveArgument(arg string, wasQuoted bool, vars map[string]interface{}) string {
if !wasQuoted {
return resolveVariable(arg, vars)
}
if val, ok := vars[arg]; ok {
return fmt.Sprintf("%v", val)
}
return arg
}

// resolveVariable resolves a variable name from vars map, or returns the original string
func resolveVariable(arg string, vars map[string]interface{}) string {
// If quoted, remove quotes and return
Expand Down
16 changes: 16 additions & 0 deletions internal/compiled/runtime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,22 @@ func TestParseArguments(t *testing.T) {
argStr: "''",
expected: []string{""},
},
// Issue #35: strip('"') must pass a double quote, not an empty string.
{
name: "quoted double quote",
argStr: `'"'`,
expected: []string{`"`},
},
{
name: "quoted single quote",
argStr: `"'"`,
expected: []string{`'`},
},
{
name: "quoted value wrapped in the other quote",
argStr: `'"a"', "'b'"`,
expected: []string{`"a"`, `'b'`},
},
}

for _, tt := range tests {
Expand Down
27 changes: 26 additions & 1 deletion internal/functions/match/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"regexp"
"strings"
"unicode"
)

// Cached compiled regexes for performance
Expand Down Expand Up @@ -44,6 +45,8 @@ func (r *Registry) registerBuiltins() {
r.Register("upper", upper)
r.Register("lower", lower)
r.Register("strip", strip)
r.Register("lstrip", lstrip)
r.Register("rstrip", rstrip)
r.Register("split", split)
r.Register("join", join)
r.Register("replace", replace)
Expand All @@ -69,12 +72,34 @@ func lower(value interface{}, args []string, kwargs map[string]interface{}) (int
return strings.ToLower(str), nil
}

// strip removes leading and trailing whitespace
// strip, lstrip and rstrip follow Python's str.strip/lstrip/rstrip(chars):
// with an argument they remove any of its characters (a set, not a
// substring) from both ends, the start or the end; without one they remove
// whitespace.
func strip(value interface{}, args []string, kwargs map[string]interface{}) (interface{}, error) {
str := fmt.Sprintf("%v", value)
if len(args) > 0 {
return strings.Trim(str, args[0]), nil
}
return strings.TrimSpace(str), nil
}

func lstrip(value interface{}, args []string, kwargs map[string]interface{}) (interface{}, error) {
str := fmt.Sprintf("%v", value)
if len(args) > 0 {
return strings.TrimLeft(str, args[0]), nil
}
return strings.TrimLeftFunc(str, unicode.IsSpace), nil
}

func rstrip(value interface{}, args []string, kwargs map[string]interface{}) (interface{}, error) {
str := fmt.Sprintf("%v", value)
if len(args) > 0 {
return strings.TrimRight(str, args[0]), nil
}
return strings.TrimRightFunc(str, unicode.IsSpace), nil
}

// split splits a string by delimiter
func split(value interface{}, args []string, kwargs map[string]interface{}) (interface{}, error) {
str := fmt.Sprintf("%v", value)
Expand Down
7 changes: 5 additions & 2 deletions internal/functions/match/more.go
Original file line number Diff line number Diff line change
Expand Up @@ -1880,8 +1880,11 @@ func applyChainFunction(value interface{}, funcName string, args []string, kwarg
str := fmt.Sprintf("%v", value)
return strings.ToLower(str), nil
case "strip":
str := fmt.Sprintf("%v", value)
return strings.TrimSpace(str), nil
return strip(value, args, kwargs)
case "lstrip":
return lstrip(value, args, kwargs)
case "rstrip":
return rstrip(value, args, kwargs)
case "split":
str := fmt.Sprintf("%v", value)
delimiter := ","
Expand Down
57 changes: 57 additions & 0 deletions internal/functions/match/strip_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package match

import "testing"

// Issue #35: strip/lstrip/rstrip("chars") follow Python's str.strip(chars):
// the argument is a set of characters, not a substring, and no argument
// strips whitespace.
var stripCases = []struct {
fn string
value string
args []string
want string
}{
{"strip", " (00:01) ", nil, "(00:01)"},
{"strip", "(00:01)", []string{"()"}, "00:01"},
{"strip", "((a) (b))", []string{")("}, "a) (b"},
{"strip", "xyabcyx", []string{"xy"}, "abc"},
{"strip", " (a) ", []string{"()"}, " (a) "},
{"strip", "abc", []string{""}, "abc"},
{"lstrip", " a ", nil, "a "},
{"lstrip", "((a)", []string{"("}, "a)"},
{"lstrip", "xyabcyx", []string{"yx"}, "abcyx"},
{"rstrip", " a ", nil, " a"},
{"rstrip", "(b))", []string{")"}, "(b"},
{"rstrip", "xyabcyx", []string{"yx"}, "xyabc"},
}

func TestStripCharsArgument(t *testing.T) {
r := NewRegistry()
for _, tc := range stripCases {
fn, ok := r.Get(tc.fn)
if !ok {
t.Fatalf("%s is not registered", tc.fn)
}
got, err := fn(tc.value, tc.args, nil)
if err != nil {
t.Fatalf("%s(%q, %q): %v", tc.fn, tc.value, tc.args, err)
}
if got != tc.want {
t.Errorf("%s(%q, %q) = %q, want %q", tc.fn, tc.value, tc.args, got, tc.want)
}
}
}

// The chain() inline fallback (used when no registry or resolver is passed)
// must agree with the registered functions.
func TestChainInlineStripCharsArgument(t *testing.T) {
for _, tc := range stripCases {
got, err := applyChainFunction(tc.value, tc.fn, append([]string(nil), tc.args...), nil)
if err != nil {
t.Fatalf("chain %s(%q, %q): %v", tc.fn, tc.value, tc.args, err)
}
if got != tc.want {
t.Errorf("chain %s(%q, %q) = %q, want %q", tc.fn, tc.value, tc.args, got, tc.want)
}
}
}
9 changes: 4 additions & 5 deletions test/ttpsuite/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ go test ./test/ttpsuite -v | grep -E 'suite:|repros:|parity:'

```
TTP 0.10.1 suite: pass 48 / skipped-by-issue 148 / design 4 of 200
gottp repros: pass 1 / skipped-by-issue 9 / design 0 of 10
gottp repros: pass 2 / skipped-by-issue 8 / design 0 of 10
source-map parity: same 199 / diverge 11 of 210
```

Expand Down Expand Up @@ -41,7 +41,7 @@ The Go tests need no Python, so they run in plain `go test ./...` and in CI. The
| `issue32_one_line_fills_several_template_lines` | #32 |
| `issue33_trailing_ignore_with_trailing_whitespace` | #33 |
| `issue34_split_joinmatches` | #34 |
| `issue35_strip_characters_argument` | #35 |
| `issue35_strip_characters_argument` | passes; #35 is fixed |
| `issue36_unknown_function_falls_back_to_str_method` | #36 |
| `sourcemap_void_group` | passes; covers `void` for source-map parity (#108) |

Expand Down Expand Up @@ -83,7 +83,7 @@ Cases per issue (first strict difference), and how many more cases hit the issue
| #28 | 9 | | Parent group whose _start_ line has no variables drops its child groups |
| #80 | 9 | 2 | Missing output features |
| #63 | 8 | | set(True) / set(False) (and any literal argument) is a string |
| #30 | 6 | | Indented template lines match data at any indentation |
| #30 | 7 | | Indented template lines match data at any indentation |
| #64 | 6 | | A variable with default() captures the leading space |
| #74 | 6 | | <extend> inside a <group> is ignored |
| #93 | 6 | | <extend>: <vars> from the extended file and the groups=/vars=/inputs=/lookups= filters are not applied |
Expand All @@ -93,15 +93,14 @@ Cases per issue (first strict difference), and how many more cases hit the issue
| #88 | 4 | | itemize on a child group drops its values, and the path argument is ignored |
| #97 | 4 | | A group macro that returns None loses its in-place changes, and the next chained macro gets None |
| #110 | 4 | | Group-specific output= results are merged into the main result instead of added as a separate item |
| #100 | 4 | | Nested-section templates from TTP answers diverge; root cause not isolated |
| #112 | 4 | | A chain stored in <vars> as a list is ignored (group chain= and chain()) |
| #69 | 3 | | A _start_ line rejected by a condition doesn't close the previous record |
| #73 | 3 | 1 | Getters: gethostname through set(), and get_date/get_time/getfilename/get_timestamp* missing |
| #79 | 3 | | _line_ with joinmatches also captures the _start_ line |
| #91 | 3 | 1 | A group with no matching lines does not emit its default values |
| #94 | 3 | | <input url=...> pointing at a directory loads nothing |
| #99 | 3 | | record()/set= across groups: the recorded value is not set and the first child record is lost |
| #100 | 3 | | Nested-section templates from TTP answers diverge; root cause not isolated |
| #35 | 2 | | strip/lstrip/rstrip ignore their characters argument |
| #72 | 2 | | Group to_int has no float fallback |
| #76 | 2 | | A dynamic-path value containing . is split into path segments |
| #77 | 2 | | Nested <template> children are merged into one result |
Expand Down
14 changes: 5 additions & 9 deletions test/ttpsuite/known_failures.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,9 @@
"issue": 34,
"reason": "split() | joinmatches returns a joined string instead of a merged list"
},
"gottp-repros/issue35_strip_characters_argument": {
"issue": 35,
"reason": "strip(\"()\") ignores its characters argument"
},
"gottp-repros/issue36_unknown_function_falls_back_to_str_method": {
"issue": 36,
"reason": "rstrip(\",\") (str method fallback) is silently skipped"
"reason": "swapcase (str method fallback) is silently skipped"
},
"test_N2G_formatter/test_n2g_formatter": {
"issue": 80,
Expand Down Expand Up @@ -141,8 +137,8 @@
"reason": "chain(var) naming a <vars> list is ignored"
},
"test_answers_and_docs/test_issue_50": {
"issue": 35,
"reason": "strip('\"') does not strip the quotes"
"issue": 30,
"reason": "indented template lines also match the deeper ipv6 address lines"
},
"test_answers_and_docs/test_issue_52_answer": {
"issue": 79,
Expand Down Expand Up @@ -196,8 +192,8 @@
"reason": "nested port/ethernet sections lose captures; root cause not isolated"
},
"test_answers_and_docs/test_slack_answer_3": {
"issue": 35,
"reason": "strip('\"') does not strip the quotes"
"issue": 100,
"reason": "sibling ospf/ospf3 groups: the ospf3 lines join the ospf record, nesting an extra ospf level; root cause not isolated"
},
"test_answers_and_docs/test_slack_answer_3_full": {
"issue": 100,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[
[
{
"v": "1,2,3"
"v": "AbC"
}
]
]
Original file line number Diff line number Diff line change
@@ -1 +1 @@
x {{ v | rstrip(",") }}
x {{ v | swapcase }}
Original file line number Diff line number Diff line change
@@ -1 +1 @@
x 1,2,3,
x aBc
Loading