### Access Package symbols and examples Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Methods to list constants, functions, types, and package-level examples. ```go func (pkg *Package) Consts() (consts []*Value) ``` ```go func (pkg *Package) Examples() (examples []*Example) ``` ```go func (pkg *Package) Funcs() (funcs []*Func) ``` ```go func (pkg *Package) Types() (types []*Type) ``` -------------------------------- ### Manage documentation examples Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Structures for representing and creating documentation examples. ```go type Example struct { // contains filtered or unexported fields } ``` ```go func NewExample(cfg *Config, name string, doc *doc.Example) *Example ``` -------------------------------- ### Install gomarkdoc Command Line Tool (Go 1.16+) Source: https://github.com/princjef/gomarkdoc/blob/master/README.md Install the gomarkdoc command-line tool using 'go install'. This command is for Go versions 1.16 and newer. ```bash go install github.com/princjef/gomarkdoc/cmd/gomarkdoc@latest ``` -------------------------------- ### Install gomarkdoc Command Line Tool (Older Go Versions) Source: https://github.com/princjef/gomarkdoc/blob/master/README.md Install the gomarkdoc command-line tool using 'go get' for older Go versions. Ensure GO111MODULE is set to 'on'. ```bash GO111MODULE=on go get -u github.com/princjef/gomarkdoc/cmd/gomarkdoc ``` -------------------------------- ### Example Documentation Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Functions and types related to Go example documentation. ```APIDOC ## Example Documentation ### Description Provides functions and types for working with Go example documentation. ### Types #### `type Example` - **Description**: Represents a Go example. ##### Methods - **`NewExample(cfg *Config, name string, doc *doc.Example) *Example`** - **Description**: Creates a new Example. - **`(*Example) Code() (string, error)`** - **Description**: Returns the code of the example. - **`(*Example) Doc() *Doc`** - **Description**: Returns the documentation for the example. - **`(*Example) HasOutput() bool`** - **Description**: Checks if the example has output. - **`(*Example) Level() int`** - **Description**: Returns the documentation level of the example. - **`(*Example) Location() Location`** - **Description**: Returns the location of the example. - **`(*Example) Name() string`** - **Description**: Returns the name of the example. - **`(*Example) Output() string`** - **Description**: Returns the output of the example. - **`(*Example) Summary() string`** - **Description**: Returns the summary of the example. - **`(*Example) Title() string`** - **Description**: Returns the title of the example. ``` -------------------------------- ### Define struct methods Source: https://github.com/princjef/gomarkdoc/blob/master/testData/docs/README-plain.md Examples of struct initializer and method signatures. ```go func NewAnotherStruct() *AnotherStruct ``` ```go func (s *AnotherStruct) GetField() string ``` -------------------------------- ### NewExample Function Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Creates a new Example struct from its name, documentation, and associated code. ```APIDOC ## func NewExample ### Description NewExample creates a new example from the example function's name, its documentation example and the files holding code related to the example. ### Parameters - **cfg** (*Config) - The configuration to use. - **name** (string) - The name of the example function. - **doc** (*doc.Example) - The documentation example object. ### Returns - **(*Example)** - A pointer to the created Example object. ``` -------------------------------- ### Get Package Variables Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Lists the top-level variables provided by the package. No setup is required. ```go func (pkg *Package) Vars() (vars []*Value) ``` -------------------------------- ### Example Usage of Receiver Type Initialization Source: https://github.com/princjef/gomarkdoc/blob/master/testData/lang/function/README-azure-devops.md Shows how to create a pointer to a Receiver instance and print it. Includes comments. ```go package main import ( "fmt" "github.com/princjef/gomarkdoc/testData/lang/function" ) func main() { // Add some comments r := &function.Receiver{} // And some more fmt.Println(r) } ``` -------------------------------- ### Define constants Source: https://github.com/princjef/gomarkdoc/blob/master/testData/docs/README-plain.md Examples of constant declarations. ```go const ( Const1 = 1 Const2 = 2 Const3 = 3 ) ``` ```go const Constant = 3 ``` -------------------------------- ### Example Struct Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Represents a single documentation example for a package or symbol. ```APIDOC ## type Example ### Description Example holds a single documentation example for a package or symbol. ``` -------------------------------- ### Render Multi-Package File Documentation Source: https://context7.com/princjef/gomarkdoc/llms.txt This example shows how to render documentation for multiple Go packages into a single file, including optional headers and footers. It involves loading packages, creating a file structure, and writing the output. ```go package main import ( "fmt" "go/build" "os" "path/filepath" "github.com/princjef/gomarkdoc" "github.com/princjef/gomarkdoc/lang" "github.com/princjef/gomarkdoc/logger" ) func main() { log := logger.New(logger.WarnLevel) var packages []*lang.Package // Load multiple packages dirs := []string{"./pkg/api", "./pkg/client", "./pkg/models"} for _, dir := range dirs { buildPkg, err := build.ImportDir(dir, build.ImportComment) if err != nil { fmt.Printf("Skipping %s: %v\n", dir, err) continue } pkg, err := lang.NewPackageFromBuild(log, buildPkg) if err != nil { fmt.Printf("Error loading %s: %v\n", dir, err) continue } packages = append(packages, pkg) } // Create a file containing all packages file := lang.NewFile( "# API Documentation\n\nGenerated documentation for the project.\n", "\n---\nGenerated by gomarkdoc", packages, ) renderer, err := gomarkdoc.NewRenderer() if err != nil { panic(err) } // Render the entire file markdown, err := renderer.File(file) if err != nil { panic(err) } if err := os.WriteFile("docs/API.md", []byte(markdown), 0644); err != nil { panic(err) } fmt.Println("Multi-package documentation generated") } ``` -------------------------------- ### Define variables Source: https://github.com/princjef/gomarkdoc/blob/master/testData/docs/README-plain.md Examples of variable declarations. ```go var ( VarA = 'a' VarB = 'b' VarC = 'c' ) ``` ```go var Var = 2 ``` -------------------------------- ### Define a struct Source: https://github.com/princjef/gomarkdoc/blob/master/testData/docs/README-plain.md Example of a struct definition. ```go type AnotherStruct struct { Field string } ``` -------------------------------- ### Define a function signature Source: https://github.com/princjef/gomarkdoc/blob/master/testData/docs/README-plain.md Example of a function signature. ```go func Func(param int) int ``` -------------------------------- ### Define a type and its method Source: https://github.com/princjef/gomarkdoc/blob/master/testData/docs/README-plain.md Example of a type definition and its associated method. ```go type Type struct{} ``` ```go func (t *Type) Func() ``` -------------------------------- ### Programmatic usage in Go Source: https://github.com/princjef/gomarkdoc/blob/master/README.md Example of using the gomarkdoc package directly within a Go application to generate documentation. ```go package main import ( "go/build" "fmt" "os" "github.com/princjef/gomarkdoc" "github.com/princjef/gomarkdoc/lang" "github.com/princjef/gomarkdoc/logger" ) func main() { // Create a renderer to output data out, err := gomarkdoc.NewRenderer() if err != nil { // handle error } wd, err := os.Getwd() if err != nil { // handle error } buildPkg, err := build.ImportDir(wd, build.ImportComment) if err != nil { // handle error } // Create a documentation package from the build representation of our // package. log := logger.New(logger.DebugLevel) pkg, err := lang.NewPackageFromBuild(log, buildPkg) if err != nil { // handle error } // Write the documentation out to console. fmt.Println(out.Package(pkg)) } ``` -------------------------------- ### Example Usage of Standalone Function Source: https://github.com/princjef/gomarkdoc/blob/master/testData/lang/function/README-azure-devops.md Demonstrates calling the Standalone function with specific arguments and printing the result. Includes a comment within the code. ```go package main import ( "fmt" "github.com/princjef/gomarkdoc/testData/lang/function" ) func main() { // Comment res, _ := function.Standalone(2, "abc") fmt.Println(res) } ``` -------------------------------- ### Access Go Package Information Programmatically Source: https://context7.com/princjef/gomarkdoc/llms.txt Use `lang.NewPackageFromBuild` to load package details. This snippet demonstrates how to retrieve and print metadata, constants, variables, functions, types, and examples from a Go package. ```go package main import ( "fmt" "go/build" "github.com/princjef/gomarkdoc/lang" "github.com/princjef/gomarkdoc/logger" ) func main() { log := logger.New(logger.WarnLevel) buildPkg, err := build.ImportDir(".", build.ImportComment) if err != nil { panic(err) } pkg, err := lang.NewPackageFromBuild(log, buildPkg) if err != nil { panic(err) } // Package metadata fmt.Printf("Name: %s\n", pkg.Name()) fmt.Printf("Import Path: %s\n", pkg.ImportPath()) fmt.Printf("Import Statement: %s\n", pkg.Import()) fmt.Printf("Directory: %s\n", pkg.Dir()) fmt.Printf("Summary: %s\n", pkg.Summary()) // Package contents fmt.Printf("\nConstants: %d\n", len(pkg.Consts())) for _, c := range pkg.Consts() { decl, _ := c.Decl() fmt.Printf(" %s\n", decl) } fmt.Printf("\nVariables: %d\n", len(pkg.Vars())) for _, v := range pkg.Vars() { decl, _ := v.Decl() fmt.Printf(" %s\n", decl) } fmt.Printf("\nFunctions: %d\n", len(pkg.Funcs())) for _, fn := range pkg.Funcs() { sig, _ := fn.Signature() fmt.Printf(" %s - %s\n", fn.Name(), sig) } fmt.Printf("\nTypes: %d\n", len(pkg.Types())) for _, typ := range pkg.Types() { fmt.Printf(" %s - %s\n", typ.Name(), typ.Summary()) fmt.Printf(" Methods: %d\n", len(typ.Methods())) fmt.Printf(" Constructors: %d\n", len(typ.Funcs())) } fmt.Printf("\nExamples: %d\n", len(pkg.Examples())) for _, ex := range pkg.Examples() { code, _ := ex.Code() fmt.Printf(" %s:\n%s\n", ex.Title(), code) } } ``` -------------------------------- ### Example Usage of Receiver with Value Receiver Source: https://github.com/princjef/gomarkdoc/blob/master/testData/lang/function/README-azure-devops.md Demonstrates calling a method that has a value receiver on a Receiver instance. ```go package main import ( "github.com/princjef/gomarkdoc/testData/lang/function" ) func main() { var r function.Receiver r.WithReceiver() } ``` -------------------------------- ### Example Usage of Standalone Function with Zero Value Source: https://github.com/princjef/gomarkdoc/blob/master/testData/lang/function/README-azure-devops.md Shows how to call the Standalone function with a zero integer value and a string, then prints the output. ```go package main import ( "fmt" "github.com/princjef/gomarkdoc/testData/lang/function" ) func main() { res, _ := function.Standalone(0, "def") fmt.Println(res) } ``` -------------------------------- ### Define a Go function Source: https://github.com/princjef/gomarkdoc/blob/master/testData/docs/README-plain.md Example of a simple Go function block. ```go func GolangCode(t int) int { return t + 1 } ``` -------------------------------- ### Golang function example Source: https://github.com/princjef/gomarkdoc/blob/master/testData/docs/README-github.md A simple Go function that takes an integer and returns an integer incremented by one. This is a basic example of a function definition. ```go func GolangCode(t int) int { return t + 1 } ``` -------------------------------- ### Example Usage of Generic Type and Method Source: https://github.com/princjef/gomarkdoc/blob/master/testData/lang/function/README-azure-devops.md Demonstrates creating an instance of the Generic struct with a specific type (int) and calling its method. ```go package main import ( "github.com/princjef/gomarkdoc/testData/lang/function" ) func main() { r := function.Generic[int]{} r.WithGenericReceiver() } ``` -------------------------------- ### Package Documentation Source: https://github.com/princjef/gomarkdoc/blob/master/testData/docs/README-azure-devops.md This section covers the overall package documentation, including descriptions, cross-references, and code examples. ```APIDOC ## Package Documentation Package docs exercises the documentation features of golang 1.19 and above at the package documentation level. This package documentation includes references to the standard library, internal functions, types, and external links. It also demonstrates numbered and non-numbered lists, as well as Go code blocks and preformatted text blocks. ### Cross-references - Standard Library: [math/rand]() - Internal Function: [Func](<#Func>) - Internal Type: [Type](<#Type>) - Type's Function: [Type.Func](<#Type.Func>) - External Package: [golang.org/x/crypto/bcrypt.Cost]() - External Link: [Outside Link]() - Direct Link: https://github.com ### Lists **Numbered List:** 1. First 2. Second 3. Third **Numbered List with blank lines:** 1. First 2. Second 3. Third **Non-numbered List:** - First another line - Second - Third **Non-numbered List with blank lines:** - First another paragraph - Second - Third ### Code Blocks **Golang Code Block:** ```go func GolangCode(t int) int { return t + 1 } ``` **Random Code Block:** ``` something preformatted in a random way ``` ``` -------------------------------- ### Implement Custom Format Interface in Go Source: https://context7.com/princjef/gomarkdoc/llms.txt Implement the `format.Format` interface to define custom rendering logic for documentation elements. This example shows how to create a `CustomFormat` struct that handles bold text, code blocks, headers, links, and more. ```go package main import ( "fmt" "strings" "github.com/princjef/gomarkdoc/lang" ) // CustomFormat implements the format.Format interface type CustomFormat struct{} func (f *CustomFormat) Bold(text string) (string, error) { return fmt.Sprintf("**%s**", text), nil } func (f *CustomFormat) CodeBlock(language, code string) (string, error) { return fmt.Sprintf("```%s\n%s\n```", language, code), nil } func (f *CustomFormat) Anchor(anchor string) string { return fmt.Sprintf(``, anchor) } func (f *CustomFormat) AnchorHeader(level int, text, anchor string) (string, error) { hashes := strings.Repeat("#", level) return fmt.Sprintf(`%s %s`, hashes, anchor, text), nil } func (f *CustomFormat) Header(level int, text string) (string, error) { hashes := strings.Repeat("#", level) return fmt.Sprintf("%s %s", hashes, text), nil } func (f *CustomFormat) RawAnchorHeader(level int, text, anchor string) (string, error) { return f.AnchorHeader(level, text, anchor) } func (f *CustomFormat) RawHeader(level int, text string) (string, error) { return f.Header(level, text) } func (f *CustomFormat) LocalHref(headerText string) (string, error) { slug := strings.ToLower(strings.ReplaceAll(headerText, " ", "-")) return fmt.Sprintf("#%s", slug), nil } func (f *CustomFormat) RawLocalHref(anchor string) string { return fmt.Sprintf("#%s", anchor) } func (f *CustomFormat) Link(text, href string) (string, error) { return fmt.Sprintf("[%s](%s)", text, href), nil } func (f *CustomFormat) CodeHref(loc lang.Location) (string, error) { if loc.Repo == nil { return "", nil } return fmt.Sprintf("%s/blob/%s/%s#L%d", loc.Repo.Remote, loc.Repo.DefaultBranch, loc.Filepath, loc.Start.Line, ), nil } func (f *CustomFormat) ListEntry(depth int, text string) (string, error) { indent := strings.Repeat(" ", depth) return fmt.Sprintf("%s- %s", indent, text), nil } func (f *CustomFormat) Accordion(title, body string) (string, error) { return fmt.Sprintf("
\n%s\n\n%s\n
", title, body), nil } func (f *CustomFormat) AccordionHeader(title string) (string, error) { return fmt.Sprintf("
\n%s\n\n", title), nil } func (f *CustomFormat) AccordionTerminator() (string, error) { return "\n
", nil } func (f *CustomFormat) Escape(text string) string { replacer := strings.NewReplacer( `\`, `\\`, `*`, `\*`, `_`, `\_`, `[`, `\[`, `]`, `\]`, ) return replacer.Replace(text) } func main() { customFmt := &CustomFormat{} bold, _ := customFmt.Bold("Important") fmt.Println(bold) // **Important** code, _ := customFmt.CodeBlock("go", "fmt.Println(\"Hello\")") fmt.Println(code) } ``` -------------------------------- ### Preformatted text block Source: https://github.com/princjef/gomarkdoc/blob/master/testData/docs/README-plain.md Example of a generic preformatted text block. ```text something preformatted in a random way ``` -------------------------------- ### Call Receiver Method with Pointer Receiver Source: https://github.com/princjef/gomarkdoc/blob/master/testData/lang/function/README-plain.md Example of calling a method on a Receiver struct using a pointer receiver. ```go package main import ( "github.com/princjef/gomarkdoc/testData/lang/function" ) func main() { r := &function.Receiver{} r.WithPtrReceiver() } ``` -------------------------------- ### Random code block example Source: https://github.com/princjef/gomarkdoc/blob/master/testData/docs/README-github.md A preformatted block of text demonstrating arbitrary content. This is not specific to any programming language. ```text something preformatted in a random way ``` -------------------------------- ### Override Gomarkdoc Templates Source: https://github.com/princjef/gomarkdoc/blob/master/README.md Use the --template-file/-t option to replace default documentation templates with custom ones. This example overrides the 'package' and 'doc' templates. ```bash gomarkdoc --template-file package=custom-package.gotxt --template-file doc=custom-doc.gotxt . ``` -------------------------------- ### Get Block Kind Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Retrieves the kind of a documentation block, indicating how its text content should be interpreted (e.g., paragraph, code block). ```go func (b *Block) Kind() BlockKind ``` -------------------------------- ### Get Package Symbols Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Retrieves a map of symbols for a given Go doc package. This is useful for analyzing the structure of documented code. ```go func PackageSymbols(pkg *doc.Package) map[string]Symbol ``` -------------------------------- ### Create Package instances Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Methods to initialize a Package representation from raw constructs or build metadata. ```go func NewPackage(cfg *Config, examples []*doc.Example) *Package ``` ```go func NewPackageFromBuild(log logger.Logger, pkg *build.Package, opts ...PackageOption) (*Package, error) ``` -------------------------------- ### Render Go Type Documentation Source: https://context7.com/princjef/gomarkdoc/llms.txt This snippet demonstrates rendering documentation for a Go type, including its methods. Ensure the package and renderer are properly initialized. ```go package main import ( "fmt" "go/build" "github.com/princjef/gomarkdoc" "github.com/princjef/gomarkdoc/lang" "github.com/princjef/gomarkdoc/logger" ) func main() { log := logger.New(logger.WarnLevel) buildPkg, err := build.ImportDir(".", build.ImportComment) if err != nil { panic(err) } pkg, err := lang.NewPackageFromBuild(log, buildPkg) if err != nil { panic(err) } renderer, err := gomarkdoc.NewRenderer() if err != nil { panic(err) } // Iterate through all types in the package for _, typ := range pkg.Types() { // Render the type documentation markdown, err := renderer.Type(typ) if err != nil { fmt.Printf("Error rendering type %s: %v\n", typ.Name(), err) continue } fmt.Printf("Type: %s\n", typ.Name()) fmt.Printf("Summary: %s\n", typ.Summary()) fmt.Printf("Methods: %d\n", len(typ.Methods())) fmt.Printf("Functions: %d\n", len(typ.Funcs())) fmt.Println(markdown) } } ``` -------------------------------- ### Configure Documentation Renderer Source: https://context7.com/princjef/gomarkdoc/llms.txt Initializes a renderer with support for custom formats, template overrides, and custom template functions. ```go package main import ( "fmt" "github.com/princjef/gomarkdoc" "github.com/princjef/gomarkdoc/format" ) func main() { // Create renderer with default GitHub format renderer, err := gomarkdoc.NewRenderer() if err != nil { panic(err) } // Create renderer with Azure DevOps format azureRenderer, err := gomarkdoc.NewRenderer( gomarkdoc.WithFormat(&format.AzureDevOpsMarkdown{}), ) if err != nil { panic(err) } // Create renderer with custom template override customRenderer, err := gomarkdoc.NewRenderer( gomarkdoc.WithFormat(&format.GitHubFlavoredMarkdown{}), gomarkdoc.WithTemplateOverride("package", ` # {{.Name}} {{.Doc.Text}} ## Functions {{range .Funcs}} ### {{.Name}} {{.Doc.Text}} {{end}} `), ) if err != nil { panic(err) } // Create renderer with custom template function funcRenderer, err := gomarkdoc.NewRenderer( gomarkdoc.WithTemplateFunc("uppercase", func(s string) string { return strings.ToUpper(s) }), ) if err != nil { panic(err) } fmt.Println("Renderers created successfully") _ = renderer _ = azureRenderer _ = customRenderer _ = funcRenderer } ``` -------------------------------- ### Create Package from Build Metadata Source: https://context7.com/princjef/gomarkdoc/llms.txt Initializes a documentation package representation using Go's build system metadata. This is the primary entry point for programmatic generation. ```go package main import ( "fmt" "go/build" "os" "github.com/princjef/gomarkdoc" "github.com/princjef/gomarkdoc/lang" "github.com/princjef/gomarkdoc/logger" ) func main() { // Create a logger log := logger.New(logger.DebugLevel) // Get the current working directory wd, err := os.Getwd() if err != nil { fmt.Fprintf(os.Stderr, "Error getting working directory: %v\n", err) os.Exit(1) } // Import the package using Go's build system buildPkg, err := build.ImportDir(wd, build.ImportComment) if err != nil { fmt.Fprintf(os.Stderr, "Error importing package: %v\n", err) os.Exit(1) } // Create documentation package with options pkg, err := lang.NewPackageFromBuild(log, buildPkg, lang.PackageWithUnexportedIncluded(), lang.PackageWithRepositoryOverrides(&lang.Repo{ Remote: "https://github.com/user/repo", DefaultBranch: "main", PathFromRoot: "/", }), ) if err != nil { fmt.Fprintf(os.Stderr, "Error creating package: %v\n", err) os.Exit(1) } // Create a renderer and output the documentation renderer, err := gomarkdoc.NewRenderer() if err != nil { fmt.Fprintf(os.Stderr, "Error creating renderer: %v\n", err) os.Exit(1) } output, err := renderer.Package(pkg) if err != nil { fmt.Fprintf(os.Stderr, "Error rendering package: %v\n", err) os.Exit(1) } fmt.Println(output) } ``` -------------------------------- ### Render Go Function Documentation Source: https://context7.com/princjef/gomarkdoc/llms.txt Use this snippet to render documentation for a single Go function. It requires loading the package and initializing the renderer. ```go package main import ( "fmt" "go/build" "github.com/princjef/gomarkdoc" "github.com/princjef/gomarkdoc/lang" "github.com/princjef/gomarkdoc/logger" ) func main() { log := logger.New(logger.WarnLevel) buildPkg, err := build.ImportDir(".", build.ImportComment) if err != nil { panic(err) } pkg, err := lang.NewPackageFromBuild(log, buildPkg) if err != nil { panic(err) } renderer, err := gomarkdoc.NewRenderer() if err != nil { panic(err) } // Get all functions in the package funcs := pkg.Funcs() for _, fn := range funcs { // Render individual function documentation markdown, err := renderer.Func(fn) if err != nil { fmt.Printf("Error rendering %s: %v\n", fn.Name(), err) continue } fmt.Printf("=== %s ===\n%s\n", fn.Name(), markdown) } } ``` -------------------------------- ### Define EmbeddedFunc Source: https://github.com/princjef/gomarkdoc/blob/master/testData/embed/README-plain.md Function signature for the embedded documentation example. ```go func EmbeddedFunc(param int) int ``` -------------------------------- ### YAML Configuration Source: https://context7.com/princjef/gomarkdoc/llms.txt Use a .gomarkdoc.yml file in the project root for reusable configuration. ```yaml # .gomarkdoc.yml output: "{{.Dir}}/README.md" format: github includeUnexported: false embed: true header: | [![Build Status](https://github.com/user/repo/workflows/CI/badge.svg)](https://github.com/user/repo/actions) footer: | Generated by [gomarkdoc](https://github.com/princjef/gomarkdoc) repository: url: https://github.com/user/repo defaultBranch: main path: / excludeDirs: - ./testdata/... - ./internal/... tags: - integration template: package: "# Custom {{.Name}}" templateFile: func: ./templates/func.gotxt ``` -------------------------------- ### Render Package Documentation to File Source: https://context7.com/princjef/gomarkdoc/llms.txt Renders a package's documentation to a markdown string and writes it to a file. ```go package main import ( "fmt" "go/build" "os" "github.com/princjef/gomarkdoc" "github.com/princjef/gomarkdoc/lang" "github.com/princjef/gomarkdoc/logger" ) func main() { log := logger.New(logger.WarnLevel) buildPkg, err := build.ImportDir(".", build.ImportComment) if err != nil { panic(err) } pkg, err := lang.NewPackageFromBuild(log, buildPkg) if err != nil { panic(err) } renderer, err := gomarkdoc.NewRenderer() if err != nil { panic(err) } // Render the entire package documentation markdown, err := renderer.Package(pkg) if err != nil { panic(err) } // Write to file if err := os.WriteFile("README.md", []byte(markdown), 0644); err != nil { panic(err) } fmt.Println("Documentation generated successfully") } ``` -------------------------------- ### Manage documentation configuration Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Defines the configuration structure and initialization for resolving documentation. ```go type Config struct { FileSet *token.FileSet Files []*ast.File Level int Repo *Repo PkgDir string WorkDir string Symbols map[string]Symbol Pkg *doc.Package Log logger.Logger } ``` ```go func NewConfig(log logger.Logger, workDir string, pkgDir string, opts ...ConfigOption) (*Config, error) ``` ```go func (c *Config) Inc(step int) *Config ``` -------------------------------- ### Lint and document the project Source: https://github.com/princjef/gomarkdoc/blob/master/CONTRIBUTING.md Run these commands to ensure code quality and regenerate project documentation. ```bash mage lint ``` ```bash mage doc ``` -------------------------------- ### Get Span URL Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Provides the URL associated with the span, if any. Returns a string. ```go func (s *Span) URL() string ``` -------------------------------- ### Get Span Text Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Provides the raw text for the span. Returns a string. ```go func (s *Span) Text() string ``` -------------------------------- ### EmbeddedFunc API Source: https://github.com/princjef/gomarkdoc/blob/master/testData/embed/README-github.md This section details the EmbeddedFunc function, which is part of the embedded documentation example. ```APIDOC ## func EmbeddedFunc(param int) int ### Description EmbeddedFunc is present in embedded content. ### Method N/A ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Generate Documentation to Stdout Source: https://context7.com/princjef/gomarkdoc/llms.txt Output documentation to the standard output stream for the current, specific, or remote packages. ```bash # Generate documentation for the current package gomarkdoc . # Generate documentation for a specific package gomarkdoc ./pkg/mypackage # Generate documentation for a remote package gomarkdoc encoding/json ``` -------------------------------- ### Get Span Kind Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Provides the kind of data that this span represents. Returns a SpanKind. ```go func (s *Span) Kind() SpanKind ``` -------------------------------- ### Create Documentation Block Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Constructs a new documentation block with specified kind, text spans, and inline status. Use this to programmatically create block elements for documentation. ```go func NewBlock(cfg *Config, kind BlockKind, spans []*Span, inline bool) *Block ``` -------------------------------- ### Import the embed package Source: https://github.com/princjef/gomarkdoc/blob/master/testData/embed/README-plain.md Import the package to access the embedded documentation functionality. ```go import "github.com/princjef/gomarkdoc/testData/embed" ``` -------------------------------- ### gomarkdoc Command Line Help Source: https://github.com/princjef/gomarkdoc/blob/master/README.md Display the help message for the gomarkdoc command-line tool, showing available flags and usage. ```bash $ gomarkdoc --help generate markdown documentation for golang code Usage: gomarkdoc [flags] [package ...] Flags: -c, --check Check the output to see if it matches the generated documentation. --output must be specified to use this. --config string File from which to load configuration (default: .gomarkdoc.yml) -e, --embed Embed documentation into existing markdown files if available, otherwise append to file. --exclude-dirs strings List of package directories to ignore when producing documentation. --footer string Additional content to inject at the end of each output file. --footer-file string File containing additional content to inject at the end of each output file. -f, --format string Format to use for writing output data. Valid options: github (default), azure-devops, plain (default "github") --header string Additional content to inject at the beginning of each output file. --header-file string File containing additional content to inject at the beginning of each output file. -h, --help help for gomarkdoc -u, --include-unexported Output documentation for unexported symbols, methods and fields in addition to exported ones. -o, --output string File or pattern specifying where to write documentation output. Defaults to printing to stdout. --repository.default-branch string Manual override for the git repository URL used in place of automatic detection. --repository.path string Manual override for the path from the root of the git repository used in place of automatic detection. --repository.url string Manual override for the git repository URL used in place of automatic detection. --tags strings Set of build tags to apply when choosing which files to include for documentation generation. -t, --template stringToString Custom template string to use for the provided template name instead of the default template. (default []) --template-file stringToString Custom template file to use for the provided template name instead of the default template. (default []) -v, --verbose count Log additional output from the execution of the command. Can be chained for additional verbosity. --version Print the version. ``` -------------------------------- ### Generate Package README with Gomarkdoc Output Option Source: https://github.com/princjef/gomarkdoc/blob/master/README.md Utilize the --output/-o option with a template to consistently redirect documentation for each package to a specific file, such as generating README.md for packages and their subpackages. ```bash gomarkdoc --output '{{.Dir}}/README.md' ./... ``` -------------------------------- ### Method to get AnotherStruct field Source: https://github.com/princjef/gomarkdoc/blob/master/testData/docs/README-github.md A Go method associated with a pointer to 'AnotherStruct' that returns the value of its 'Field' as a string. ```go func (s *AnotherStruct) GetField() string ``` -------------------------------- ### Import gomarkdoc package Source: https://github.com/princjef/gomarkdoc/blob/master/cmd/gomarkdoc/README.md Import the gomarkdoc command package to access its functionality. ```go import "github.com/princjef/gomarkdoc/cmd/gomarkdoc" ``` -------------------------------- ### Get Block Level Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Returns the rendering level for a HeaderBlock. This is primarily used for header blocks to determine their depth in the output. ```go func (b *Block) Level() int ``` -------------------------------- ### Import standard library package Source: https://github.com/princjef/gomarkdoc/blob/master/testData/docs/README-github.md Imports the 'docs' package from the test data. This is boilerplate for Go files. ```go import "github.com/princjef/gomarkdoc/testData/docs" ``` -------------------------------- ### Get List Contents from Block Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Retrieves the list contents for a block that is of type ListBlock. Returns nil if the block is not a list block. ```go func (b *Block) List() *List ``` -------------------------------- ### Generate Documentation to File Source: https://github.com/princjef/gomarkdoc/blob/master/README.md Use the gomarkdoc command to generate documentation for a package and save it to a markdown file. The '.' specifies the current directory as the package source. ```bash gomarkdoc --output doc.md . ``` -------------------------------- ### Get Spans from Block Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Retrieves the text spans that constitute the content of a documentation block. These spans represent individual pieces of text with potential formatting. ```go func (b *Block) Spans() []*Span ``` -------------------------------- ### Import simple package Source: https://github.com/princjef/gomarkdoc/blob/master/testData/simple/README-github.md Import the simple package to access its types and functions. ```go import "github.com/princjef/gomarkdoc/testData/simple" ``` -------------------------------- ### Escape Special Markdown Characters Source: https://github.com/princjef/gomarkdoc/blob/master/format/formatcore/README.md Escapes special characters in the provided text to ensure they are rendered literally in Markdown. URLs starting with a scheme are not escaped. ```go func Escape(text string) string ``` -------------------------------- ### Verify documentation Source: https://github.com/princjef/gomarkdoc/blob/master/README.md Use the -c flag to verify that the generated documentation matches the existing file content, typically for CI workflows. ```bash gomarkdoc -o README.md -c . ``` -------------------------------- ### Import gomarkdoc Package Source: https://github.com/princjef/gomarkdoc/blob/master/README.md Import the gomarkdoc package to use its functionality in your Go projects. ```go import "github.com/princjef/gomarkdoc" ``` -------------------------------- ### Verify Documentation Source: https://context7.com/princjef/gomarkdoc/llms.txt Check if existing documentation matches the generated output without modifying files. ```bash # Check that documentation matches generated output gomarkdoc -o README.md -c . ``` -------------------------------- ### Run project tests and coverage Source: https://github.com/princjef/gomarkdoc/blob/master/CONTRIBUTING.md Use these commands to validate changes, check test coverage, and generate a detailed HTML report. ```bash mage test ``` ```bash mage coverage ``` -------------------------------- ### Import Tags Package Source: https://github.com/princjef/gomarkdoc/blob/master/testData/tags/README-github.md Imports the necessary tags package for demonstrating build tag usage. ```go import "github.com/princjef/gomarkdoc/testData/tags" ``` -------------------------------- ### Generate Code Href (Go) Source: https://github.com/princjef/gomarkdoc/blob/master/format/README.md Always returns an empty string as standard markdown does not define a file linking format. ```go func (f *PlainMarkdown) CodeHref(loc lang.Location) (string, error) ``` -------------------------------- ### Verify development environment with Mage Source: https://github.com/princjef/gomarkdoc/blob/master/CONTRIBUTING.md Execute this command to ensure the development environment is correctly configured. ```bash mage test ``` -------------------------------- ### Access Package metadata Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Methods to retrieve directory, import, and naming information for the package. ```go func (pkg *Package) Dir() string ``` ```go func (pkg *Package) Dirname() string ``` ```go func (pkg *Package) Import() string ``` ```go func (pkg *Package) ImportPath() string ``` ```go func (pkg *Package) Name() string ``` ```go func (pkg *Package) Level() int ``` -------------------------------- ### Output Documentation to File Source: https://context7.com/princjef/gomarkdoc/llms.txt Write generated documentation to specific files or project-wide READMEs, with options to exclude directories. ```bash # Write documentation to a specific file gomarkdoc --output doc.md . # Generate README files for all packages in a project gomarkdoc --output '{{.Dir}}/README.md' ./... # Exclude test directories when generating docs gomarkdoc --exclude-dirs ./testData/... --output '{{.Dir}}/README.md' ./... ``` -------------------------------- ### NewRenderer Source: https://github.com/princjef/gomarkdoc/blob/master/README.md Initializes a new Renderer instance with optional configurations. ```APIDOC ## func NewRenderer ### Description Initializes a Renderer configured using the provided options. If no options are provided, it defaults to GitHubFlavoredMarkdown. ### Parameters #### Request Body - **opts** (...RendererOption) - Optional - A variadic list of configuration options for the renderer. ### Response #### Success Response (200) - **renderer** (*Renderer) - The initialized renderer instance. - **error** (error) - An error object if initialization fails. ``` -------------------------------- ### Import generic package Source: https://github.com/princjef/gomarkdoc/blob/master/testData/generics/README-azure-devops.md Import path for the generics test data package. ```go import "github.com/princjef/gomarkdoc/testData/generics" ``` -------------------------------- ### Repository Configuration Source: https://context7.com/princjef/gomarkdoc/llms.txt Manually configure repository details for source code links. ```bash # Specify all repository details gomarkdoc \ --repository.url "https://github.com/user/repo" \ --repository.default-branch main \ --repository.path / \ -o README.md . ``` -------------------------------- ### Verbose Output Source: https://context7.com/princjef/gomarkdoc/llms.txt Enable logging levels for debugging documentation generation. ```bash # Info level logging gomarkdoc -v -o README.md . # Debug level logging gomarkdoc -vv -o README.md . ``` -------------------------------- ### Create List Block Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Creates a new documentation block representing a list. This function is used when the block content is a list with a given definition. ```go func NewListBlock(cfg *Config, list *List, inline bool) *Block ``` -------------------------------- ### Configure repository metadata Source: https://github.com/princjef/gomarkdoc/blob/master/README.md Manually specify repository details to ensure consistent documentation generation. ```bash gomarkdoc --repository.url "https://github.com/princjef/gomarkdoc" --repository.default-branch master --repository.path / -o README.md . ``` -------------------------------- ### Access Package documentation content Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Methods to retrieve structured documentation comments and summaries. ```go func (pkg *Package) Doc() *Doc ``` ```go func (pkg *Package) Summary() string ``` -------------------------------- ### Generate an anchor Source: https://github.com/princjef/gomarkdoc/blob/master/format/README.md Produces an anchor string for linking. ```go func (f *AzureDevOpsMarkdown) Anchor(anchor string) string ``` -------------------------------- ### Embed documentation in existing files Source: https://github.com/princjef/gomarkdoc/blob/master/README.md Use the -e flag to append or embed generated documentation into an existing file. ```bash gomarkdoc -o README.md -e . ``` -------------------------------- ### Create Package with Repository Overrides Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Creates a PackageOption that allows defining manual overrides for automatic repository detection logic when creating a package. This is used with NewPackageFromBuild. ```go func PackageWithRepositoryOverrides(repo *Repo) PackageOption ``` -------------------------------- ### Build Tags Source: https://context7.com/princjef/gomarkdoc/llms.txt Include files requiring specific build tags during documentation generation. ```bash # Generate documentation including files with 'integration' build tag gomarkdoc --tags integration . # Multiple tags gomarkdoc --tags integration,linux . ``` -------------------------------- ### Config.Inc Method Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Creates a copy of the Config and increments its level by a specified step. ```APIDOC ## (*Config) Inc Method ### Description Inc copies the Config and increments the level by the provided step. ### Parameters - **step** (int) - The amount to increment the level by. ### Returns - **(*Config)** - A new Config object with the updated level. ``` -------------------------------- ### Configure Markdown Format Source: https://context7.com/princjef/gomarkdoc/llms.txt Specify the target markdown platform format for the generated output. ```bash # Use GitHub Flavored Markdown (default) gomarkdoc --format github --output README.md . # Use Azure DevOps compatible markdown gomarkdoc --format azure-devops --output README.md . # Use plain markdown without platform-specific features gomarkdoc --format plain --output README.md . ``` -------------------------------- ### Define block types Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Enumerates the supported types of documentation block elements. ```go type BlockKind string ``` ```go const ( // ParagraphBlock defines a block that represents a paragraph of text. ParagraphBlock BlockKind = "paragraph" // CodeBlock defines a block that represents a section of code. CodeBlock BlockKind = "code" // HeaderBlock defines a block that represents a section header. HeaderBlock BlockKind = "header" // ListBlock defines a block that represents an ordered or unordered list. ListBlock BlockKind = "list" ) ``` -------------------------------- ### Import logger package Source: https://github.com/princjef/gomarkdoc/blob/master/logger/README.md Import the logger package to use its functionalities. ```go import "github.com/princjef/gomarkdoc/logger" ``` -------------------------------- ### PlainMarkdown.ListEntry Source: https://github.com/princjef/gomarkdoc/blob/master/format/README.md Generates an unordered list entry at a specified depth. ```APIDOC ## ListEntry ### Description ListEntry generates an unordered list entry with the provided text at the provided zero-indexed depth. A depth of 0 is considered the topmost level of list. ### Method func (*PlainMarkdown) ListEntry(depth int, text string) (string, error) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **string** - The markdown list entry string. - **error** - An error if the list entry cannot be generated. #### Response Example None ``` -------------------------------- ### NewConfig Function Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Initializes a new Config struct for a given package directory, attempting to resolve repository information. ```APIDOC ## func NewConfig ### Description NewConfig generates a Config for the provided package directory. It will resolve the filepath and attempt to determine the repository containing the directory. If no repository is found, the Repo field will be set to nil. An error is returned if the provided directory is invalid. ### Parameters - **log** (logger.Logger) - The logger to use. - **workDir** (string) - The working directory. - **pkgDir** (string) - The directory path of the package. - **opts** (...ConfigOption) - Optional configuration options. ### Returns - **(*Config, error)** - A pointer to the created Config object and an error if any occurred. ``` -------------------------------- ### Initialize generic struct Source: https://github.com/princjef/gomarkdoc/blob/master/testData/generics/README-azure-devops.md Constructor function for creating a new Generic instance. ```go func NewGeneric[T any](param T) Generic[T] ``` -------------------------------- ### Include build tags Source: https://github.com/princjef/gomarkdoc/blob/master/README.md Specify build tags to include files that are part of a specific build configuration. ```bash gomarkdoc --tags sometag . ``` -------------------------------- ### Define Package struct Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Represents the documentation information for a package and its symbols. ```go type Package struct { // contains filtered or unexported fields } ``` -------------------------------- ### Renderer Methods Source: https://github.com/princjef/gomarkdoc/blob/master/README.md Methods available on the Renderer instance to generate documentation strings for different Go language constructs. ```APIDOC ## Renderer Methods ### Description These methods render specific Go language constructs into documentation strings. ### Methods - **Example(ex *lang.Example)**: Renders an example's documentation. - **File(file *lang.File)**: Renders a file containing one or more packages. - **Func(fn *lang.Func)**: Renders a function's documentation. - **Package(pkg *lang.Package)**: Renders a package's documentation. - **Type(typ *lang.Type)**: Renders a type's documentation. ### Response - **string**: The rendered documentation string. - **error**: An error object if rendering fails. ``` -------------------------------- ### Repository Information Structure Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Represents information about a repository relevant to documentation generation. Includes Remote, DefaultBranch, and PathFromRoot. ```go type Repo struct { Remote string DefaultBranch string PathFromRoot string } ``` -------------------------------- ### Package Options Structure Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Holds options related to the configuration of a package and its documentation during creation. The fields are filtered or unexported. ```go type PackageOptions struct { // contains filtered or unexported fields } ``` -------------------------------- ### Config Documentation Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Functions and types related to configuration for Gomarkdoc. ```APIDOC ## Config Documentation ### Description Provides functions and types for configuring Gomarkdoc. ### Types #### `type Config` - **Description**: Configuration for Gomarkdoc. ##### Methods - **`NewConfig(log logger.Logger, workDir string, pkgDir string, opts ...ConfigOption) (*Config, error)`** - **Description**: Creates a new Config. - **`(*Config) Inc(step int) *Config`** - **Description**: Increments the configuration step. #### `type ConfigOption` - **Description**: Option for configuring Gomarkdoc. ##### Functions - **`ConfigWithRepoOverrides(overrides *Repo) ConfigOption`** - **Description**: Creates a ConfigOption with repository overrides. ``` -------------------------------- ### Format Text as Plain Text Source: https://github.com/princjef/gomarkdoc/blob/master/format/formatcore/README.md Returns the provided text as is, without applying any Markdown formatting. This can be used to ensure text is treated literally. ```go func PlainText(text string) string ``` -------------------------------- ### Handle documentation content Source: https://github.com/princjef/gomarkdoc/blob/master/lang/README.md Provides structures and methods for accessing structured documentation comments. ```go type Doc struct { // contains filtered or unexported fields } ``` ```go func NewDoc(cfg *Config, text string) *Doc ``` ```go func (d *Doc) Blocks() []*Block ``` ```go func (d *Doc) Level() int ``` -------------------------------- ### Generate Link Source: https://github.com/princjef/gomarkdoc/blob/master/format/README.md Generates a markdown link with the given text and href. ```go func (f *GitHubFlavoredMarkdown) Link(text, href string) (string, error) ```