codesurgeon

package module
v0.0.0-...-2e4df5a Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2026 License: MIT Imports: 21 Imported by: 0

README

go2json

A Go code parser that outputs structured JSON (or compact Go-syntax) for every struct, function, method, interface, variable, and constant in a package.

The JSON output is machine-readable, so you can pipe it into scripts or AI tools. For example, an LLM can iterate over every function in a package to generate tests, find which handlers match a route pattern, or build a dependency graph — without parsing Go itself.

Install

go install github.com/wricardo/go2json/cmd/go2json@latest

Or build from source:

go build -o go2json ./cmd/go2json

Commands

parse

Parse Go source files and extract structural information.

# Parse current directory (JSON output, default)
go2json parse --path .

# Parse recursively
go2json parse --path . --recursive

# Compact Go-syntax output (optimized for LLMs)
go2json parse --path . --format llm

# With comments enabled
go2json parse --path . --format llm --comments

# Ignore test files
go2json parse --path . --recursive --ignore-rule "*_test.go"
describe

Show a type and all the types it depends on, expanded to a configurable depth.

# Describe a type with default depth (1 level of dependencies)
go2json describe --type UserService

# Go deeper into the dependency tree
go2json describe --type Order --depth 3 --path ./internal/models

# JSON output for programmatic use
go2json describe --type Config --format json --omit-nulls
install-skill

Install the go2json Claude Code skill to ~/.claude/skills/go2json/. This makes the skill available in all Claude Code sessions, giving the AI agent full knowledge of go2json's commands, flags, and usage patterns.

go2json install-skill

Output Formats

  • json (default) — structured JSON with full type details, bodies, params, returns, and tags
  • llm — compact Go-syntax format with same-type field grouping, no indentation, minimal tokens
  • grepindex — one-line-per-entity flat index, pipe through grep to search
LLM Format Example
// directory: ./mypackage
package mypackage
type Config struct{
Host,Port,Path string
Timeout int
Debug,Verbose bool
*Validate() error
*Apply(ctx context.Context) error
}
func NewConfig(host string,port int) *Config
var DefaultConfig Config
const MaxRetries = 3

Fields with the same type are grouped (Host,Port,Path string). Methods are nested inside their struct with * for pointer receivers. No alignment padding, no indentation — minimal tokens.

grepindex Format Example
directory> /project
package> models directory: /project/internal/models
struct> User has_methods package: models
field> ID (string) struct: User has_methods package: models
method> FullName() string receiver: (*User) package: models
function> NewUser(name, email string) *User package: models

Pipe through grep:

# All structs in the project
go2json parse -r --format grepindex | grep "^struct>"

# All methods on a specific type
go2json parse -r --format grepindex | grep "receiver: (\*User)"

Flags

--path, -f                     path to parse (default: ".")
--recursive, -r                recurse into subdirectories
--format                       json, llm, or grepindex (default: "json")
--comments                     include doc comments (default: false)
--plain-structs                include structs without methods (default: true)
--structs-with-method          include structs with methods (default: true)
--fields-plain-structs         include fields of plain structs (default: true)
--fields-structs-with-method   include fields of structs with methods (default: true)
--methods                      include methods (default: true)
--functions                    include functions (default: true)
--tags                         include struct tags (default: true)
--omit-nulls                   omit null/empty values from JSON (default: false)
--ignore-rule                  glob pattern to ignore files (repeatable)

Library Usage

import g2j "github.com/wricardo/go2json"

parsed, err := g2j.ParseDirectoryRecursive("./mypackage")
if err != nil {
    log.Fatal(err)
}
fmt.Println(g2j.PrettyPrint(parsed, "llm", nil, true, true, true, true, true, true, true, false, false))

Requirements

  • Go 1.24.0+

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyFileChanges

func ApplyFileChanges(changes []FileChange) error

ApplyFileChanges applies a set of code changes to multiple files. It creates directories and files as needed, then inserts or updates code fragments in each target file. Changes are grouped by file path before being applied.

func BuildTypeIndex

func BuildTypeIndex(parsed []*ParsedInfo) map[string]typeEntry

BuildTypeIndex indexes every struct, interface, and named type by unqualified name across all parsed packages.

func EnsureGoFileExists

func EnsureGoFileExists(filename string, packageName string) error

func FindFunction

func FindFunction(directory, receiver, functionName string) (foundFilePath string, err error)

FindFunction uses Comby to find a function in a directory. returns the file path and nil error if found returns empty string and nil error if not found returns empty string and error if there was an error

func FormatCodeAndFixImports

func FormatCodeAndFixImports(filePath string) error

FormatCodeAndFixImports applies gofmt and goimports to the modified files.

func FormatWithGoImports

func FormatWithGoImports(filename string) error

func InsertCodeFragments

func InsertCodeFragments(implementationsMap map[string][]CodeFragment) error

InsertCodeFragments inserts or updates code fragments in Go files. It parses each file, applies code changes using AST manipulation, and writes the modified files back. If Overwrite is true, existing declarations are replaced.

func MustRenderTemplate

func MustRenderTemplate(tmpl string, data interface{}) string

MustRenderTemplate is a helper function to render a template with the given data. It panics if the template is invalid.

func PrettyPrint

func PrettyPrint(
	parsed []*ParsedInfo,
	mode string,
	ignoreRules []string,
	plainStructs, fieldsPlainStructs, structsWithMethod, fieldsStructsWithMethod, methods, functions, tags bool,
	comments bool,
	omitNulls bool,
) string

func RenderTemplate

func RenderTemplate(tmpl string, data interface{}) (string, error)

RenderTemplate renders a Go template string with the provided data. Returns the rendered string or an error if the template is invalid or execution fails.

func RenderTemplateNoError

func RenderTemplateNoError(tmpl string, data interface{}) string

RenderTemplateNoError renders a Go template with the given data, ignoring any errors. Use this when you're certain the template is valid and want simpler error handling.

func ToSnakeCase

func ToSnakeCase(s string) string

ToSnakeCase converts a camelCase or PascalCase string to snake_case. It inserts underscores before uppercase letters (except the first character).

Types

type CodeFragment

type CodeFragment struct {
	Content   string
	Overwrite bool
}

type Constant

type Constant struct {
	Name  string   `json:"name"`
	Value string   `json:"value"`
	Docs  []string `json:"docs,omitempty"`
}

Constant represents a constant in a Go package.

type Field

type Field struct {
	Name        string      `json:"name"`
	Type        string      `json:"type"`
	TypeDetails TypeDetails `json:"type_details"`
	Tag         string      `json:"tag,omitempty"`
	Private     bool        `json:"private"`
	Pointer     bool        `json:"pointer"`
	Slice       bool        `json:"slice"`
	Docs        []string    `json:"docs,omitempty"`
	Comment     string      `json:"comment,omitempty"`

	PtrStruct *Struct `json:"-"` // Pointer to the struct that this field belongs to
}

Field represents a field in a Go struct.

type FileChange

type FileChange struct {
	PackageName string
	File        string
	Fragments   []CodeFragment
}

type Function

type Function struct {
	Name        string   `json:"name"`
	Params      []Param  `json:"params,omitempty"`
	Returns     []Param  `json:"returns,omitempty"`
	Docs        []string `json:"docs,omitempty"`
	Signature   string   `json:"signature"`
	Body        string   `json:"body,omitempty"`       // New field for function body
	Definition  string   `json:"definition,omitempty"` // Full Go code definition of the function
	IsExported  bool     `json:"is_exported"`          // Whether the function is exported (public)
	IsTest      bool     `json:"is_test"`              // Whether the function is a test function (TestXxx)
	IsBenchmark bool     `json:"is_benchmark"`         // Whether the function is a benchmark function (BenchmarkXxx)
}

Function represents a Go function with its parameters, return types, and documentation.

type GoList

type GoList struct {
	Dir         string       `json:"Dir"`
	ImportPath  string       `json:"ImportPath"`
	Name        string       `json:"Name"`
	Target      string       `json:"Target"`
	Root        string       `json:"Root"`
	Module      GoListModule `json:"Module"`
	Match       []string     `json:"Match"`
	Stale       bool         `json:"Stale"`
	StaleReason string       `json:"StaleReason"`
	GoFiles     []string     `json:"GoFiles"`
	Imports     []string     `json:"Imports"`
	Deps        []string     `json:"Deps"`
}

type GoListModule

type GoListModule struct {
	Path      string `json:"Path"`
	Main      bool   `json:"Main"`
	Dir       string `json:"Dir"`
	GoMod     string `json:"GoMod"`
	GoVersion string `json:"GoVersion"`
}

type Import

type Import struct {
	Name string `json:"name,omitempty"` // the alias of the package as it's being imported
	Path string `json:"path"`

	PtrPackage *Package `json:"-"` // Pointer to the package that this import belongs to
}

type Interface

type Interface struct {
	Name       string   `json:"name"`
	Methods    []Method `json:"methods,omitempty"`
	Docs       []string `json:"docs,omitempty"`
	Definition string   `json:"definition,omitempty"` // Full Go code definition of the interface
	IsExported bool     `json:"is_exported"`          // Whether the interface is exported (public)

	PtrPackage *Package `json:"-"` // Pointer to the package that this interface belongs to
}

Interface represents a Go interface and its methods.

type Method

type Method struct {
	Receiver    string   `json:"receiver,omitempty"` // Receiver type (e.g., "*MyStruct" or "MyStruct")
	Name        string   `json:"name"`
	Params      []Param  `json:"params,omitempty"`
	Returns     []Param  `json:"returns,omitempty"`
	Docs        []string `json:"docs,omitempty"`
	Signature   string   `json:"signature"`
	Body        string   `json:"body,omitempty"`       // New field for method body
	Definition  string   `json:"definition,omitempty"` // Full Go code definition of the method
	IsExported  bool     `json:"is_exported"`          // Whether the method is exported (public)
	IsTest      bool     `json:"is_test"`              // Whether the method is a test method
	IsBenchmark bool     `json:"is_benchmark"`         // Whether the method is a benchmark method

	PtrStruct *Struct `json:"-"` // Pointer to the struct that this method belongs to
}

Method represents a method in a Go struct or interface.

type Module

type Module struct {
	RootModuleName    string    `json:"root_module_name"`   // Name of the module as seen on the go.mod file of the project
	RelativeDirectory string    `json:"relative_directory"` // Relative (to go.mod) directory of the module / or /cmd/something
	FullName          string    `json:"full_name"`          // Full name of the module, including the relative directory should be RootModuleName/RelativeDirectory
	Packages          []Package `json:"packages"`
}

Module represents a Go module with its packages.

type Package

type Package struct {
	Package    string      `json:"package"`     // Name of the package as seen in the package declaration (e.g., "main")
	ModuleName string      `json:"module_name"` // Name of the module as seen in the go.mod file
	Imports    []Import    `json:"imports,omitempty"`
	Structs    []Struct    `json:"structs,omitempty"`
	Functions  []Function  `json:"functions,omitempty"`
	Variables  []Variable  `json:"variables,omitempty"`
	Constants  []Constant  `json:"constants,omitempty"`
	Interfaces []Interface `json:"interfaces,omitempty"`
	TypeDefs   []TypeDef   `json:"type_defs,omitempty"`

	PtrModule *Module `json:"-"` // Pointer to the module that this package belongs to
}

Package represents a Go package with its components such as imports, structs, functions, etc.

type Param

type Param struct {
	Name        string      `json:"name"` // Name of the parameter or return value
	Type        string      `json:"type"` // Type (e.g., "int", "*string")
	TypeDetails TypeDetails `json:"type_details"`

	PtrMethod *Method   `json:"-"` // Pointer to the method that this parameter belongs to
	PtrFunc   *Function `json:"-"` // Pointer to the function that this parameter belongs to
}

Param represents a parameter or return value in a Go function or method.

type ParsedInfo

type ParsedInfo struct {
	Modules   []Module  `json:"modules"`
	Packages  []Package `json:"packages"`  // Deprecated: use Modules instead
	Directory string    `json:"directory"` // if information was parsed from a directory. It's either a directory or a file
	File      string    `json:"file"`      // if information was parsed from a single file. It's either a directory or a file
}

ParsedInfo holds parsed information about Go packages.

func DescribeType

func DescribeType(typeName string, parsed []*ParsedInfo, maxDepth int) ([]*ParsedInfo, error)

DescribeType performs a BFS from typeName through field and method type references, bounded by maxDepth. It returns synthetic []*ParsedInfo containing only the discovered types, grouped by package.

func ParseDirectory

func ParseDirectory(fileOrDirectory string) (*ParsedInfo, error)

ParseDirectory parses a directory containing Go files and returns the parsed information.

func ParseDirectoryRecursive

func ParseDirectoryRecursive(path string) ([]*ParsedInfo, error)

ParseDirectoryRecursive parses a directory recursively and returns the parsed information.

func ParseDirectoryWithFilter

func ParseDirectoryWithFilter(fileOrDirectory string, filter func(fs.FileInfo) bool) (*ParsedInfo, error)

ParseDirectoryWithFilter parses a directory with an optional filter function to include specific files.

func ParseFile

func ParseFile(fileOrDirectory string) (*ParsedInfo, error)

ParseFile parses a Go file or directory and returns the parsed information.

func ParseString

func ParseString(fileContent string) (*ParsedInfo, error)

ParseString parses Go source code provided as a string and returns the parsed information.

type Struct

type Struct struct {
	Name       string   `json:"name"`
	Fields     []Field  `json:"fields,omitempty"`
	Methods    []Method `json:"methods,omitempty"`
	Docs       []string `json:"docs,omitempty"`
	Definition string   `json:"definition,omitempty"` // Full Go code definition of the struct
	IsExported bool     `json:"is_exported"`          // Whether the struct is exported (public)

	PtrPackage *Package `json:"-"` // Pointer to the package that this struct belongs to
}

Struct represents a Go struct and its fields and methods.

type TypeDef

type TypeDef struct {
	Name       string   `json:"name"`
	Underlying string   `json:"underlying"` // The underlying type expression as a string
	Docs       []string `json:"docs,omitempty"`
	Definition string   `json:"definition,omitempty"` // Full Go code definition
	IsExported bool     `json:"is_exported"`

	PtrPackage *Package `json:"-"`
}

TypeDef represents a named type declaration that is neither a struct nor an interface (e.g., "type SomeFunc func(a string) error" or "type SpecialString string").

type TypeDetails

type TypeDetails struct {
	Package     *string // in the cases of external types. like pbhire.Person this would be "github.com/x/y/pbhire"
	PackageName *string // in the cases of external types. like pbhire.Person this would be "pbhire"
	Type        *string // in the cases of external types. like pbhire.Person this would be "Person"

	TypeName       string
	IsPointer      bool
	IsSlice        bool
	IsMap          bool
	IsBuiltin      bool // if string, int, etc
	IsExternal     bool // if the type is from another package
	TypeReferences []TypeReference
}

type TypeReference

type TypeReference struct {
	Package     *string
	PackageName *string
	Name        string // the name of the type, example TypeReference or Person or int32 or string
}

type Variable

type Variable struct {
	Name string   `json:"name"`
	Type string   `json:"type"`
	Docs []string `json:"docs,omitempty"`
}

Variable represents a global variable in a Go package.

Directories

Path Synopsis
cmd
go2json command
Package main implements the go2json CLI tool.
Package main implements the go2json CLI tool.
examples
example_01 command
example_02 command
example_03 command
example_04 command

Jump to

Keyboard shortcuts

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