// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package modfile implements a parser and formatter for go.mod files. // // The go.mod syntax is described in // https://pkg.go.dev/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 [File.AddNewRequire] and // [File.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.
package modfile import ( ) // A File is the parsed, interpreted form of a go.mod file. type File struct { Module *Module Go *Go Toolchain *Toolchain Godebug []*Godebug Require []*Require Exclude []*Exclude Replace []*Replace Retract []*Retract Tool []*Tool Ignore []*Ignore Syntax *FileSyntax } // A Module is the module statement. type Module struct { Mod module.Version Deprecated string Syntax *Line } // A Go is the go statement. type Go struct { Version string // "1.23" Syntax *Line } // A Toolchain is the toolchain statement. type Toolchain struct { Name string // "go1.21rc1" Syntax *Line } // A Godebug is a single godebug key=value statement. type Godebug struct { Key string Value string Syntax *Line } // An Exclude is a single exclude statement. type Exclude struct { Mod module.Version Syntax *Line } // A Replace is a single replace statement. type Replace struct { Old module.Version New module.Version Syntax *Line } // A Retract is a single retract statement. type Retract struct { VersionInterval Rationale string Syntax *Line } // A Tool is a single tool statement. type Tool struct { Path string Syntax *Line } // An Ignore is a single ignore statement. type Ignore struct { Path string Syntax *Line } // 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 } // A Require is a single require statement. type Require struct { Mod module.Version Indirect bool // has "// indirect" comment Syntax *Line } func ( *Require) () { .Syntax.markRemoved() * = Require{} } func ( *Require) ( string) { .Mod.Version = if := .Syntax; len(.Token) > 0 { if .InBlock { // If the line is preceded by an empty line, remove it; see // https://golang.org/issue/33779. if len(.Comments.Before) == 1 && len(.Comments.Before[0].Token) == 0 { .Comments.Before = .Comments.Before[:0] } if len(.Token) >= 2 { // example.com v1.2.3 .Token[1] = } } else { if len(.Token) >= 3 { // require example.com v1.2.3 .Token[2] = } } } } // setIndirect sets line to have (or not have) a "// indirect" comment. func ( *Require) ( bool) { .Indirect = := .Syntax if isIndirect() == { return } if { // Adding comment. if len(.Suffix) == 0 { // New comment. .Suffix = []Comment{{Token: "// indirect", Suffix: true}} return } := &.Suffix[0] := strings.TrimSpace(strings.TrimPrefix(.Token, string(slashSlash))) if == "" { // Empty comment. .Token = "// indirect" return } // Insert at beginning of existing comment. .Token = "// indirect; " + return } // Removing comment. := strings.TrimSpace(strings.TrimPrefix(.Suffix[0].Token, string(slashSlash))) if == "indirect" { // Remove whole comment. .Suffix = nil return } // Remove comment prefix. := &.Suffix[0] := strings.Index(.Token, "indirect;") .Token = "//" + .Token[+len("indirect;"):] } // isIndirect reports whether line has a "// indirect" comment, // meaning it is in go.mod only for its effect on indirect dependencies, // so that it can be dropped entirely once the effective version of the // indirect dependency reaches the given minimum version. func ( *Line) bool { if len(.Suffix) == 0 { return false } := strings.Fields(strings.TrimPrefix(.Suffix[0].Token, string(slashSlash))) return (len() == 1 && [0] == "indirect" || len() > 1 && [0] == "indirect;") } func ( *File) ( string) error { if .Syntax == nil { .Syntax = new(FileSyntax) } if .Module == nil { .Module = &Module{ Mod: module.Version{Path: }, Syntax: .Syntax.addLine(nil, "module", AutoQuote()), } } else { .Module.Mod.Path = .Syntax.updateLine(.Module.Syntax, "module", AutoQuote()) } return nil } func ( *File) ( string) { if .Syntax == nil { .Syntax = new(FileSyntax) } .Syntax.Stmt = append(.Syntax.Stmt, &CommentBlock{ Comments: Comments{ Before: []Comment{ { Token: , }, }, }, }) } type VersionFixer func(path, version string) (string, error) // errDontFix is returned by a VersionFixer to indicate the version should be // left alone, even if it's not canonical. var dontFixRetract VersionFixer = func(, string) (string, error) { return , nil } // 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 ( string, []byte, VersionFixer) (*File, error) { return parseToFile(, , , true) } // 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 ( string, []byte, VersionFixer) (*File, error) { return parseToFile(, , , false) } func ( string, []byte, VersionFixer, bool) ( *File, error) { , := parse(, ) if != nil { return nil, } := &File{ Syntax: , } var ErrorList // fix versions in retract directives after the file is parsed. // We need the module path to fix versions, and it might be at the end. defer func() { := len() .fixRetract(, &) if len() > { , = nil, } }() for , := range .Stmt { switch x := .(type) { case *Line: .add(&, nil, , .Token[0], .Token[1:], , ) case *LineBlock: if len(.Token) > 1 { if { = append(, Error{ Filename: , Pos: .Start, Err: fmt.Errorf("unknown block type: %s", strings.Join(.Token, " ")), }) } continue } switch .Token[0] { default: if { = append(, Error{ Filename: , Pos: .Start, Err: fmt.Errorf("unknown block type: %s", strings.Join(.Token, " ")), }) } continue case "module", "godebug", "require", "exclude", "replace", "retract", "tool", "ignore": for , := range .Line { .add(&, , , .Token[0], .Token, , ) } } } } if len() > 0 { return nil, } return , nil } var GoVersionRE = lazyregexp.New(`^([1-9][0-9]*)\.(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))?([a-z]+[0-9]+)?$`) var laxGoVersionRE = lazyregexp.New(`^v?(([1-9][0-9]*)\.(0|[1-9][0-9]*))([^0-9].*)$`) // Toolchains must be named beginning with `go1`, // like "go1.20.3" or "go1.20.3-gccgo". As a special case, "default" is also permitted. // Note that this regexp is a much looser condition than go/version.IsValid, // for forward compatibility. // (This code has to be work to identify new toolchains even if we tweak the syntax in the future.) var ToolchainRE = lazyregexp.New(`^default$|^go1($|\.)`) func ( *File) ( *ErrorList, *LineBlock, *Line, string, []string, VersionFixer, bool) { // If strict is false, this module is a dependency. // We ignore all unknown directives as well as main-module-only // directives like replace and exclude. It will work better for // forward compatibility if we can depend on modules that have unknown // statements (presumed relevant only when acting as the main module) // and simply ignore those statements. if ! { switch { case "go", "module", "retract", "require", "ignore": // want these even for dependency go.mods default: return } } := func( string, error) { * = append(*, Error{ Filename: .Syntax.Name, Pos: .Start, ModPath: , Verb: , Err: , }) } := func( error) { * = append(*, Error{ Filename: .Syntax.Name, Pos: .Start, Err: , }) } := func( string, ...any) { (fmt.Errorf(, ...)) } switch { default: ("unknown directive: %s", ) case "go": if .Go != nil { ("repeated go statement") return } if len() != 1 { ("go directive expects exactly one argument") return } else if !GoVersionRE.MatchString([0]) { := false if ! { if := laxGoVersionRE.FindStringSubmatch([0]); != nil { [0] = [1] = true } } if ! { ("invalid go version '%s': must match format 1.23.0", [0]) return } } .Go = &Go{Syntax: } .Go.Version = [0] case "toolchain": if .Toolchain != nil { ("repeated toolchain statement") return } if len() != 1 { ("toolchain directive expects exactly one argument") return } else if !ToolchainRE.MatchString([0]) { ("invalid toolchain version '%s': must match format go1.23.0 or default", [0]) return } .Toolchain = &Toolchain{Syntax: } .Toolchain.Name = [0] case "module": if .Module != nil { ("repeated module statement") return } := parseDeprecation(, ) .Module = &Module{ Syntax: , Deprecated: , } if len() != 1 { ("usage: module module/path") return } , := parseString(&[0]) if != nil { ("invalid quoted string: %v", ) return } .Module.Mod = module.Version{Path: } case "godebug": if len() != 1 || strings.ContainsAny([0], "\"`',") { ("usage: godebug key=value") return } , , := strings.Cut([0], "=") if ! { ("usage: godebug key=value") return } .Godebug = append(.Godebug, &Godebug{ Key: , Value: , Syntax: , }) case "require", "exclude": if len() != 2 { ("usage: %s module/path v1.2.3", ) return } , := parseString(&[0]) if != nil { ("invalid quoted string: %v", ) return } , := parseVersion(, , &[1], ) if != nil { () return } , := modulePathMajor() if != nil { () return } if := module.CheckPathMajor(, ); != nil { (, ) return } if == "require" { .Require = append(.Require, &Require{ Mod: module.Version{Path: , Version: }, Syntax: , Indirect: isIndirect(), }) } else { .Exclude = append(.Exclude, &Exclude{ Mod: module.Version{Path: , Version: }, Syntax: , }) } case "replace": , := parseReplace(.Syntax.Name, , , , ) if != nil { * = append(*, *) return } .Replace = append(.Replace, ) case "retract": := parseDirectiveComment(, ) , := parseVersionInterval(, "", &, dontFixRetract) if != nil { if { () return } else { // Only report errors parsing intervals in the main module. We may // support additional syntax in the future, such as open and half-open // intervals. Those can't be supported now, because they break the // go.mod parser, even in lax mode. return } } if len() > 0 && { // In the future, there may be additional information after the version. ("unexpected token after version: %q", [0]) return } := &Retract{ VersionInterval: , Rationale: , Syntax: , } .Retract = append(.Retract, ) case "tool": if len() != 1 { ("tool directive expects exactly one argument") return } , := parseString(&[0]) if != nil { ("invalid quoted string: %v", ) return } .Tool = append(.Tool, &Tool{ Path: , Syntax: , }) case "ignore": if len() != 1 { ("ignore directive expects exactly one argument") return } , := parseString(&[0]) if != nil { ("invalid quoted string: %v", ) return } .Ignore = append(.Ignore, &Ignore{ Path: , Syntax: , }) } } func ( string, *Line, string, []string, VersionFixer) (*Replace, *Error) { := func( string, error) *Error { return &Error{ Filename: , Pos: .Start, ModPath: , Verb: , Err: , } } := func( error) *Error { return &Error{ Filename: , Pos: .Start, Err: , } } := func( string, ...any) *Error { return (fmt.Errorf(, ...)) } := 2 if len() >= 2 && [1] == "=>" { = 1 } if len() < +2 || len() > +3 || [] != "=>" { return nil, ("usage: %s module/path [v1.2.3] => other/module v1.4\n\t or %s module/path [v1.2.3] => ../local/directory", , ) } , := parseString(&[0]) if != nil { return nil, ("invalid quoted string: %v", ) } , := modulePathMajor() if != nil { return nil, (, ) } var string if == 2 { , = parseVersion(, , &[1], ) if != nil { return nil, () } if := module.CheckPathMajor(, ); != nil { return nil, (, ) } } , := parseString(&[+1]) if != nil { return nil, ("invalid quoted string: %v", ) } := "" if len() == +2 { if !IsDirectoryPath() { if strings.Contains(, "@") { return nil, ("replacement module must match format 'path version', not 'path@version'") } return nil, ("replacement module without version must be directory path (rooted or starting with . or ..)") } if filepath.Separator == '/' && strings.Contains(, `\`) { return nil, ("replacement directory appears to be Windows path (on a non-windows system)") } } if len() == +3 { , = parseVersion(, , &[+2], ) if != nil { return nil, () } if IsDirectoryPath() { return nil, ("replacement module directory path %q cannot have version", ) } } return &Replace{ Old: module.Version{Path: , Version: }, New: module.Version{Path: , Version: }, Syntax: , }, nil } // fixRetract applies fix to each retract directive in f, appending any errors // to errs. // // Most versions are fixed as we parse the file, but for retract directives, // the relevant module path is the one specified with the module directive, // and that might appear at the end of the file (or not at all). func ( *File) ( VersionFixer, *ErrorList) { if == nil { return } := "" if .Module != nil { = .Module.Mod.Path } var *Retract := func( error) { * = append(*, Error{ Filename: .Syntax.Name, Pos: .Syntax.Start, Err: , }) } for _, = range .Retract { if == "" { (errors.New("no module directive found, so retract cannot be used")) return // only print the first one of these } := .Syntax.Token if [0] == "retract" { = [1:] } , := parseVersionInterval("retract", , &, ) if != nil { () } .VersionInterval = } } func ( *WorkFile) ( *ErrorList, *Line, string, []string, VersionFixer) { := func( error) { * = append(*, Error{ Filename: .Syntax.Name, Pos: .Start, Err: , }) } := func( string, ...any) { (fmt.Errorf(, ...)) } switch { default: ("unknown directive: %s", ) case "go": if .Go != nil { ("repeated go statement") return } if len() != 1 { ("go directive expects exactly one argument") return } else if !GoVersionRE.MatchString([0]) { ("invalid go version '%s': must match format 1.23.0", [0]) return } .Go = &Go{Syntax: } .Go.Version = [0] case "toolchain": if .Toolchain != nil { ("repeated toolchain statement") return } if len() != 1 { ("toolchain directive expects exactly one argument") return } else if !ToolchainRE.MatchString([0]) { ("invalid toolchain version '%s': must match format go1.23.0 or default", [0]) return } .Toolchain = &Toolchain{Syntax: } .Toolchain.Name = [0] case "godebug": if len() != 1 || strings.ContainsAny([0], "\"`',") { ("usage: godebug key=value") return } , , := strings.Cut([0], "=") if ! { ("usage: godebug key=value") return } .Godebug = append(.Godebug, &Godebug{ Key: , Value: , Syntax: , }) case "use": if len() != 1 { ("usage: %s local/dir", ) return } , := parseString(&[0]) if != nil { ("invalid quoted string: %v", ) return } .Use = append(.Use, &Use{ Path: , Syntax: , }) case "replace": , := parseReplace(.Syntax.Name, , , , ) if != nil { * = append(*, *) return } .Replace = append(.Replace, ) } } // IsDirectoryPath reports whether the given path should be interpreted as a directory path. // Just like on the go command line, relative paths starting with a '.' or '..' path component // and rooted paths are directory paths; the rest are module paths. func ( string) bool { // Because go.mod files can move from one system to another, // we check all known path syntaxes, both Unix and Windows. return == "." || strings.HasPrefix(, "./") || strings.HasPrefix(, `.\`) || == ".." || strings.HasPrefix(, "../") || strings.HasPrefix(, `..\`) || strings.HasPrefix(, "/") || strings.HasPrefix(, `\`) || len() >= 2 && ('A' <= [0] && [0] <= 'Z' || 'a' <= [0] && [0] <= 'z') && [1] == ':' } // MustQuote reports whether s must be quoted in order to appear as // a single token in a go.mod line. func ( string) bool { for , := range { switch { case ' ', '"', '\'', '`': return true case '(', ')', '[', ']', '{', '}', ',': if len() > 1 { return true } default: if !unicode.IsPrint() { return true } } } return == "" || strings.Contains(, "//") || strings.Contains(, "/*") } // AutoQuote returns s or, if quoting is required for s to appear in a go.mod, // the quotation of s. func ( string) string { if MustQuote() { return strconv.Quote() } return } func ( string, string, *[]string, VersionFixer) (VersionInterval, error) { := * if len() == 0 || [0] == "(" { return VersionInterval{}, fmt.Errorf("expected '[' or version") } if [0] != "[" { , := parseVersion(, , &[0], ) if != nil { return VersionInterval{}, } * = [1:] return VersionInterval{Low: , High: }, nil } = [1:] if len() == 0 { return VersionInterval{}, fmt.Errorf("expected version after '['") } , := parseVersion(, , &[0], ) if != nil { return VersionInterval{}, } = [1:] if len() == 0 || [0] != "," { return VersionInterval{}, fmt.Errorf("expected ',' after version") } = [1:] if len() == 0 { return VersionInterval{}, fmt.Errorf("expected version after ','") } , := parseVersion(, , &[0], ) if != nil { return VersionInterval{}, } = [1:] if len() == 0 || [0] != "]" { return VersionInterval{}, fmt.Errorf("expected ']' after version") } = [1:] * = return VersionInterval{Low: , High: }, nil } func ( *string) (string, error) { := * if strings.HasPrefix(, `"`) { var error if , = strconv.Unquote(); != nil { return "", } } else if strings.ContainsAny(, "\"'`") { // Other quotes are reserved both for possible future expansion // and to avoid confusion. For example if someone types 'x' // we want that to be a syntax error and not a literal x in literal quotation marks. return "", fmt.Errorf("unquoted string cannot contain quote") } * = AutoQuote() return , nil } var deprecatedRE = lazyregexp.New(`(?s)(?:^|\n\n)Deprecated: *(.*?)(?:$|\n\n)`) // parseDeprecation extracts the text of comments on a "module" directive and // extracts a deprecation message from that. // // A deprecation message is contained in a paragraph within a block of comments // that starts with "Deprecated:" (case sensitive). The message runs until the // end of the paragraph and does not include the "Deprecated:" prefix. If the // comment block has multiple paragraphs that start with "Deprecated:", // parseDeprecation returns the message from the first. func ( *LineBlock, *Line) string { := parseDirectiveComment(, ) := deprecatedRE.FindStringSubmatch() if == nil { return "" } return [1] } // parseDirectiveComment extracts the text of comments on a directive. // If the directive's line does not have comments and is part of a block that // does have comments, the block's comments are used. func ( *LineBlock, *Line) string { := .Comment() if != nil && len(.Before) == 0 && len(.Suffix) == 0 { = .Comment() } := [][]Comment{.Before, .Suffix} var []string for , := range { for , := range { if !strings.HasPrefix(.Token, "//") { continue // blank line } = append(, strings.TrimSpace(strings.TrimPrefix(.Token, "//"))) } } return strings.Join(, "\n") } type ErrorList []Error func ( ErrorList) () string { := make([]string, len()) for , := range { [] = .Error() } return strings.Join(, "\n") } type Error struct { Filename string Pos Position Verb string ModPath string Err error } func ( *Error) () string { var string if .Pos.LineRune > 1 { // Don't print LineRune if it's 1 (beginning of line). // It's always 1 except in scanner errors, which are rare. = fmt.Sprintf("%s:%d:%d: ", .Filename, .Pos.Line, .Pos.LineRune) } else if .Pos.Line > 0 { = fmt.Sprintf("%s:%d: ", .Filename, .Pos.Line) } else if .Filename != "" { = fmt.Sprintf("%s: ", .Filename) } var string if .ModPath != "" { = fmt.Sprintf("%s %s: ", .Verb, .ModPath) } else if .Verb != "" { = fmt.Sprintf("%s: ", .Verb) } return + + .Err.Error() } func ( *Error) () error { return .Err } func ( string, string, *string, VersionFixer) (string, error) { , := parseString() if != nil { return "", &Error{ Verb: , ModPath: , Err: &module.InvalidVersionError{ Version: *, Err: , }, } } if != nil { , := (, ) if != nil { if , := .(*module.ModuleError); { return "", &Error{ Verb: , ModPath: , Err: .Err, } } return "", } = } else { := module.CanonicalVersion() if == "" { return "", &Error{ Verb: , ModPath: , Err: &module.InvalidVersionError{ Version: , Err: errors.New("must be of the form v1.2.3"), }, } } = } * = return *, nil } func ( string) (string, error) { , , := module.SplitPathVersion() if ! { return "", fmt.Errorf("invalid module path") } return , nil } func ( *File) () ([]byte, error) { return Format(.Syntax), nil } // Cleanup cleans up the file f after any edit operations. // To avoid quadratic behavior, modifications like [File.DropRequire] // clear the entry but do not remove it from the slice. // Cleanup cleans out all the cleared entries. func ( *File) () { := 0 for , := range .Godebug { if .Key != "" { .Godebug[] = ++ } } .Godebug = .Godebug[:] = 0 for , := range .Require { if .Mod.Path != "" { .Require[] = ++ } } .Require = .Require[:] = 0 for , := range .Exclude { if .Mod.Path != "" { .Exclude[] = ++ } } .Exclude = .Exclude[:] = 0 for , := range .Replace { if .Old.Path != "" { .Replace[] = ++ } } .Replace = .Replace[:] = 0 for , := range .Retract { if .Low != "" || .High != "" { .Retract[] = ++ } } .Retract = .Retract[:] .Syntax.Cleanup() } func ( *File) ( string) error { if !GoVersionRE.MatchString() { return fmt.Errorf("invalid language version %q", ) } if .Go == nil { var Expr if .Module != nil && .Module.Syntax != nil { = .Module.Syntax } else if .Syntax == nil { .Syntax = new(FileSyntax) } .Go = &Go{ Version: , Syntax: .Syntax.addLine(, "go", ), } } else { .Go.Version = .Syntax.updateLine(.Go.Syntax, "go", ) } return nil } // DropGoStmt deletes the go statement from the file. func ( *File) () { if .Go != nil { .Go.Syntax.markRemoved() .Go = nil } } // DropToolchainStmt deletes the toolchain statement from the file. func ( *File) () { if .Toolchain != nil { .Toolchain.Syntax.markRemoved() .Toolchain = nil } } func ( *File) ( string) error { if !ToolchainRE.MatchString() { return fmt.Errorf("invalid toolchain name %q", ) } if .Toolchain == nil { var Expr if .Go != nil && .Go.Syntax != nil { = .Go.Syntax } else if .Module != nil && .Module.Syntax != nil { = .Module.Syntax } .Toolchain = &Toolchain{ Name: , Syntax: .Syntax.addLine(, "toolchain", ), } } else { .Toolchain.Name = .Syntax.updateLine(.Toolchain.Syntax, "toolchain", ) } return nil } // AddGodebug sets the first godebug line for key to value, // preserving any existing comments for that line and removing all // other godebug lines for key. // // If no line currently exists for key, AddGodebug adds a new line // at the end of the last godebug block. func ( *File) (, string) error { := true for , := range .Godebug { if .Key == { if { .Value = .Syntax.updateLine(.Syntax, "godebug", +"="+) = false } else { .Syntax.markRemoved() * = Godebug{} } } } if { .addNewGodebug(, ) } return nil } // addNewGodebug adds a new godebug key=value line at the end // of the last godebug block, regardless of any existing godebug lines for key. func ( *File) (, string) { := .Syntax.addLine(nil, "godebug", +"="+) := &Godebug{ Key: , Value: , Syntax: , } .Godebug = append(.Godebug, ) } // 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) (, string) error { := true for , := range .Require { if .Mod.Path == { if { .Mod.Version = .Syntax.updateLine(.Syntax, "require", AutoQuote(), ) = false } else { .Syntax.markRemoved() * = Require{} } } } if { .AddNewRequire(, , false) } return nil } // 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) (, string, bool) { := .Syntax.addLine(nil, "require", AutoQuote(), ) := &Require{ Mod: module.Version{Path: , Version: }, Syntax: , } .setIndirect() .Require = append(.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 // [File.Cleanup] after all edits are complete. func ( *File) ( []*Require) { type struct { string bool } := make(map[string]) for , := range { if , := [.Mod.Path]; && . != .Mod.Version { panic(fmt.Errorf("SetRequire called with conflicting versions for path %s (%s and %s)", .Mod.Path, ., .Mod.Version)) } [.Mod.Path] = {.Mod.Version, .Indirect} } // Update or delete the existing Require entries to preserve // only the first for each module path in req. for , := range .Require { , := [.Mod.Path] if { .setVersion(.) .setIndirect(.) } else { .markRemoved() } delete(, .Mod.Path) } // Add new entries in the last block of the file for any paths that weren't // already present. // // This step is nondeterministic, but the final result will be deterministic // because we will sort the block. for , := range { .AddNewRequire(, ., .) } .SortBlocks() } // 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) ( []*Require) { .setRequireSeparateIndirect(, false) } // SetRequireAtMostTwo is like SetRequireSeparateIndirect but it aggressively // consolidates all requirements into at most two blocks (one direct, one indirect). // It ignores existing blocks and comments when deciding where to place requirements. func ( *File) ( []*Require) { .setRequireSeparateIndirect(, true) } func ( *File) ( []*Require, bool) { // hasComments returns whether a line or block has comments // other than "indirect". := func( Comments) bool { return len(.Before) > 0 || len(.After) > 0 || len(.Suffix) > 1 || (len(.Suffix) == 1 && strings.TrimSpace(strings.TrimPrefix(.Suffix[0].Token, string(slashSlash))) != "indirect") } // moveReq adds r to block. If r was in another block, moveReq deletes // it from that block and transfers its comments. := func( *Require, *LineBlock) { var *Line if .Syntax == nil { = &Line{Token: []string{AutoQuote(.Mod.Path), .Mod.Version}} .Syntax = if .Indirect { .setIndirect(true) } } else { = new(Line) * = *.Syntax if !.InBlock && len(.Token) > 0 && .Token[0] == "require" { .Token = .Token[1:] } .Syntax.Token = nil // Cleanup will delete the old line. .Syntax = } .InBlock = true .Line = append(.Line, ) } // Examine existing require lines and blocks. := make(map[string]*Require) for , := range { [.Mod.Path] = } := make(map[*Line]bool) for , := range .Require { if := [.Mod.Path]; != nil { [.Syntax] = .Indirect } } var ( // We may insert new requirements into the last uncommented // direct-only and indirect-only blocks. We may also move requirements // to the opposite block if their indirect markings change. = -1 = -1 // If there are no direct-only or indirect-only blocks, a new block may // be inserted after the last require line or block. = -1 // If there's only one require line or block, and it's uncommented, // we'll move its requirements to the direct-only or indirect-only blocks. = 0 // Track the block each requirement belongs to (if any) so we can // move them later. = make(map[*Line]*LineBlock) []Comment []Comment ) for , := range .Syntax.Stmt { switch stmt := .(type) { case *Line: if len(.Token) == 0 || .Token[0] != "require" { continue } = ++ if !(.Comments) { if isIndirect() { = } else { = } } case *LineBlock: if len(.Token) == 0 || .Token[0] != "require" { continue } = ++ := len(.Line) > 0 && !(.Comments) := len(.Line) > 0 && !(.Comments) for , := range .Line { [] = if (.Comments) { = false = false } else if isIndirect() { = false } else { = false } } if { = } if { = } if { := false for , := range .Line { if , := []; && ! { = true break } } := & if ! && len(.Line) > 0 { = & } if len(*) > 0 && len(.Comments.Before) > 0 { * = append(*, Comment{Token: "//"}) } * = append(*, .Comments.Before...) .Comments.Before = nil } } } := == 1 && !(*.Syntax.Stmt[].Comment()) // Create direct and indirect blocks if needed. Convert lines into blocks // if needed. If we end up with an empty block or a one-line block, // Cleanup will delete it or convert it to a line later. := func( int) *LineBlock { := &LineBlock{Token: []string{"require"}} .Syntax.Stmt = append(.Syntax.Stmt, nil) copy(.Syntax.Stmt[+1:], .Syntax.Stmt[:]) .Syntax.Stmt[] = return } := func( int) *LineBlock { switch stmt := .Syntax.Stmt[].(type) { case *LineBlock: return case *Line: := &LineBlock{ Token: []string{"require"}, Line: []*Line{}, } .Token = .Token[1:] // remove "require" .InBlock = true .Syntax.Stmt[] = return default: panic(fmt.Sprintf("unexpected statement: %v", )) } } var *LineBlock if < 0 { if >= 0 { = ++ } else if >= 0 { = + 1 } else { = len(.Syntax.Stmt) } = () } else { = () } var *LineBlock if < 0 { = + 1 = () } else { = () } if { if len() > 0 { .Comments.Before = append(.Comments.Before, ...) } if len() > 0 { .Comments.Before = append(.Comments.Before, ...) } } // Delete requirements we don't want anymore. // Update versions and indirect comments on requirements we want to keep. // If a requirement is in last{Direct,Indirect}Block with the wrong // indirect marking after this, or if the requirement is in a single // uncommented mixed block (oneFlatUncommentedBlock), move it to the // correct block. // // Some blocks may be empty after this. Cleanup will remove them. := make(map[string]*Require) for , := range .Require { := .Mod.Path if [] == nil || [] != nil { // Requirement not needed, or duplicate requirement. Delete. .markRemoved() continue } [.Mod.Path] = .setVersion([].Mod.Version) .setIndirect([].Indirect) if [].Indirect && ( || || [.Syntax] == ) { (, ) } else if ![].Indirect && ( || || [.Syntax] == ) { (, ) } } // Add new requirements. for , := range { if [] == nil { if .Indirect { (, ) } else { (, ) } .Require = append(.Require, ) } } .SortBlocks() } func ( *File) ( string) error { for , := range .Godebug { if .Key == { .Syntax.markRemoved() * = Godebug{} } } return nil } func ( *File) ( string) error { for , := range .Require { if .Mod.Path == { .Syntax.markRemoved() * = Require{} } } return nil } // AddExclude adds an exclude statement to the mod file. Errors if the provided // version is not a canonical version string func ( *File) (, string) error { if := checkCanonicalVersion(, ); != nil { return } var *Line for , := range .Exclude { if .Mod.Path == && .Mod.Version == { return nil } if .Mod.Path == { = .Syntax } } .Exclude = append(.Exclude, &Exclude{Mod: module.Version{Path: , Version: }, Syntax: .Syntax.addLine(, "exclude", AutoQuote(), )}) return nil } func ( *File) (, string) error { for , := range .Exclude { if .Mod.Path == && .Mod.Version == { .Syntax.markRemoved() * = Exclude{} } } return nil } func ( *File) (, , , string) error { return addReplace(.Syntax, &.Replace, , , , ) } func ( *FileSyntax, *[]*Replace, , , , string) error { := true := module.Version{Path: , Version: } := module.Version{Path: , Version: } := []string{"replace", AutoQuote()} if != "" { = append(, ) } = append(, "=>", AutoQuote()) if != "" { = append(, ) } var *Line for , := range * { if .Old.Path == && ( == "" || .Old.Version == ) { if { // Found replacement for old; update to use new. .New = .updateLine(.Syntax, ...) = false continue } // Already added; delete other replacements for same. .Syntax.markRemoved() * = Replace{} } if .Old.Path == { = .Syntax } } if { * = append(*, &Replace{Old: , New: , Syntax: .addLine(, ...)}) } return nil } func ( *File) (, string) error { for , := range .Replace { if .Old.Path == && .Old.Version == { .Syntax.markRemoved() * = Replace{} } } return nil } // AddRetract adds a retract statement to the mod file. Errors if the provided // version interval does not consist of canonical version strings func ( *File) ( VersionInterval, string) error { var string if .Module != nil { = .Module.Mod.Path } if := checkCanonicalVersion(, .High); != nil { return } if := checkCanonicalVersion(, .Low); != nil { return } := &Retract{ VersionInterval: , } if .Low == .High { .Syntax = .Syntax.addLine(nil, "retract", AutoQuote(.Low)) } else { .Syntax = .Syntax.addLine(nil, "retract", "[", AutoQuote(.Low), ",", AutoQuote(.High), "]") } if != "" { for := range strings.SplitSeq(, "\n") { := Comment{Token: "// " + } .Syntax.Comment().Before = append(.Syntax.Comment().Before, ) } } return nil } func ( *File) ( VersionInterval) error { for , := range .Retract { if .VersionInterval == { .Syntax.markRemoved() * = Retract{} } } return nil } // AddTool adds a new tool directive with the given path. // It does nothing if the tool line already exists. func ( *File) ( string) error { for , := range .Tool { if .Path == { return nil } } .Tool = append(.Tool, &Tool{ Path: , Syntax: .Syntax.addLine(nil, "tool", ), }) .SortBlocks() return nil } // DropTool removes a tool directive with the given path. // It does nothing if no such tool directive exists. func ( *File) ( string) error { for , := range .Tool { if .Path == { .Syntax.markRemoved() * = Tool{} } } return nil } // AddIgnore adds a new ignore directive with the given path. // It does nothing if the ignore line already exists. func ( *File) ( string) error { for , := range .Ignore { if .Path == { return nil } } .Ignore = append(.Ignore, &Ignore{ Path: , Syntax: .Syntax.addLine(nil, "ignore", ), }) .SortBlocks() return nil } // DropIgnore removes an ignore directive with the given path. // It does nothing if no such ignore directive exists. func ( *File) ( string) error { for , := range .Ignore { if .Path == { .Syntax.markRemoved() * = Ignore{} } } return nil } func ( *File) () { .removeDups() // otherwise sorting is unsafe // semanticSortForExcludeVersionV is the Go version (plus leading "v") at which // lines in exclude blocks start to use semantic sort instead of lexicographic sort. // See go.dev/issue/60028. const = "v1.21" := .Go != nil && semver.Compare("v"+.Go.Version, ) >= 0 for , := range .Syntax.Stmt { , := .(*LineBlock) if ! { continue } := compareLine if .Token[0] == "exclude" && { = compareLineExclude } else if .Token[0] == "retract" { = compareLineRetract } slices.SortStableFunc(.Line, ) } } // removeDups removes duplicate exclude, replace and tool directives. // // Earlier exclude and tool directives take priority. // // Later replace directives take priority. // // require directives are not de-duplicated. That's left up to higher-level // logic (MVS). // // retract directives are not de-duplicated since comments are // meaningful, and versions may be retracted multiple times. func ( *File) () { removeDups(.Syntax, &.Exclude, &.Replace, &.Tool, &.Ignore) } func ( *FileSyntax, *[]*Exclude, *[]*Replace, *[]*Tool, *[]*Ignore) { := make(map[*Line]bool) // Remove duplicate excludes. if != nil { := make(map[module.Version]bool) for , := range * { if [.Mod] { [.Syntax] = true continue } [.Mod] = true } var []*Exclude for , := range * { if ![.Syntax] { = append(, ) } } * = } // Remove duplicate replacements. // Later replacements take priority over earlier ones. := make(map[module.Version]bool) for , := range slices.Backward(*) { if [.Old] { [.Syntax] = true continue } [.Old] = true } var []*Replace for , := range * { if ![.Syntax] { = append(, ) } } * = if != nil { := make(map[string]bool) for , := range * { if [.Path] { [.Syntax] = true continue } [.Path] = true } var []*Tool for , := range * { if ![.Syntax] { = append(, ) } } * = } if != nil { := make(map[string]bool) for , := range * { if [.Path] { [.Syntax] = true continue } [.Path] = true } var []*Ignore for , := range * { if ![.Syntax] { = append(, ) } } * = } // Duplicate require and retract directives are not removed. // Drop killed statements from the syntax tree. var []Expr for , := range .Stmt { switch stmt := .(type) { case *Line: if [] { continue } case *LineBlock: var []*Line for , := range .Line { if ![] { = append(, ) } } .Line = if len() == 0 { continue } } = append(, ) } .Stmt = } // compareLine compares li and lj. It sorts lexicographically without assigning // any special meaning to tokens. func (, *Line) int { for := 0; < len(.Token) && < len(.Token); ++ { if .Token[] != .Token[] { return cmp.Compare(.Token[], .Token[]) } } return cmp.Compare(len(.Token), len(.Token)) } // compareLineExclude compares li and lj for lines in an "exclude" block. func (, *Line) int { if len(.Token) != 2 || len(.Token) != 2 { // Not a known exclude specification. // Fall back to sorting lexicographically. return compareLine(, ) } // An exclude specification has two tokens: ModulePath and Version. // Compare module path by string order and version by semver rules. if , := .Token[0], .Token[0]; != { return cmp.Compare(, ) } return semver.Compare(.Token[1], .Token[1]) } // compareLineRetract compares li and lj for lines in a "retract" block. // It treats each line as a version interval. Single versions are compared as // if they were intervals with the same low and high version. // Intervals are sorted in descending order, first by low version, then by // high version, using [semver.Compare]. func (, *Line) int { := func( *Line) VersionInterval { if len(.Token) == 1 { return VersionInterval{Low: .Token[0], High: .Token[0]} } else if len(.Token) == 5 && .Token[0] == "[" && .Token[2] == "," && .Token[4] == "]" { return VersionInterval{Low: .Token[1], High: .Token[3]} } else { // Line in unknown format. Treat as an invalid version. return VersionInterval{} } } := () := () if := semver.Compare(.Low, .Low); != 0 { return - } return -semver.Compare(.High, .High) } // checkCanonicalVersion returns a non-nil error if vers is not a canonical // version string or does not match the major version of path. // // If path is non-empty, the error text suggests a format with a major version // corresponding to the path. func (, string) error { , , := module.SplitPathVersion() if == "" || != module.CanonicalVersion() { if == "" { return &module.InvalidVersionError{ Version: , Err: fmt.Errorf("must be of the form v1.2.3"), } } return &module.InvalidVersionError{ Version: , Err: fmt.Errorf("must be of the form %s.2.3", module.PathMajorPrefix()), } } if { if := module.CheckPathMajor(, ); != nil { if == "" { // In this context, the user probably wrote "v2.3.4" when they meant // "v2.3.4+incompatible". Suggest that instead of "v0 or v1". return &module.InvalidVersionError{ Version: , Err: fmt.Errorf("should be %s+incompatible (or module %s/%v)", , , semver.Major()), } } return } } return nil }