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 @@ -4,6 +4,9 @@ All notable changes to GoTTP will be documented in this file.

## [Unreleased]

### 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)

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

### Fixed
Expand Down
26 changes: 26 additions & 0 deletions docs/source/Forming Results Structure/Anonymous group.rst
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,29 @@ Anonymous groups can be nested:

All results are merged into the parent group.


Top-Level Anonymous Group
-------------------------

A top-level group without a ``name``, and the implicit group gottp creates for a template with no group tags at all, give each input's result as a list of matches, as Python TTP does:

.. code-block:: xml

<group>
interface {{ interface }}
</group>

With the input ``interface Lo0`` / ``interface Lo1``, ``NewParser().Result()`` is:

.. code-block:: json

[[[{"interface": "Lo0"}, {"interface": "Lo1"}]]]

The outer list has one item per template and the next one item per input; the innermost list is the input's matches. ``CompiledTemplate.Parse`` returns the template's result, ``[[{"interface": "Lo0"}, {"interface": "Lo1"}]]``.

- An unnamed ``<group>`` always gives a list, even for one match: ``[[{"interface": "Lo0"}]]``.
- A template with no group tags (for example just ``interface {{ interface }}``) is an implicit group named ``_anonymous_``, as in Python TTP. One match gives a dict, ``[{"interface": "Lo0"}]``, and several give a list.
- Each input keeps its own result: with a second input ``interface Lo2`` the result is ``[[{"interface": "Lo0"}, {"interface": "Lo1"}], [{"interface": "Lo2"}]]``.
- Results of named top-level groups in the same input are added to the list as one more item. With a ``<group name="host">`` for ``hostname {{ name }}`` next to the anonymous group (inside ``<template>``) and the input line ``hostname r1``: ``[[{"interface": "Lo0"}, {"interface": "Lo1"}, {"host": {"name": "r1"}}]]``.
- An input with no anonymous match gives just its other results (``{}`` when there are none).
- With ``<template results="per_template">``, the matches of all inputs form one list: ``[{"interface": "Lo0"}, {"interface": "Lo1"}, {"interface": "Lo2"}]``.
169 changes: 69 additions & 100 deletions internal/compiled/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -656,48 +656,8 @@ func (r *Runtime) Parse(inputs map[string]string, vars map[string]interface{}, o
// Python TTP: anonymous groups are merged with the rest of the groups' results
var resultsToFormat interface{}
if r.compiled.ResultsMethod == "per_template" {
if anonymousResults, ok := results["_anonymous_"]; ok {
// If _anonymous_ is a list, that becomes the root result
// Otherwise, merge it into results
if anonymousList, ok := anonymousResults.([]interface{}); ok {
// Anonymous group with multiple matches - the list is the result
resultsToFormat = anonymousList
} else {
// Single match or other type - merge into results
delete(results, "_anonymous_")
if anonymousMap, ok := anonymousResults.(map[string]interface{}); ok {
for k, v := range anonymousMap {
results[k] = v
}
}
resultsToFormat = results
}
} else {
resultsToFormat = results
}
resultsToFormat = formResults(results)
} else {
// per_input - merge _anonymous_ into each input's results
for _, inputResults := range resultsPerInput {
if anonymousResults, ok := inputResults["_anonymous_"]; ok {
// If _anonymous_ is a list, that becomes the input's result
// Otherwise, merge it into inputResults
if anonymousList, ok := anonymousResults.([]interface{}); ok {
// Anonymous group with multiple matches - store the list for later use
// We'll handle this when creating resultsList
// Store it back in the map temporarily so we can access it
inputResults["_anonymous_list"] = anonymousList
} else {
// Single match or other type - merge into inputResults
delete(inputResults, "_anonymous_")
if anonymousMap, ok := anonymousResults.(map[string]interface{}); ok {
for k, v := range anonymousMap {
inputResults[k] = v
}
}
}
}
}

// per_input - create a result for each input, even if empty
// Create results list with one entry per input
resultsList := make([]interface{}, 0)
Expand All @@ -716,27 +676,16 @@ func (r *Runtime) Parse(inputs map[string]string, vars map[string]interface{}, o

for _, inputName := range inputNamesList {
if inputResults, exists := resultsPerInput[inputName]; exists {
// Check if this input has anonymous group results stored as a list
// Anonymous groups with multiple matches are stored at "_anonymous_list" key
if anonymousList, ok := inputResults["_anonymous_list"]; ok {
if list, ok := anonymousList.([]interface{}); ok {
// Anonymous group results - these should BE the entire result list
// Don't append, just use the list directly as the result
resultsToFormat = list
goto skipResultsListBuild
}
}

// This input had results - use its results map
resultsList = append(resultsList, inputResults)
// This input had results; an anonymous group's results
// become this input's result (Python TTP form_results).
resultsList = append(resultsList, formResults(inputResults))
} else {
// Empty result for this input (matches Python TTP behavior)
resultsList = append(resultsList, make(map[string]interface{}))
}
}

resultsToFormat = resultsList
skipResultsListBuild:
}

// Process output functions if any
Expand All @@ -761,6 +710,53 @@ func (r *Runtime) Parse(inputs map[string]string, vars map[string]interface{}, o
return finalResults, nil
}

// formResults turns one input's results map (or, for per_template, the
// combined results map) into that input's result, the way Python TTP's
// template.form_results does (ttp/ttp.py:989-1003 in TTP 0.10.1). Results of
// top-level anonymous groups are stored under "_anonymous_"; when present,
// that value becomes the result, and anything else in the map is appended to
// it as one more item. Without anonymous results the map is the result.
//
// Python never has an empty "_anonymous_" list (it only creates the key on a
// match); gottp can, so an empty one counts as absent. When "_anonymous_" is a
// single dict (the implicit group of a template without tags, matched once)
// and other results exist, Python raises AttributeError; gottp merges the
// dict into the rest instead, as it did before.
func formResults(result map[string]interface{}) interface{} {
anonymous, ok := result["_anonymous_"]
if !ok {
return result
}
delete(result, "_anonymous_")
switch a := anonymous.(type) {
case []interface{}:
if len(a) == 0 {
return result
}
if len(result) == 0 {
return a
}
datum := make([]interface{}, 0, len(a)+1)
datum = append(datum, a...)
return append(datum, result)
case map[string]interface{}:
if len(result) == 0 {
return a
}
for k, v := range a {
result[k] = v
}
return result
case nil:
return result
default:
if len(result) == 0 {
return anonymous
}
return result
}
}

// errStreamGate is the sentinel matched by errors.Is when the gate fires.
// The public TemplateNotStreamableError wraps this.
var errStreamGate = errors.New("template not streamable (internal sentinel)")
Expand Down Expand Up @@ -1359,31 +1355,10 @@ func (r *Runtime) ParseWithSourceMap(inputs map[string]string, vars map[string]i
var resultsToFormat interface{}

if r.compiled.ResultsMethod == "per_template" {
// per_template - return single results map
resultsToFormat = results
// per_template - return single results map, with an anonymous
// group's results as the result (Python TTP form_results)
resultsToFormat = formResults(results)
} else {
// per_input - handle anonymous groups
// Anonymous groups with multiple matches need special handling
for _, inputResults := range resultsPerInput {
if anonymousResults, ok := inputResults["_anonymous_"]; ok {
// If _anonymous_ is a list, that becomes the input's result
// Otherwise, merge it into inputResults
if anonymousList, ok := anonymousResults.([]interface{}); ok {
// Anonymous group with multiple matches - store the list for later use
// We'll handle this when creating resultsList
// Store it back in the map temporarily so we can access it
inputResults["_anonymous_list"] = anonymousList
} else {
// Single match or other type - merge into inputResults
delete(inputResults, "_anonymous_")
if anonymousMap, ok := anonymousResults.(map[string]interface{}); ok {
for k, v := range anonymousMap {
inputResults[k] = v
}
}
}
}
}

// per_input - create a result for each input, even if empty
// Create results list with one entry per input
Expand All @@ -1403,27 +1378,16 @@ func (r *Runtime) ParseWithSourceMap(inputs map[string]string, vars map[string]i

for _, inputName := range inputNamesList {
if inputResults, exists := resultsPerInput[inputName]; exists {
// Check if this input has anonymous group results stored as a list
// Anonymous groups with multiple matches are stored at "_anonymous_list" key
if anonymousList, ok := inputResults["_anonymous_list"]; ok {
if list, ok := anonymousList.([]interface{}); ok {
// Anonymous group results - these should BE the entire result list
// Don't append, just use the list directly as the result
resultsToFormat = list
goto skipResultsListBuild
}
}

// This input had results - use its results map
resultsList = append(resultsList, inputResults)
// This input had results; an anonymous group's results
// become this input's result (Python TTP form_results).
resultsList = append(resultsList, formResults(inputResults))
} else {
// Empty result for this input (matches Python TTP behavior)
resultsList = append(resultsList, make(map[string]interface{}))
}
}

resultsToFormat = resultsList
skipResultsListBuild:
}

// Process output functions if any
Expand Down Expand Up @@ -7114,18 +7078,23 @@ func (r *Runtime) processOutputFunctions(results interface{}, vars map[string]in
result = formatted
} else {
// For other formatters, format each input's results separately
// BUT: for table formatter with anonymous groups (list of dicts),
// Python TTP combines all matches into a single table
// BUT: Python TTP's table formatter takes the whole results
// list and flattens each input's result into one table. An
// input's result is a dict, or a list of matches when the
// template has a top-level anonymous group (#62).
if outputConfig.Format == "table" {
// Check if resultList is a list of dicts (anonymous group results)
allDicts := true
allTableable := true
for _, item := range resultList {
if _, ok := item.(map[string]interface{}); !ok {
allDicts = false
switch item.(type) {
case map[string]interface{}, []interface{}:
default:
allTableable = false
}
if !allTableable {
break
}
}
if allDicts {
if allTableable {
// Anonymous group results - combine into single table
formatted, err := formatFn(resultList, nil, kwargs)
if err != nil {
Expand Down
6 changes: 6 additions & 0 deletions internal/compiler/streamability.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,12 @@ func hasAnyJoinMatches(g *CompiledGroup) bool {
// reviewability.
func analyzeStreamability(g *CompiledGroup) {
g.NormalizedPath = strings.TrimSuffix(g.Name, "*")
if g.NormalizedPath == "_anonymous_" {
// The implicit group of a template without group tags is named
// "_anonymous_", as in Python TTP (#62). It streams like an unnamed
// <group>, with an empty path.
g.NormalizedPath = ""
}

var reasons []string

Expand Down
7 changes: 5 additions & 2 deletions internal/parser/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -347,8 +347,11 @@ doneParsingRoot:
if len(tmpl.Groups) == 0 && strings.TrimSpace(root.Content) != "" {
content := strings.TrimSpace(root.Content)
// Create an implicit anonymous group
// Python TTP wraps such a template as <group name="_anonymous_">
// (ttp/ttp.py:1388-1394), not as an unnamed <group>: the path has
// no "*", so one match gives a dict and several give a list (#62).
implicitGroup := &Group{
Name: "", // Empty name = anonymous group
Name: "_anonymous_",
Pattern: content,
Groups: []*Group{},
Attributes: make(map[string]string),
Expand Down Expand Up @@ -746,7 +749,7 @@ func parseChildTemplate(elem xmlElement) (*Template, error) {
if len(childTmpl.Groups) == 0 && strings.TrimSpace(elem.Content) != "" {
content := strings.TrimSpace(elem.Content)
implicitGroup := &Group{
Name: "",
Name: "_anonymous_", // as above: Python TTP's implicit group name
Pattern: content,
Groups: []*Group{},
Attributes: make(map[string]string),
Expand Down
34 changes: 34 additions & 0 deletions parsestream_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,37 @@ ip {{ ip }}
t.Errorf("groupPath %q should strip trailing star, got with star or wrong path", got)
}
}

// A template without group tags gets an implicit group named "_anonymous_"
// (Python TTP's name for it, #62). Like an unnamed <group>, it streams with
// an empty groupPath.
func TestParseStream_ImplicitGroupHasEmptyGroupPath(t *testing.T) {
for _, tmpl := range []string{
"interface {{ name }}",
"<group>\ninterface {{ name }}\n</group>",
} {
c, err := CompileTemplate(tmpl)
if err != nil {
t.Fatalf("compile %q: %v", tmpl, err)
}
var paths []string
var records []map[string]interface{}
err = c.ParseStream(Inputs{"Default_Input": "interface A\ninterface B\n"}, nil, nil,
func(m map[string]interface{}, sr [2]int, gp string) error {
paths = append(paths, gp)
records = append(records, m)
return nil
})
if err != nil {
t.Fatalf("ParseStream %q: %v", tmpl, err)
}
if len(records) != 2 || records[0]["name"] != "A" || records[1]["name"] != "B" {
t.Errorf("%q: records = %v, want A and B", tmpl, records)
}
for _, gp := range paths {
if gp != "" {
t.Errorf("%q: groupPath = %q, want empty", tmpl, gp)
}
}
}
}
Loading
Loading