📖 3 min read (~ 600 words).

Report a key's line and column

The task: a lint rule for a compose-style file. Every image must pin a tag, and each one that does not is reported with its line and column, so an editor can jump to it.

The file

// Two documents. "nginx" and "redis" pin no tag.
const src = `services:
  web:
    image: nginx
    ports:
      - 80
  db:
    image: postgres:17
---
services:
  cache:
    image: redis
`

Full source: docs/examples/documents/keyposition/example_test.go

The stream holds two documents. A Go value would hold the first and no position at all.

The rule

// lint reports every "image" key whose value pins no tag, as file:line:column.
func lint(w io.Writer, name string, src []byte) error {
	f, err := parser.ParseBytes(src)
	if err != nil {
		return err
	}

	for i, doc := range f.Docs {
		// Filter returns every node of one type under the body, in document order.
		for _, n := range ast.Filter(ast.MappingValueType, doc.Body) {
			entry, ok := n.(*ast.MappingValueNode)
			if !ok || entry.Key.String() != "image" {
				continue
			}

			image := entry.Value.String()
			if strings.Contains(image, ":") {
				continue
			}

			pos := entry.Value.GetToken().Position
			fmt.Fprintf(w, "%s:%d:%d: %s %q pins no tag (document %d)\n",
				name, pos.Line, pos.Column, entry.GetPath(), image, i)
		}
	}

	return nil
}

Full source: docs/examples/documents/keyposition/example_test.go

ast.Filter returns every node of one type under a node, in document order. Each MappingValueNode is one entry, with its Key and its Value. Filtering each document’s Body keeps the document index, which ast.FilterFile merges away.

GetToken().Position holds Line and Column, counted from 1 in characters. GetPath returns the entry’s path inside its own document.

Run it

if err := lint(os.Stdout, "compose.yaml", []byte(src)); err != nil {
	fmt.Println(err)
}

Full source: docs/examples/documents/keyposition/example_test.go

compose.yaml:3:12: $.services.web.image "nginx" pins no tag (document 0)
compose.yaml:11:12: $.services.cache.image "redis" pins no tag (document 1)

Full source: docs/examples/documents/keyposition/example_test.go

Both reports point at the value: column 12 is the first character of nginx and of redis. Use entry.Key.GetToken().Position to point at the key, column 5.

One key, by path

When the rule names one key, a path finds it:

path, err := expressions.PathString("$.services.db.image")
if err != nil {
	fmt.Println(err)

	return
}

// FilterFile returns the first match, searching the documents in order.
n, err := path.FilterFile(f)
if err != nil {
	fmt.Println(err)

	return
}
pos := n.GetToken().Position
fmt.Printf("%d:%d %s\n", pos.Line, pos.Column, n)

// AnnotateSource draws the lines around the node, with a caret under it.
annotated, err := path.AnnotateSource([]byte(src), false)
if err != nil {
	fmt.Println(err)

	return
}
fmt.Println(string(annotated))

Full source: docs/examples/documents/keyposition/example_test.go

7:12 postgres:17
   4 |     ports:
   5 |       - 80
   6 |   db:
>  7 |     image: postgres:17
                  ^
   8 | ---
   9 | services:
  10 |   cache:

Full source: docs/examples/documents/keyposition/example_test.go

FilterFile searches the documents in order and returns the first match. AnnotateSource draws three lines of context on each side and a caret under the node’s first character. Pass true to color it.

A path that matches nothing

path, err := expressions.PathString("$.services.api.image")
if err != nil {
	fmt.Println(err)

	return
}
_, err = path.FilterFile(f)
fmt.Println(errors.Is(err, expressions.ErrNotFoundNode))
fmt.Println(err)

Full source: docs/examples/documents/keyposition/example_test.go

true
failed to find path ( $.services.api.image ): node not found

Full source: docs/examples/documents/keyposition/example_test.go

Match the kind with errors.Is and expressions.ErrNotFoundNode.

Variations

  • Point at a collection. A block mapping’s token is the : after its first key, not the key itself: the mapping under web: reports 3:10. Report a key’s position for a collection value.
  • Report positions while reading a large file. A walk hands each node over with its token, and never builds the tree. See Read one subtree of a large file.

See YAMLPath for the path syntax, and Tokens for what a position counts.