goparser

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2025 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package goparser was taken from an open source project (https://github.com/zpatrick/go-parser) by zpatrick. Since it seemed that he had abandon it, I've integrated it into this project (and extended it).

Package goparser was taken from an open source project (https://github.com/zpatrick/go-parser) by zpatrick. Since it seemed that he had abandon it, I've integrated it into this project (and extended it).

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrModuleNotConfigured  = errors.New("module not configured")
	ErrPackageOutsideModule = errors.New("path does not belong to module")
	ErrModuleNotFound       = errors.New("no go.mod found in parent directories")
)
View Source
var (
	// ErrWorkspaceNotFound is returned when no go.work file is found
	ErrWorkspaceNotFound = errors.New("go.work file not found")
	// ErrNoModulesFound is returned when workspace has no modules
	ErrNoModulesFound = errors.New("no modules found in workspace")
)

Functions

func FindModuleOrWorkspace added in v0.6.1

func FindModuleOrWorkspace(path string) (*GoWorkspace, *GoModule, error)

FindModuleOrWorkspace walks up from path checking for go.work or go.mod Prefers go.work over go.mod at each directory level Returns workspace, module, error Exactly one of workspace or module will be non-nil on success

func FormatTypeParams added in v0.5.0

func FormatTypeParams(params []*GoType) string

FormatTypeParams returns the textual representation of a list of type parameters. For example, `[T any, U ~string]` or an empty string when there are no type parameters.

func GetFilePaths

func GetFilePaths(config ParseConfig, paths ...string) ([]string, error)

GetFilePaths will iterate directories (recursively) and add explicit files in the paths.

It is possible to use relative paths or fully qualified paths along with '.' for current directory. The paths are stat:ed so it will check if it is a file or directory and do accordingly. If file it will ignore configuration and blindly accept the file.

func ModuleShortName added in v0.6.1

func ModuleShortName(module *GoModule) string

ModuleShortName returns a short name for a module suitable for anchors Uses the last component of the module path

func NameWithTypeParams added in v0.5.0

func NameWithTypeParams(name string, params []*GoType) string

NameWithTypeParams returns the identifier including formatted type parameters.

func ParseSingleFileWalker

func ParseSingleFileWalker(
	config ParseConfig,
	process ParseSingleFileWalkerFunc,
	paths ...string,
) error

ParseSingleFileWalker is same as ParseAny, except that it will be fed one GoFile at the time and thus consume much less memory.

It uses GetFilePaths and hence, the traversal is in sorted order, directory by directory.

func ParseSinglePackageWalker

func ParseSinglePackageWalker(
	config ParseConfig,
	process ParseSinglePackageWalkerFunc,
	paths ...string,
) error

ParseSinglePackageWalker is same as ParseAny, except that it will be fed one GoPackage at the time and thus consume much less memory.

It uses GetFilePaths and hence, the traversal is in sorted order, directory by directory. It will bundle all files in same directory and assign those to a GoPackage before invoking ParseSinglePackageWalkerFunc

Types

type DebugFunc added in v0.5.0

type DebugFunc func(format string, args ...interface{})

type DocConcatenationMode added in v0.6.1

type DocConcatenationMode int

ParseConfig to use when invoking ParseAny, ParseSingleFileWalker, and ParseSinglePackageWalker.

.ParserConfig [source,go] ---- include::${gad:current:fq}[tag=parse-config,indent=0] ---- <1> These are usually excluded since many testcases is not documented anyhow <2> As of _go 1.16_ it is recommended to *only* use module based parsing tag::parse-config[]

const (
	DocConcatenationNone DocConcatenationMode = iota
	DocConcatenationFull
)

type GoAssignment

type GoAssignment struct {
	File *GoFile
	Name string
	Doc  string
	// Decl will be the same if multi var assignment on same row e.g. var pelle, lisa = 10, 19
	// then both pelle and list will have 'var pelle, lisa = 10, 19' as Decl
	Decl     string
	FullDecl string
	Exported bool
}

GoAssignment represents a single var assignment e.g. var pelle = 10

type GoCustomType

type GoCustomType struct {
	File       *GoFile
	Name       string
	Doc        string
	Type       string
	Decl       string
	Exported   bool
	TypeParams []*GoType
}

GoCustomType is a custom type definition

type GoField

type GoField struct {
	File            *GoFile
	Struct          *GoStruct
	Doc             string
	Decl            string
	Name            string
	Type            string
	Exported        bool
	Tag             *GoTag
	AnonymousStruct *GoStruct
	TypeInfo        *GoType
}

GoField is a field in a file or struct

type GoFile

type GoFile struct {
	Module *GoModule
	// Package is the single package name where as FqPackage is the
	// fully qualified package (if Module) has been set.
	Package string
	// FqPackage is the fully qualified package name (if Module field)
	// is set to calculate the fq package name
	FqPackage        string
	FilePath         string
	Doc              string
	Decl             string
	ImportFullDecl   string
	BuildTags        []string // Build tags extracted from //go:build or // +build directives
	Structs          []*GoStruct
	Interfaces       []*GoInterface
	Imports          []*GoImport
	StructMethods    []*GoStructMethod
	CustomTypes      []*GoCustomType
	CustomFuncs      []*GoMethod
	VarAssignments   []*GoAssignment
	ConstAssignments []*GoAssignment
}

GoFile represents a complete file

func ParseAny

func ParseAny(config ParseConfig, paths ...string) ([]*GoFile, error)

ParseAny parses one or more directories (recursively) for go files. It is also possible to add files along with directories (or just files).

It is possible to use relative paths or fully qualified paths along with '.' for current directory. The paths are stat:ed so it will check if it is a file or directory and do accordingly. If file it will ignore configuration and blindly accept the file.

The example below parses from current directory down recursively and skips test, internal and underscore directories. Example: ParseAny(ParseConfig{}, ".")

Next example will recursively add go files from src and one single test.go under directory dummy (both relative current directory). Example: ParseAny(ParseConfig{}, "./src", "./dummy/test.go")

func ParseCode added in v0.6.1

func ParseCode(code string, opts ...Option) (*GoFile, error)

ParseCode parses inline Go source code with optional configuration.

Example:

code := `package main
func main() {}`
file, err := goparser.ParseCode(code)

// With virtual path
file, err := goparser.ParseCode(code, goparser.WithPath("main.go"))

func ParseDir added in v0.6.1

func ParseDir(path string, opts ...Option) ([]*GoFile, error)

ParseDir recursively parses a directory with optional configuration.

Example:

// Simple
files, err := goparser.ParseDir("./src")

// With options
files, err := goparser.ParseDir("./src",
    goparser.WithModule(mod),
    goparser.WithTests(true),
    goparser.WithBuildTags("linux"))

func ParseFile added in v0.6.1

func ParseFile(path string, opts ...Option) (*GoFile, error)

ParseFile parses a single Go source file with optional configuration.

Example:

// Simple
file, err := goparser.ParseFile("main.go")

// With module
mod, _ := goparser.NewModule("go.mod")
file, err := goparser.ParseFile("main.go", goparser.WithModule(mod))

func ParseFiles deprecated

func ParseFiles(mod *GoModule, paths ...string) ([]*GoFile, error)

ParseFiles parses one or more files

Deprecated: Use Parser.ParseFiles instead:

parser := goparser.NewParser(goparser.WithModule(mod))
files, err := parser.ParseFiles(paths...)

func ParseInlineFile deprecated

func ParseInlineFile(mod *GoModule, path, code string) (*GoFile, error)

ParseInlineFile will parse the code provided.

To simulate package names set the path to some level equal to or greater than GoModule.Base. Otherwise just set path "" to ignore.

Deprecated: Use ParseCode with options instead:

file, err := goparser.ParseCode(code, goparser.WithModule(mod), goparser.WithPath(path))

func ParseInlineFileWithConfig deprecated added in v0.6.1

func ParseInlineFileWithConfig(config ParseConfig, path, code string) (*GoFile, error)

ParseInlineFileWithConfig parses inline code with configuration.

Deprecated: Use ParseCode with options instead:

file, err := goparser.ParseCode(code,
    goparser.WithModule(config.Module),
    goparser.WithPath(path),
    goparser.WithDocConcatenation(config.DocConcatenation))

func ParseSingleFile deprecated

func ParseSingleFile(mod *GoModule, path string) (*GoFile, error)

ParseSingleFile parses a single file at the same time

If a module is passed, it will calculate package relative to that

Deprecated: Use ParseFile with WithModule option instead:

file, err := goparser.ParseFile(path, goparser.WithModule(mod))

func (*GoFile) DeclImports

func (g *GoFile) DeclImports() string

DeclImports emits the imports

func (*GoFile) FindMethodsByReceiver added in v0.2.0

func (g *GoFile) FindMethodsByReceiver(receiver string) []*GoStructMethod

FindMethodsByReceiver searches the file / package after struct and custom type receiver methods that matches the _receiver_ name.

func (*GoFile) ImportPath

func (g *GoFile) ImportPath() (string, error)

ImportPath resolves the import path.

type GoImport

type GoImport struct {
	File *GoFile
	Doc  string
	Name string
	Path string
}

GoImport represents a import of a package

func (*GoImport) Prefix

func (g *GoImport) Prefix() string

Prefix is for an import - guess what prefix will be used in type declarations. For examples:

"strings" -> "strings"
"net/http/httptest" -> "httptest"

Libraries where the package name does not match will be mis-identified.

type GoInterface

type GoInterface struct {
	File        *GoFile
	Doc         string
	Decl        string
	FullDecl    string
	Name        string
	Exported    bool
	Methods     []*GoMethod
	TypeParams  []*GoType
	TypeSet     []*GoType
	TypeSetDecl []string
}

GoInterface specifies a interface definition

type GoMethod

type GoMethod struct {
	File       *GoFile
	Name       string
	Doc        string
	Decl       string
	FullDecl   string
	Exported   bool
	Params     []*GoType
	Results    []*GoType
	TypeParams []*GoType
}

GoMethod is a method on a struct, custom type, interface or just plain function

type GoModule

type GoModule struct {
	// File is the actual parsed go.mod file
	File *modfile.File
	// FilePath is the filepath to the go module
	FilePath string
	// Base is where all other packages are relative to.
	//
	// This is usually the directory to the File field since
	// go.mod is usually in root project folder.
	Base string
	// Name of the module e.g. github.com/mariotoffia/goasciidoc
	Name string
	// Version of this module
	Version string
	// GoVersion specifies the required go version
	GoVersion string
	// UnresolvedDecl contains all unresolved declarations.
	Unresolved []UnresolvedDecl
	// contains filtered or unexported fields
}

GoModule is a simple representation of a go.mod

func FindAllModules added in v0.6.1

func FindAllModules(basePath string) ([]*GoModule, error)

FindAllModules recursively finds all go.mod files under basePath Used when --sub-module is specified without go.work Returns empty slice if no modules found

func FindModule added in v0.5.0

func FindModule(path string) (*GoModule, error)

FindModule walks parent directories of the provided path until it locates a go.mod file. It returns ErrModuleNotFound when no module file is present.

func LoadModule added in v0.6.1

func LoadModule(modPath string) (*GoModule, error)

LoadModule is a convenience wrapper around NewModule that loads from a go.mod file path

func NewModule

func NewModule(path string) (*GoModule, error)

NewModule creates a new module from go.mod pointed out in the in param path parameter.

func NewModuleFromBuff

func NewModuleFromBuff(path string, buff []byte) (*GoModule, error)

NewModuleFromBuff creates a new module from the buff specified in the buff parameter and states that the buff is read from path.

func (*GoModule) AddUnresolvedDeclaration added in v0.4.4

func (gm *GoModule) AddUnresolvedDeclaration(u UnresolvedDecl) *GoModule

func (*GoModule) ResolvePackage

func (gm *GoModule) ResolvePackage(path string) (string, error)

ResolvePackage tries to resolve the full package import path for the provided file path. When the file resides outside of the module or the module lacks sufficient information, an error is returned describing the problem.

type GoPackage

type GoPackage struct {
	GoFile
	// Files are all files in current package.
	Files []*GoFile
}

GoPackage is a aggregation of all GoFiles in a single package for ease of access.

type GoStruct

type GoStruct struct {
	File       *GoFile
	Doc        string
	Decl       string
	FullDecl   string
	Name       string
	Exported   bool
	Fields     []*GoField
	TypeParams []*GoType
}

GoStruct represents a struct

func (*GoStruct) HasJSONTag added in v0.6.1

func (s *GoStruct) HasJSONTag() bool

HasJSONTag returns true if any field in the struct has a json tag

func (*GoStruct) HasYAMLTag added in v0.6.1

func (s *GoStruct) HasYAMLTag() bool

HasYAMLTag returns true if any field in the struct has a yaml tag

func (*GoStruct) ToJSON added in v0.6.1

func (s *GoStruct) ToJSON() string

ToJSON generates an example JSON representation of the struct

func (*GoStruct) ToYAML added in v0.6.1

func (s *GoStruct) ToYAML() string

ToYAML generates an example YAML representation of the struct

type GoStructMethod

type GoStructMethod struct {
	GoMethod
	Receivers     []string
	ReceiverTypes []*GoType
}

GoStructMethod is a GoMethod but has receivers and is positioned on a struct or custom type.

type GoTag

type GoTag struct {
	File  *GoFile
	Field *GoField
	Value string
}

GoTag is a tag on a struct field

func (*GoTag) Get

func (g *GoTag) Get(key string) string

Get returns a struct tag with the specified name e.g. json

type GoType

type GoType struct {
	File       *GoFile
	Name       string
	Type       string
	Underlying string
	Exported   bool
	Inner      []*GoType
	Kind       TypeKind
}

GoType represents a go type such as a array, map, custom type etc.

type GoWorkspace added in v0.6.1

type GoWorkspace struct {
	File      *modfile.WorkFile    // Parsed go.work content
	FilePath  string               // Absolute path to go.work
	Base      string               // Directory containing go.work
	Modules   []*GoModule          // All modules in workspace
	ModuleMap map[string]*GoModule // Module name -> GoModule (for fast lookup)
}

GoWorkspace represents a Go workspace (go.work file)

func FindWorkspace added in v0.6.1

func FindWorkspace(path string) (*GoWorkspace, error)

FindWorkspace searches for go.work file starting from path It walks up the directory tree until a go.work file is found Returns ErrWorkspaceNotFound if no workspace found

func LoadWorkspace added in v0.6.1

func LoadWorkspace(workPath string) (*GoWorkspace, error)

LoadWorkspace loads a workspace from the specified go.work file

func (*GoWorkspace) ContainsModule added in v0.6.1

func (w *GoWorkspace) ContainsModule(importPath string) bool

ContainsModule checks if an import path belongs to any workspace module

func (*GoWorkspace) ModuleForPath added in v0.6.1

func (w *GoWorkspace) ModuleForPath(importPath string) *GoModule

ModuleForPath returns the module that owns the given import path Returns nil if no module matches

type Option added in v0.6.1

type Option func(*Parser)

Option is a functional option for configuring a Parser.

func WithAllBuildTags added in v0.6.1

func WithAllBuildTags() Option

WithAllBuildTags attempts to discover and load all build tag variants.

Example:

parser := goparser.NewParser(goparser.WithAllBuildTags())

func WithBuildTags added in v0.6.1

func WithBuildTags(tags ...string) Option

WithBuildTags sets build tags for conditional compilation. Each string represents a set of comma-separated tags (e.g., "linux,amd64").

Example:

parser := goparser.NewParser(
    goparser.WithBuildTags("linux,amd64", "integration"))

func WithDebug added in v0.6.1

func WithDebug(fn DebugFunc) Option

WithDebug sets a debug logging function. The function is called with debug messages during parsing.

Example:

parser := goparser.NewParser(
    goparser.WithDebug(func(format string, args ...interface{}) {
        log.Printf(format, args...)
    }))

func WithDocConcatenation added in v0.6.1

func WithDocConcatenation(mode DocConcatenationMode) Option

WithDocConcatenation sets the documentation concatenation mode. DocConcatenationFull concatenates doc comments separated by blank lines.

Example:

parser := goparser.NewParser(
    goparser.WithDocConcatenation(goparser.DocConcatenationFull))

func WithIgnoreMarkdownHeadings added in v0.6.1

func WithIgnoreMarkdownHeadings(ignore bool) Option

WithIgnoreMarkdownHeadings removes markdown heading markers from documentation. When enabled, "# Title" becomes "Title" in doc comments.

Example:

parser := goparser.NewParser(goparser.WithIgnoreMarkdownHeadings(true))

func WithInternal added in v0.6.1

func WithInternal(include bool) Option

WithInternal includes internal packages in parsing. By default, internal packages are excluded.

Example:

parser := goparser.NewParser(goparser.WithInternal(true))

func WithModule added in v0.6.1

func WithModule(mod *GoModule) Option

WithModule sets the Go module context for resolving package paths.

Example:

mod, _ := goparser.NewModule("go.mod")
parser := goparser.NewParser(goparser.WithModule(mod))

func WithPath added in v0.6.1

func WithPath(path string) Option

WithPath sets a virtual path for inline code parsing. This is only used when calling Parser.ParseCode without an explicit path.

Example:

parser := goparser.NewParser(goparser.WithPath("virtual.go"))
file, err := parser.ParseCode(code, "") // Uses "virtual.go"

func WithTests added in v0.6.1

func WithTests(include bool) Option

WithTests includes test files (*_test.go) in parsing. By default, test files are excluded.

Example:

parser := goparser.NewParser(goparser.WithTests(true))

func WithUnderScore added in v0.6.1

func WithUnderScore(include bool) Option

WithUnderScore includes directories starting with underscore. By default, underscore directories are excluded.

Example:

parser := goparser.NewParser(goparser.WithUnderScore(true))

type ParseConfig

type ParseConfig struct {
	// Test denotes if test files (ending with _test.go) should be included or not
	// (default not included)
	Test bool // <1>
	// Internal determines if internal folders are included or not (default not)
	Internal bool
	// UnderScore, when set to true it will include directories beginning with _
	UnderScore bool
	// Optional module to resolve fully qualified package paths
	Module *GoModule // <2>
	// Workspace contains multi-module workspace information
	// When set, Module field may be nil (workspace contains multiple modules)
	Workspace *GoWorkspace
	// Debug collects debug statements during traversal.
	Debug DebugFunc
	// DocConcatenation controls how doc comments split by blank lines are handled.
	DocConcatenation DocConcatenationMode
	// BuildTags specifies build tags to use when loading packages.
	// Each string represents a set of comma-separated tags (e.g., "linux,amd64").
	// If empty, default build constraints apply.
	BuildTags []string
	// AllBuildTags when set to true, attempts to discover and load all build tags.
	AllBuildTags bool
	// IgnoreMarkdownHeadings when set to true, replaces markdown headings (#, ##, etc.) in comments with their text content
	IgnoreMarkdownHeadings bool
	// Excludes specifies regular expressions (or glb:-prefixed glob-like patterns) for paths to exclude from documentation generation.
	// Patterns are applied to slash-separated absolute and relative paths.
	Excludes []string
}

func (*ParseConfig) GetAllModules added in v0.6.1

func (pc *ParseConfig) GetAllModules() []*GoModule

GetAllModules returns all modules from workspace or single module as slice

func (*ParseConfig) GetModuleForPath added in v0.6.1

func (pc *ParseConfig) GetModuleForPath(path string) *GoModule

GetModuleForPath returns the appropriate module for a given file path In workspace mode, it finds which module owns the path In single-module mode, returns the configured Module

type ParseSingleFileWalkerFunc

type ParseSingleFileWalkerFunc func(*GoFile) error

ParseSingleFileWalkerFunc is used in conjunction with ParseSingleFileWalker.

If the ParseSingleFileWalker is returning an error, parsing will immediately stop and the error is returned.

type ParseSinglePackageWalkerFunc

type ParseSinglePackageWalkerFunc func(*GoPackage) error

ParseSinglePackageWalkerFunc is used in conjunction with ParseSinglePackageWalker.

If the ParseSinglePackageWalker is returning an error, parsing will immediately stop and the error is returned.

type Parser added in v0.6.1

type Parser struct {
	// contains filtered or unexported fields
}

Parser holds parsing configuration and provides methods for parsing Go source code. Create a new Parser using NewParser with optional configuration.

Example:

parser := goparser.NewParser(
    goparser.WithModule(mod),
    goparser.WithBuildTags("linux"))
file, err := parser.ParseFile("main.go")

func NewParser added in v0.6.1

func NewParser(opts ...Option) *Parser

NewParser creates a new Parser with the specified options. If no options are provided, sensible defaults are used.

Example:

parser := goparser.NewParser(
    goparser.WithModule(mod),
    goparser.WithTests(true))

func (*Parser) ParseCode added in v0.6.1

func (p *Parser) ParseCode(code string, virtualPath string) (*GoFile, error)

ParseCode parses inline Go source code. The virtualPath parameter is optional and can be empty string.

Example:

code := `package main
func main() {}`
file, err := parser.ParseCode(code, "main.go")

func (*Parser) ParseDir added in v0.6.1

func (p *Parser) ParseDir(paths ...string) ([]*GoFile, error)

ParseDir recursively parses one or more directories. It also accepts individual file paths.

Example:

files, err := parser.ParseDir("./src", "./cmd")

func (*Parser) ParseFile added in v0.6.1

func (p *Parser) ParseFile(path string) (*GoFile, error)

ParseFile parses a single Go source file.

Example:

file, err := parser.ParseFile("main.go")

func (*Parser) ParseFiles added in v0.6.1

func (p *Parser) ParseFiles(paths ...string) ([]*GoFile, error)

ParseFiles parses multiple Go source files. All files are parsed with the same configuration.

Example:

files, err := parser.ParseFiles("file1.go", "file2.go", "file3.go")

func (*Parser) WalkFiles added in v0.6.1

func (p *Parser) WalkFiles(fn func(*GoFile) error, paths ...string) error

WalkFiles walks through the specified files one at a time, calling fn for each. This is memory efficient for processing large numbers of files.

Example:

err := parser.WalkFiles(func(file *GoFile) error {
    fmt.Println(file.Package)
    return nil
}, "./src")

func (*Parser) WalkPackages added in v0.6.1

func (p *Parser) WalkPackages(fn func(*GoPackage) error, paths ...string) error

WalkPackages walks through packages one at a time, calling fn for each. Files in the same directory are grouped into a single GoPackage. This is memory efficient for processing large codebases.

Example:

err := parser.WalkPackages(func(pkg *GoPackage) error {
    fmt.Printf("Package %s has %d files\n", pkg.Package, len(pkg.Files))
    return nil
}, "./src")

type Resolver added in v0.2.0

type Resolver interface {
	LoadAll() ([]*GoPackage, error)
}

func NewResolver added in v0.2.0

func NewResolver(config ParseConfig, filepath string) (Resolver, error)

NewResolver creates a new `Resolver` from the filepath to the _go.mod_ file or directory where _go.mod_ resides.

type ResolverImpl added in v0.2.0

type ResolverImpl struct {
	// contains filtered or unexported fields
}

ResolverImpl is the implementation of a `Resolver` where it operarates on a `GoModule` level.

func (*ResolverImpl) LoadAll added in v0.4.4

func (r *ResolverImpl) LoadAll() ([]*GoPackage, error)

type TypeKind added in v0.5.0

type TypeKind int

TypeKind represents the general classification of a Go type expression.

const (
	TypeKindUnknown TypeKind = iota
	TypeKindIdent
	TypeKindSelector
	TypeKindPointer
	TypeKindArray
	TypeKindSlice
	TypeKindMap
	TypeKindChan
	TypeKindFunc
	TypeKindStruct
	TypeKindInterface
	TypeKindEllipsis
	TypeKindIndex
	TypeKindIndexList
	TypeKindBinaryExpr
	TypeKindParen
)

type UnresolvedDecl added in v0.4.4

type UnresolvedDecl struct {
	Expr    ast.Expr
	Message string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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