...

Package modfile

import "golang.org/x/mod/modfile"
Overview
Index

Overview ▾

Package modfile implements a parser and formatter for go.mod files.

The go.mod syntax is described in https://golang.org/cmd/go/#hdr-The_go_mod_file.

The Parse and ParseLax functions both parse a go.mod file and return an abstract syntax tree. ParseLax ignores unknown statements and may be used to parse go.mod files that may have been developed with newer versions of Go.

The File struct returned by Parse and ParseLax represent an abstract go.mod file. File has several methods like AddNewRequire and DropReplace that can be used to programmatically edit a file.

The Format function formats a File back to a byte slice which can be written to a file.

Index ▾

Variables
func AutoQuote(s string) string
func Format(f *FileSyntax) []byte
func IsDirectoryPath(ns string) bool
func ModulePath(mod []byte) string
func MustQuote(s string) bool
type Comment
type CommentBlock
    func (x *CommentBlock) Span() (start, end Position)
type Comments
    func (c *Comments) Comment() *Comments
type Error
    func (e *Error) Error() string
    func (e *Error) Unwrap() error
type ErrorList
    func (e ErrorList) Error() string
type Exclude
type Expr
type File
    func Parse(file string, data []byte, fix VersionFixer) (*File, error)
    func ParseLax(file string, data []byte, fix VersionFixer) (*File, error)
    func (f *File) AddComment(text string)
    func (f *File) AddExclude(path, vers string) error
    func (f *File) AddGoStmt(version string) error
    func (f *File) AddModuleStmt(path string) error
    func (f *File) AddNewRequire(path, vers string, indirect bool)
    func (f *File) AddReplace(oldPath, oldVers, newPath, newVers string) error
    func (f *File) AddRequire(path, vers string) error
    func (f *File) AddRetract(vi VersionInterval, rationale string) error
    func (f *File) Cleanup()
    func (f *File) DropExclude(path, vers string) error
    func (f *File) DropReplace(oldPath, oldVers string) error
    func (f *File) DropRequire(path string) error
    func (f *File) DropRetract(vi VersionInterval) error
    func (f *File) Format() ([]byte, error)
    func (f *File) SetRequire(req []*Require)
    func (f *File) SetRequireSeparateIndirect(req []*Require)
    func (f *File) SortBlocks()
type FileSyntax
    func (x *FileSyntax) Cleanup()
    func (x *FileSyntax) Span() (start, end Position)
type Go
type LParen
    func (x *LParen) Span() (start, end Position)
type Line
    func (x *Line) Span() (start, end Position)
type LineBlock
    func (x *LineBlock) Span() (start, end Position)
type Module
type Position
type RParen
    func (x *RParen) Span() (start, end Position)
type Replace
type Require
type Retract
type Use
type VersionFixer
type VersionInterval
type WorkFile
    func ParseWork(file string, data []byte, fix VersionFixer) (*WorkFile, error)
    func (f *WorkFile) AddGoStmt(version string) error
    func (f *WorkFile) AddNewUse(diskPath, modulePath string)
    func (f *WorkFile) AddReplace(oldPath, oldVers, newPath, newVers string) error
    func (f *WorkFile) AddUse(diskPath, modulePath string) error
    func (f *WorkFile) Cleanup()
    func (f *WorkFile) DropReplace(oldPath, oldVers string) error
    func (f *WorkFile) DropUse(path string) error
    func (f *WorkFile) SetUse(dirs []*Use)
    func (f *WorkFile) SortBlocks()

Package files

print.go read.go rule.go work.go

Variables

var GoVersionRE = lazyregexp.New(`^([1-9][0-9]*)\.(0|[1-9][0-9]*)$`)

func AutoQuote

func AutoQuote(s string) string

AutoQuote returns s or, if quoting is required for s to appear in a go.mod, the quotation of s.

func Format

func Format(f *FileSyntax) []byte

Format returns a go.mod file as a byte slice, formatted in standard style.

func IsDirectoryPath

func IsDirectoryPath(ns string) bool

IsDirectoryPath reports whether the given path should be interpreted as a directory path. Just like on the go command line, relative paths and rooted paths are directory paths; the rest are module paths.

func ModulePath

func ModulePath(mod []byte) string

ModulePath returns the module path from the gomod file text. If it cannot find a module path, it returns an empty string. It is tolerant of unrelated problems in the go.mod file.

func MustQuote

func MustQuote(s string) bool

MustQuote reports whether s must be quoted in order to appear as a single token in a go.mod line.

type Comment

A Comment represents a single // comment.

type Comment struct {
    Start  Position
    Token  string // without trailing newline
    Suffix bool   // an end of line (not whole line) comment
}

type CommentBlock

A CommentBlock represents a top-level block of comments separate from any rule.

type CommentBlock struct {
    Comments
    Start Position
}

func (*CommentBlock) Span

func (x *CommentBlock) Span() (start, end Position)

type Comments

Comments collects the comments associated with an expression.

type Comments struct {
    Before []Comment // whole-line comments before this expression
    Suffix []Comment // end-of-line comments after this expression

    // For top-level expressions only, After lists whole-line
    // comments following the expression.
    After []Comment
}

func (*Comments) Comment

func (c *Comments) Comment() *Comments

Comment returns the receiver. This isn't useful by itself, but a Comments struct is embedded into all the expression implementation types, and this gives each of those a Comment method to satisfy the Expr interface.

type Error

type Error struct {
    Filename string
    Pos      Position
    Verb     string
    ModPath  string
    Err      error
}

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorList

type ErrorList []Error

func (ErrorList) Error

func (e ErrorList) Error() string

type Exclude

An Exclude is a single exclude statement.

type Exclude struct {
    Mod    module.Version
    Syntax *Line
}

type Expr

An Expr represents an input element.

type Expr interface {
    // Span returns the start and end position of the expression,
    // excluding leading or trailing comments.
    Span() (start, end Position)

    // Comment returns the comments attached to the expression.
    // This method would normally be named 'Comments' but that
    // would interfere with embedding a type of the same name.
    Comment() *Comments
}

type File

A File is the parsed, interpreted form of a go.mod file.

type File struct {
    Module  *Module
    Go      *Go
    Require []*Require
    Exclude []*Exclude
    Replace []*Replace
    Retract []*Retract

    Syntax *FileSyntax
}

func Parse

func Parse(file string, data []byte, fix VersionFixer) (*File, error)

Parse parses and returns a go.mod file.

file is the name of the file, used in positions and errors.

data is the content of the file.

fix is an optional function that canonicalizes module versions. If fix is nil, all module versions must be canonical (module.CanonicalVersion must return the same string).

func ParseLax

func ParseLax(file string, data []byte, fix VersionFixer) (*File, error)

ParseLax is like Parse but ignores unknown statements. It is used when parsing go.mod files other than the main module, under the theory that most statement types we add in the future will only apply in the main module, like exclude and replace, and so we get better gradual deployments if old go commands simply ignore those statements when found in go.mod files in dependencies.

func (*File) AddComment

func (f *File) AddComment(text string)

func (*File) AddExclude

func (f *File) AddExclude(path, vers string) error

AddExclude adds a exclude statement to the mod file. Errors if the provided version is not a canonical version string

func (*File) AddGoStmt

func (f *File) AddGoStmt(version string) error

func (*File) AddModuleStmt

func (f *File) AddModuleStmt(path string) error

func (*File) AddNewRequire

func (f *File) AddNewRequire(path, vers string, indirect bool)

AddNewRequire adds a new require line for path at version vers at the end of the last require block, regardless of any existing require lines for path.

func (*File) AddReplace

func (f *File) AddReplace(oldPath, oldVers, newPath, newVers string) error

func (*File) AddRequire

func (f *File) AddRequire(path, vers string) error

AddRequire sets the first require line for path to version vers, preserving any existing comments for that line and removing all other lines for path.

If no line currently exists for path, AddRequire adds a new line at the end of the last require block.

func (*File) AddRetract

func (f *File) AddRetract(vi VersionInterval, rationale string) error

AddRetract adds a retract statement to the mod file. Errors if the provided version interval does not consist of canonical version strings

func (*File) Cleanup

func (f *File) Cleanup()

Cleanup cleans up the file f after any edit operations. To avoid quadratic behavior, modifications like DropRequire clear the entry but do not remove it from the slice. Cleanup cleans out all the cleared entries.

func (*File) DropExclude

func (f *File) DropExclude(path, vers string) error

func (*File) DropReplace

func (f *File) DropReplace(oldPath, oldVers string) error

func (*File) DropRequire

func (f *File) DropRequire(path string) error

func (*File) DropRetract

func (f *File) DropRetract(vi VersionInterval) error

func (*File) Format

func (f *File) Format() ([]byte, error)

func (*File) SetRequire

func (f *File) SetRequire(req []*Require)

SetRequire updates the requirements of f to contain exactly req, preserving the existing block structure and line comment contents (except for 'indirect' markings) for the first requirement on each named module path.

The Syntax field is ignored for the requirements in req.

Any requirements not already present in the file are added to the block containing the last require line.

The requirements in req must specify at most one distinct version for each module path.

If any existing requirements may be removed, the caller should call Cleanup after all edits are complete.

func (*File) SetRequireSeparateIndirect

func (f *File) SetRequireSeparateIndirect(req []*Require)

SetRequireSeparateIndirect updates the requirements of f to contain the given requirements. Comment contents (except for 'indirect' markings) are retained from the first existing requirement for each module path. Like SetRequire, SetRequireSeparateIndirect adds requirements for new paths in req, updates the version and "// indirect" comment on existing requirements, and deletes requirements on paths not in req. Existing duplicate requirements are deleted.

As its name suggests, SetRequireSeparateIndirect puts direct and indirect requirements into two separate blocks, one containing only direct requirements, and the other containing only indirect requirements. SetRequireSeparateIndirect may move requirements between these two blocks when their indirect markings change. However, SetRequireSeparateIndirect won't move requirements from other blocks, especially blocks with comments.

If the file initially has one uncommented block of requirements, SetRequireSeparateIndirect will split it into a direct-only and indirect-only block. This aids in the transition to separate blocks.

func (*File) SortBlocks

func (f *File) SortBlocks()

type FileSyntax

A FileSyntax represents an entire go.mod file.

type FileSyntax struct {
    Name string // file path
    Comments
    Stmt []Expr
}

func (*FileSyntax) Cleanup

func (x *FileSyntax) Cleanup()

Cleanup cleans up the file syntax x after any edit operations. To avoid quadratic behavior, (*Line).markRemoved marks the line as dead by setting line.Token = nil but does not remove it from the slice in which it appears. After edits have all been indicated, calling Cleanup cleans out the dead lines.

func (*FileSyntax) Span

func (x *FileSyntax) Span() (start, end Position)

type Go

A Go is the go statement.

type Go struct {
    Version string // "1.23"
    Syntax  *Line
}

type LParen

An LParen represents the beginning of a parenthesized line block. It is a place to store suffix comments.

type LParen struct {
    Comments
    Pos Position
}

func (*LParen) Span

func (x *LParen) Span() (start, end Position)

type Line

A Line is a single line of tokens.

type Line struct {
    Comments
    Start   Position
    Token   []string
    InBlock bool
    End     Position
}

func (*Line) Span

func (x *Line) Span() (start, end Position)

type LineBlock

A LineBlock is a factored block of lines, like

require (
	"x"
	"y"
)
type LineBlock struct {
    Comments
    Start  Position
    LParen LParen
    Token  []string
    Line   []*Line
    RParen RParen
}

func (*LineBlock) Span

func (x *LineBlock) Span() (start, end Position)

type Module

A Module is the module statement.

type Module struct {
    Mod        module.Version
    Deprecated string
    Syntax     *Line
}

type Position

A Position describes an arbitrary source position in a file, including the file, line, column, and byte offset.

type Position struct {
    Line     int // line in input (starting at 1)
    LineRune int // rune in line (starting at 1)
    Byte     int // byte in input (starting at 0)
}

type RParen

An RParen represents the end of a parenthesized line block. It is a place to store whole-line (before) comments.

type RParen struct {
    Comments
    Pos Position
}

func (*RParen) Span

func (x *RParen) Span() (start, end Position)

type Replace

A Replace is a single replace statement.

type Replace struct {
    Old    module.Version
    New    module.Version
    Syntax *Line
}

type Require

A Require is a single require statement.

type Require struct {
    Mod      module.Version
    Indirect bool // has "// indirect" comment
    Syntax   *Line
}

type Retract

A Retract is a single retract statement.

type Retract struct {
    VersionInterval
    Rationale string
    Syntax    *Line
}

type Use

A Use is a single directory statement.

type Use struct {
    Path       string // Use path of module.
    ModulePath string // Module path in the comment.
    Syntax     *Line
}

type VersionFixer

type VersionFixer func(path, version string) (string, error)

type VersionInterval

A VersionInterval represents a range of versions with upper and lower bounds. Intervals are closed: both bounds are included. When Low is equal to High, the interval may refer to a single version ('v1.2.3') or an interval ('[v1.2.3, v1.2.3]'); both have the same representation.

type VersionInterval struct {
    Low, High string
}

type WorkFile

A WorkFile is the parsed, interpreted form of a go.work file.

type WorkFile struct {
    Go      *Go
    Use     []*Use
    Replace []*Replace

    Syntax *FileSyntax
}

func ParseWork

func ParseWork(file string, data []byte, fix VersionFixer) (*WorkFile, error)

ParseWork parses and returns a go.work file.

file is the name of the file, used in positions and errors.

data is the content of the file.

fix is an optional function that canonicalizes module versions. If fix is nil, all module versions must be canonical (module.CanonicalVersion must return the same string).

func (*WorkFile) AddGoStmt

func (f *WorkFile) AddGoStmt(version string) error

func (*WorkFile) AddNewUse

func (f *WorkFile) AddNewUse(diskPath, modulePath string)

func (*WorkFile) AddReplace

func (f *WorkFile) AddReplace(oldPath, oldVers, newPath, newVers string) error

func (*WorkFile) AddUse

func (f *WorkFile) AddUse(diskPath, modulePath string) error

func (*WorkFile) Cleanup

func (f *WorkFile) Cleanup()

Cleanup cleans up the file f after any edit operations. To avoid quadratic behavior, modifications like DropRequire clear the entry but do not remove it from the slice. Cleanup cleans out all the cleared entries.

func (*WorkFile) DropReplace

func (f *WorkFile) DropReplace(oldPath, oldVers string) error

func (*WorkFile) DropUse

func (f *WorkFile) DropUse(path string) error

func (*WorkFile) SetUse

func (f *WorkFile) SetUse(dirs []*Use)

func (*WorkFile) SortBlocks

func (f *WorkFile) SortBlocks()