commentparsing

package
v0.0.0-...-8b517f2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 19 Imported by: 2 modules, 15 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

commentparsing

Carries a config struct's doc comments into the compiled package, so they can be read back at run time — including from another module, whose source is in the read-only module cache.

A doc comment is the one thing about a field that compilation discards. A struct tag survives, so reflection already reads validate and the rest off the type.

API reference: go doc github.com/smartcontractkit/chainlink-common/x/config/commentparsing. Whole working commands: examples/.

Generate

Add a //go:generate directive and a gen command to the package declaring your config:

//go:generate go run ./gen

func main() {
	if err := commentparsing.Run(commentparsing.RunArgs{
		Roots:       []any{&Config{}},
		Markup:      tomlmarkup.New(),
		Tool:        "example.com/app/gen",
		LocalPrefix: "example.com",
	}); err != nil {
		log.Fatal(err)
	}
}

Run walks the type tree from those roots — through pointers, slices, maps and embedded fields, stopping at a type your config language reads whole — and writes a doccomments_gen.go into every package of your module it reaches. One call covers a config tree spanning several packages. Commit the generated files.

List every type a consumer may reach on its own, not just the outermost config. A package exposing a config and a secrets file, or two sections meant to be embedded independently, needs all of them as roots.

See examples/simple for the smallest whole version of this.

Read it back

fields, err := commentparsing.Lookup(reflect.TypeFor[simple.Config]())
fmt.Println(fields["Timeout"].Comment)

No source, no Go toolchain, no module cache — the comments are compiled in. A type from a dependency reads the same way, as long as that dependency generated. If it did not, Lookup names it and says where to run go generate.

Generating something else from the same comments

Run takes any number of extra generators, each handed the packages it discovered:

commentparsing.Run(args, myJSONSchema, (&configDocs{Dir: "docs/config"}).Generate)

A Package carries its import path, package clause, directory and the types the walk reached with their field comments, so a config file reference or a settings page needs neither the walk nor the parsing. Comments arrive resolved, whether they came from local source or a dependency's compiled methods.

Files is Run without the writing, for a caller that must inspect the output before it lands — a check that committed files are up to date, say.

Examples

Directory Shows
examples/simple One package, one config struct
examples/nested Two packages of one module, reached through an embed, generated by one call
examples/separate_module_use A real module boundary — the consumer reads the dependency's documentation without its source

Each commits its doccomments_gen.go, so the output is readable without running anything. The first two regenerate with go generate ./... from this directory.

separate_module_use is two modules of its own, and go generate ./... never descends into a nested module, so it needs its own invocation:

cd examples/separate_module_use && go generate ./...

Its replace directives exist only because it sits inside this repository. A real consumer requires released versions and needs neither.

Keeping generated files fresh

The source of truth is the doc comment. To change what a field's documentation says, edit the comment and re-run go generate.

Generated files are artifacts, so they can fall behind. Every one needs a //go:generate directive reaching it; CI runs make generate and fails on any resulting diff. Regenerating an unchanged package produces byte-identical output, which is what makes that diff mean something — a generator you add has to sort anything it iterates out of a map.

Deleting a documented type is the one edit that needs a hand: the committed file still declares a method on it, so the package no longer compiles, and a go run ./gen that imports that package to name its roots cannot start — the cleanup below never gets the chance to run. Delete the stale doccomments_gen.go (or have the generate recipe rm the artifacts first, as one would for any generated Go that its own generator imports) and regenerate.

A package that stops documenting anything has its generated file removed, so no committed file keeps methods for types the tree no longer reaches. Removal is limited to files the same Tool wrote, and to the module being generated: another tool's file, and a nested module's, belong to their own runs. A file under the reserved name with no generated-by header at all is never written over — the run fails and names it.

Only non-test files are read, and only those the build in hand selects, as go build selects them.

Known limitations

A config type has to exist on every platform that compiles its package. The file generation writes carries no build constraint of its own, while the source it reads is filtered by the build that ran it. A type declared only in config_linux.go is therefore missed by a run on another platform, and given a receiver those platforms cannot compile by a run on Linux. Same for a type behind a -tags build tag, which is not visible to the generator at all. Supporting one would mean generating per platform and tagging each file, which no config struct here has asked for; declare config types unconditionally.

DocComments is reserved on a documented type. A field or hand-written method of that name cannot coexist with the generated one, so it is reported rather than redeclared.

Two embedded types cannot promote one field name, unless every path to it crosses a pointer. Go leaves that selector legal to declare and illegal to use, and a config file keying on the name cannot say which of the two it means, so generation refuses the type rather than documenting a field nothing can set. Name the field on the outer type to shadow both, or stop embedding one of them. The exception is the polymorphic-section idiom — one pointer embed per variant, all nil but the one a discriminator selects — where the tied fields never exist at once, and an encoder skipping the nil embeds emits the selected variant's keys unambiguously. A tie with even one pointer-free path is still refused.

Documentation promoted through an embedded interface, or an unexported embedded pointer, cannot be read. A lookup constructs the type to call the method on, and neither of those can be filled in from the type alone — an interface has no implementation to pick and an unexported field cannot be set — so the promotion is reported instead. Generating in the package that declares the outer type gives it a method of its own, which is the fix either way.

A generic type cannot be documented. A method on its declaration needs a receiver type parameter list, which the reflected type a run starts from cannot supply. Reported, not generated.

Why generation, rather than finding a dependency's source with the go tool

go list -f '{{.Dir}}' <import path> resolves any package's directory, including a dependency's in the module cache. A consumer could call that and parse the source itself. We chose generation because:

  • It keeps reading documentation a library operation, not a build step. A running service can describe its own configuration; a stripped container image has no Go toolchain to shell out to.
  • go list needs a resolvable module graph. On a cold cache or in a sandbox without network, a directory read becomes a download, or a failure.
  • Whether a nested struct is a config section or an internal detail is a judgement belonging to the package that declares it.
  • A package that has not generated is named, with the fix. A path resolved by string manipulation fails as lstat …: no such file or directory for a path nobody wrote.

The cost: the generated file can drift, every package on the path has to opt in, and nothing verifies from outside that a dependency regenerated.

Documentation

Overview

Package commentparsing recovers a config tree's doc comments and feeds them to code generators.

Run closes that gap from one root value: it parses the comments of types this module declares, reads the compiled DocComments method of types from a dependency, and writes those methods for the local packages so the next module downstream can do the same. See the examples below, the examples directory for whole working commands, and the README for the wider arrangement.

The generated methods are a build artifact, so they can fall behind the comments they were read from. A package that ships them should regenerate in CI and fail on a diff.

Example

A generator names one root and nothing else. commentparsing.Files returns the output rather than writing it, so it can be printed here; a real //go:generate command calls commentparsing.Run and lets the files reach disk.

package main

import (
	"fmt"
	"path/filepath"

	"github.com/smartcontractkit/chainlink-common/x/config/commentparsing"
	"github.com/smartcontractkit/chainlink-common/x/config/commentparsing/examples/simple"
	"github.com/smartcontractkit/chainlink-common/x/config/markup/tomlmarkup"
)

func main() {
	files, err := commentparsing.Files(commentparsing.RunArgs{
		Dir:    filepath.Join("examples", "simple"),
		Roots:  []any{&simple.Config{}},
		Markup: tomlmarkup.New(),
		Tool:   "github.com/smartcontractkit/chainlink-common/x/config/commentparsing/examples/simple/gen",
	})
	if err != nil {
		panic(err)
	}
	fmt.Print(files[filepath.Join(".", commentparsing.GeneratedFileName)])

}
Output:
// Code generated by github.com/smartcontractkit/chainlink-common/x/config/commentparsing/examples/simple/gen, DO NOT EDIT.

package simple

import "github.com/smartcontractkit/chainlink-common/x/config/commentparsing"

func (Config) DocComments() map[string]commentparsing.FieldDoc {
	return map[string]commentparsing.FieldDoc{
		"Endpoint": {Comment: "Endpoint is the upstream URL to dial.\nIt must include a scheme, and a trailing path is preserved."},
		"Retries":  {Comment: "Retries is the attempt count after the first."},
		"Timeout":  {Comment: "Timeout bounds a single request. Zero means no timeout."},
	}
}

Index

Examples

Constants

View Source
const GeneratedFileName = "doccomments_gen.go"

GeneratedFileName is where the DocComments methods are written. It is skipped when parsing, so a regeneration reads the same sources as the first run.

Variables

View Source
var DerefType = decode.DerefType

DerefType strips every level of pointer from t. A nil t stays nil.

Functions

func Files

func Files(args RunArgs, generators ...Generator) (map[string]string, error)

Files discovers the config tree under args and returns what every generator produced from it, keyed by path relative to RunArgs.Dir, cleaned. A path that leaves that directory is an error: nothing outside it is a run's to write, and nothing outside it is covered by the staleness handling Run applies.

The content is what Run would write, header and gofmt included, so a caller that must inspect the output before it lands - a check that committed files are up to date, say - compares the bytes it is given against the bytes on disk.

func Lookup

func Lookup(t reflect.Type) (map[string]FieldDoc, error)

Lookup returns the documentation recorded for t, following pointers to the struct type.

A failure means the generator has not run over the package that declares t.

One gap is not reported: a type that embeds a documented type promotes its method, so a struct whose own package never generated answers with the embedded type's fields. Those comments are right for the fields the embed promoted, and the embedder's own fields are simply absent - undocumented, as any field without a comment is. Only a field that shadows an embedded one by name takes the wrong comment; two embeds promoting one name are refused at generation instead.

Example

A consumer reads the generated methods back at run time, with no access to the source they came from.

package main

import (
	"fmt"
	"reflect"

	"github.com/smartcontractkit/chainlink-common/x/config/commentparsing"
	"github.com/smartcontractkit/chainlink-common/x/config/commentparsing/examples/simple"
)

func main() {
	fields, err := commentparsing.Lookup(reflect.TypeFor[simple.Config]())
	if err != nil {
		panic(err)
	}
	fmt.Println(fields["Timeout"].Comment)

}
Output:
Timeout bounds a single request. Zero means no timeout.

func Run

func Run(args RunArgs, generators ...Generator) error

Run generates as Files does and writes the result.

The reserved GeneratedFileName is managed rather than only written: a file under that name that RunArgs.Tool wrote and this run did not produce is removed, so a package that stops documenting anything does not keep methods for types it no longer has. A file another tool generated is neither removed nor written over, which is what lets two runs share a module; renaming a tool therefore orphans what its old name wrote. A file with no generated-by header at all is left alone too. Either collision fails the run and names the file, before anything is written. Nested modules are left to their own runs.

Types

type DocCommenter

type DocCommenter interface {
	DocComments() map[string]FieldDoc
}

DocCommenter is implemented by the generated code, returning the documentation of the type it was generated for, keyed by Go field name.

type FieldDoc

type FieldDoc struct {
	// Comment is the field's whole doc comment, not just the first sentence.
	Comment string
}

FieldDoc is what a field's declaration says about itself that compilation discards.

type Generator

type Generator func(pkgs []Package) (map[string]string, error)

Generator turns the discovered packages of a config tree into files to write, keyed by path relative to RunArgs.Dir.

The packages arrive already resolved, whether their comments came from local source or from a dependency's compiled methods.

type Package

type Package struct {
	// ImportPath matches what reflection reports as a type's package. Empty for a package parsed
	// without one.
	ImportPath string

	// Name is the package clause.
	Name string

	// Dir is where the package's generated files belong. [ParseDir] reports the directory it
	// read; the walk rewrites it relative to the run directory.
	Dir string

	// Types are sorted by name, so regenerating an unchanged package produces an unchanged file.
	Types []Type
	// contains filtered or unexported fields
}

Package is one package of a config tree, as a Generator receives it.

func ParseDir

func ParseDir(dir string) (*Package, error)

ParseDir reads the doc comments of every struct type declared in the package rooted at dir. Test files are excluded.

Only the files the active build selects are read, as go/build.Context.MatchFile decides it from GOOS, GOARCH and the constraints in each file, so a package declaring one type across config_linux.go and config_windows.go yields the one the build in hand compiles rather than both. Since what generation writes is untagged, a config type that exists on one platform only is not supported: generating on another misses it, and generating on its own leaves a receiver the others cannot compile. A type behind a -tags build tag is not visible here either.

func (*Package) Type

func (p *Package) Type(name string) (Type, bool)

Type finds a type by name. A miss means the type is not declared in the package, which differs from having no documentation.

type RunArgs

type RunArgs struct {
	// Roots are the config values whose type trees are walked. List every type a consumer may
	// reach on its own, not only the outermost config.
	Roots []any

	// Markup is the required config language, such as tomlmarkup.New(). The walk stops at a type
	// it reads whole, whose fields aren't configured one at a time and so need no docs.
	Markup markup.Markup

	// Dir anchors the run: the module enclosing it decides which types are local, and every
	// generated file path is relative to it. Empty means the working directory.
	Dir string

	// LocalPrefix groups this repository's imports after third-party ones, as goimports' -local
	// does.
	LocalPrefix string

	// Tool names the generator in each file's "Code generated by" header.
	Tool string
}

RunArgs are the inputs that cannot be derived from the config tree itself.

type Type

type Type struct {
	Name   string
	Fields map[string]FieldDoc
}

Type is one struct declaration and the documentation of its fields.

Directories

Path Synopsis
examples
nested
Package nested is a config package whose tree reaches into a second package of this module.
Package nested is a config package whose tree reaches into a second package of this module.
nested/gen command
Command gen generates the DocComments for this example.
Command gen generates the DocComments for this example.
nested/upstream
Package upstream is a second package of this module that the consumer's config tree reaches into.
Package upstream is a second package of this module that the consumer's config tree reaches into.
simple
Package simple is a config package that documents itself.
Package simple is a config package that documents itself.
simple/gen command
Command gen generates the DocComments for this example.
Command gen generates the DocComments for this example.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL