package modfile
import (
"cmp"
"errors"
"fmt"
"path/filepath"
"slices"
"strconv"
"strings"
"unicode"
"golang.org/x/mod/internal/lazyregexp"
"golang.org/x/mod/module"
"golang.org/x/mod/semver"
)
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
}
type Module struct {
Mod module .Version
Deprecated string
Syntax *Line
}
type Go struct {
Version string
Syntax *Line
}
type Toolchain struct {
Name string
Syntax *Line
}
type Godebug struct {
Key string
Value string
Syntax *Line
}
type Exclude struct {
Mod module .Version
Syntax *Line
}
type Replace struct {
Old module .Version
New module .Version
Syntax *Line
}
type Retract struct {
VersionInterval
Rationale string
Syntax *Line
}
type Tool struct {
Path string
Syntax *Line
}
type Ignore struct {
Path string
Syntax *Line
}
type VersionInterval struct {
Low , High string
}
type Require struct {
Mod module .Version
Indirect bool
Syntax *Line
}
func (r *Require ) markRemoved () {
r .Syntax .markRemoved ()
*r = Require {}
}
func (r *Require ) setVersion (v string ) {
r .Mod .Version = v
if line := r .Syntax ; len (line .Token ) > 0 {
if line .InBlock {
if len (line .Comments .Before ) == 1 && len (line .Comments .Before [0 ].Token ) == 0 {
line .Comments .Before = line .Comments .Before [:0 ]
}
if len (line .Token ) >= 2 {
line .Token [1 ] = v
}
} else {
if len (line .Token ) >= 3 {
line .Token [2 ] = v
}
}
}
}
func (r *Require ) setIndirect (indirect bool ) {
r .Indirect = indirect
line := r .Syntax
if isIndirect (line ) == indirect {
return
}
if indirect {
if len (line .Suffix ) == 0 {
line .Suffix = []Comment {{Token : "// indirect" , Suffix : true }}
return
}
com := &line .Suffix [0 ]
text := strings .TrimSpace (strings .TrimPrefix (com .Token , string (slashSlash )))
if text == "" {
com .Token = "// indirect"
return
}
com .Token = "// indirect; " + text
return
}
f := strings .TrimSpace (strings .TrimPrefix (line .Suffix [0 ].Token , string (slashSlash )))
if f == "indirect" {
line .Suffix = nil
return
}
com := &line .Suffix [0 ]
i := strings .Index (com .Token , "indirect;" )
com .Token = "//" + com .Token [i +len ("indirect;" ):]
}
func isIndirect (line *Line ) bool {
if len (line .Suffix ) == 0 {
return false
}
f := strings .Fields (strings .TrimPrefix (line .Suffix [0 ].Token , string (slashSlash )))
return (len (f ) == 1 && f [0 ] == "indirect" || len (f ) > 1 && f [0 ] == "indirect;" )
}
func (f *File ) AddModuleStmt (path string ) error {
if f .Syntax == nil {
f .Syntax = new (FileSyntax )
}
if f .Module == nil {
f .Module = &Module {
Mod : module .Version {Path : path },
Syntax : f .Syntax .addLine (nil , "module" , AutoQuote (path )),
}
} else {
f .Module .Mod .Path = path
f .Syntax .updateLine (f .Module .Syntax , "module" , AutoQuote (path ))
}
return nil
}
func (f *File ) AddComment (text string ) {
if f .Syntax == nil {
f .Syntax = new (FileSyntax )
}
f .Syntax .Stmt = append (f .Syntax .Stmt , &CommentBlock {
Comments : Comments {
Before : []Comment {
{
Token : text ,
},
},
},
})
}
type VersionFixer func (path, version string ) (string , error )
var dontFixRetract VersionFixer = func (_ , vers string ) (string , error ) {
return vers , nil
}
func Parse (file string , data []byte , fix VersionFixer ) (*File , error ) {
return parseToFile (file , data , fix , true )
}
func ParseLax (file string , data []byte , fix VersionFixer ) (*File , error ) {
return parseToFile (file , data , fix , false )
}
func parseToFile (file string , data []byte , fix VersionFixer , strict bool ) (parsed *File , err error ) {
fs , err := parse (file , data )
if err != nil {
return nil , err
}
f := &File {
Syntax : fs ,
}
var errs ErrorList
defer func () {
oldLen := len (errs )
f .fixRetract (fix , &errs )
if len (errs ) > oldLen {
parsed , err = nil , errs
}
}()
for _ , x := range fs .Stmt {
switch x := x .(type ) {
case *Line :
f .add (&errs , nil , x , x .Token [0 ], x .Token [1 :], fix , strict )
case *LineBlock :
if len (x .Token ) > 1 {
if strict {
errs = append (errs , Error {
Filename : file ,
Pos : x .Start ,
Err : fmt .Errorf ("unknown block type: %s" , strings .Join (x .Token , " " )),
})
}
continue
}
switch x .Token [0 ] {
default :
if strict {
errs = append (errs , Error {
Filename : file ,
Pos : x .Start ,
Err : fmt .Errorf ("unknown block type: %s" , strings .Join (x .Token , " " )),
})
}
continue
case "module" , "godebug" , "require" , "exclude" , "replace" , "retract" , "tool" , "ignore" :
for _ , l := range x .Line {
f .add (&errs , x , l , x .Token [0 ], l .Token , fix , strict )
}
}
}
}
if len (errs ) > 0 {
return nil , errs
}
return f , 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].*)$` )
var ToolchainRE = lazyregexp .New (`^default$|^go1($|\.)` )
func (f *File ) add (errs *ErrorList , block *LineBlock , line *Line , verb string , args []string , fix VersionFixer , strict bool ) {
if !strict {
switch verb {
case "go" , "module" , "retract" , "require" , "ignore" :
default :
return
}
}
wrapModPathError := func (modPath string , err error ) {
*errs = append (*errs , Error {
Filename : f .Syntax .Name ,
Pos : line .Start ,
ModPath : modPath ,
Verb : verb ,
Err : err ,
})
}
wrapError := func (err error ) {
*errs = append (*errs , Error {
Filename : f .Syntax .Name ,
Pos : line .Start ,
Err : err ,
})
}
errorf := func (format string , args ...any ) {
wrapError (fmt .Errorf (format , args ...))
}
switch verb {
default :
errorf ("unknown directive: %s" , verb )
case "go" :
if f .Go != nil {
errorf ("repeated go statement" )
return
}
if len (args ) != 1 {
errorf ("go directive expects exactly one argument" )
return
} else if !GoVersionRE .MatchString (args [0 ]) {
fixed := false
if !strict {
if m := laxGoVersionRE .FindStringSubmatch (args [0 ]); m != nil {
args [0 ] = m [1 ]
fixed = true
}
}
if !fixed {
errorf ("invalid go version '%s': must match format 1.23.0" , args [0 ])
return
}
}
f .Go = &Go {Syntax : line }
f .Go .Version = args [0 ]
case "toolchain" :
if f .Toolchain != nil {
errorf ("repeated toolchain statement" )
return
}
if len (args ) != 1 {
errorf ("toolchain directive expects exactly one argument" )
return
} else if !ToolchainRE .MatchString (args [0 ]) {
errorf ("invalid toolchain version '%s': must match format go1.23.0 or default" , args [0 ])
return
}
f .Toolchain = &Toolchain {Syntax : line }
f .Toolchain .Name = args [0 ]
case "module" :
if f .Module != nil {
errorf ("repeated module statement" )
return
}
deprecated := parseDeprecation (block , line )
f .Module = &Module {
Syntax : line ,
Deprecated : deprecated ,
}
if len (args ) != 1 {
errorf ("usage: module module/path" )
return
}
s , err := parseString (&args [0 ])
if err != nil {
errorf ("invalid quoted string: %v" , err )
return
}
f .Module .Mod = module .Version {Path : s }
case "godebug" :
if len (args ) != 1 || strings .ContainsAny (args [0 ], "\"`'," ) {
errorf ("usage: godebug key=value" )
return
}
key , value , ok := strings .Cut (args [0 ], "=" )
if !ok {
errorf ("usage: godebug key=value" )
return
}
f .Godebug = append (f .Godebug , &Godebug {
Key : key ,
Value : value ,
Syntax : line ,
})
case "require" , "exclude" :
if len (args ) != 2 {
errorf ("usage: %s module/path v1.2.3" , verb )
return
}
s , err := parseString (&args [0 ])
if err != nil {
errorf ("invalid quoted string: %v" , err )
return
}
v , err := parseVersion (verb , s , &args [1 ], fix )
if err != nil {
wrapError (err )
return
}
pathMajor , err := modulePathMajor (s )
if err != nil {
wrapError (err )
return
}
if err := module .CheckPathMajor (v , pathMajor ); err != nil {
wrapModPathError (s , err )
return
}
if verb == "require" {
f .Require = append (f .Require , &Require {
Mod : module .Version {Path : s , Version : v },
Syntax : line ,
Indirect : isIndirect (line ),
})
} else {
f .Exclude = append (f .Exclude , &Exclude {
Mod : module .Version {Path : s , Version : v },
Syntax : line ,
})
}
case "replace" :
replace , wrappederr := parseReplace (f .Syntax .Name , line , verb , args , fix )
if wrappederr != nil {
*errs = append (*errs , *wrappederr )
return
}
f .Replace = append (f .Replace , replace )
case "retract" :
rationale := parseDirectiveComment (block , line )
vi , err := parseVersionInterval (verb , "" , &args , dontFixRetract )
if err != nil {
if strict {
wrapError (err )
return
} else {
return
}
}
if len (args ) > 0 && strict {
errorf ("unexpected token after version: %q" , args [0 ])
return
}
retract := &Retract {
VersionInterval : vi ,
Rationale : rationale ,
Syntax : line ,
}
f .Retract = append (f .Retract , retract )
case "tool" :
if len (args ) != 1 {
errorf ("tool directive expects exactly one argument" )
return
}
s , err := parseString (&args [0 ])
if err != nil {
errorf ("invalid quoted string: %v" , err )
return
}
f .Tool = append (f .Tool , &Tool {
Path : s ,
Syntax : line ,
})
case "ignore" :
if len (args ) != 1 {
errorf ("ignore directive expects exactly one argument" )
return
}
s , err := parseString (&args [0 ])
if err != nil {
errorf ("invalid quoted string: %v" , err )
return
}
f .Ignore = append (f .Ignore , &Ignore {
Path : s ,
Syntax : line ,
})
}
}
func parseReplace (filename string , line *Line , verb string , args []string , fix VersionFixer ) (*Replace , *Error ) {
wrapModPathError := func (modPath string , err error ) *Error {
return &Error {
Filename : filename ,
Pos : line .Start ,
ModPath : modPath ,
Verb : verb ,
Err : err ,
}
}
wrapError := func (err error ) *Error {
return &Error {
Filename : filename ,
Pos : line .Start ,
Err : err ,
}
}
errorf := func (format string , args ...any ) *Error {
return wrapError (fmt .Errorf (format , args ...))
}
arrow := 2
if len (args ) >= 2 && args [1 ] == "=>" {
arrow = 1
}
if len (args ) < arrow +2 || len (args ) > arrow +3 || args [arrow ] != "=>" {
return nil , errorf ("usage: %s module/path [v1.2.3] => other/module v1.4\n\t or %s module/path [v1.2.3] => ../local/directory" , verb , verb )
}
s , err := parseString (&args [0 ])
if err != nil {
return nil , errorf ("invalid quoted string: %v" , err )
}
pathMajor , err := modulePathMajor (s )
if err != nil {
return nil , wrapModPathError (s , err )
}
var v string
if arrow == 2 {
v , err = parseVersion (verb , s , &args [1 ], fix )
if err != nil {
return nil , wrapError (err )
}
if err := module .CheckPathMajor (v , pathMajor ); err != nil {
return nil , wrapModPathError (s , err )
}
}
ns , err := parseString (&args [arrow +1 ])
if err != nil {
return nil , errorf ("invalid quoted string: %v" , err )
}
nv := ""
if len (args ) == arrow +2 {
if !IsDirectoryPath (ns ) {
if strings .Contains (ns , "@" ) {
return nil , errorf ("replacement module must match format 'path version', not 'path@version'" )
}
return nil , errorf ("replacement module without version must be directory path (rooted or starting with . or ..)" )
}
if filepath .Separator == '/' && strings .Contains (ns , `\` ) {
return nil , errorf ("replacement directory appears to be Windows path (on a non-windows system)" )
}
}
if len (args ) == arrow +3 {
nv , err = parseVersion (verb , ns , &args [arrow +2 ], fix )
if err != nil {
return nil , wrapError (err )
}
if IsDirectoryPath (ns ) {
return nil , errorf ("replacement module directory path %q cannot have version" , ns )
}
}
return &Replace {
Old : module .Version {Path : s , Version : v },
New : module .Version {Path : ns , Version : nv },
Syntax : line ,
}, nil
}
func (f *File ) fixRetract (fix VersionFixer , errs *ErrorList ) {
if fix == nil {
return
}
path := ""
if f .Module != nil {
path = f .Module .Mod .Path
}
var r *Retract
wrapError := func (err error ) {
*errs = append (*errs , Error {
Filename : f .Syntax .Name ,
Pos : r .Syntax .Start ,
Err : err ,
})
}
for _, r = range f .Retract {
if path == "" {
wrapError (errors .New ("no module directive found, so retract cannot be used" ))
return
}
args := r .Syntax .Token
if args [0 ] == "retract" {
args = args [1 :]
}
vi , err := parseVersionInterval ("retract" , path , &args , fix )
if err != nil {
wrapError (err )
}
r .VersionInterval = vi
}
}
func (f *WorkFile ) add (errs *ErrorList , line *Line , verb string , args []string , fix VersionFixer ) {
wrapError := func (err error ) {
*errs = append (*errs , Error {
Filename : f .Syntax .Name ,
Pos : line .Start ,
Err : err ,
})
}
errorf := func (format string , args ...any ) {
wrapError (fmt .Errorf (format , args ...))
}
switch verb {
default :
errorf ("unknown directive: %s" , verb )
case "go" :
if f .Go != nil {
errorf ("repeated go statement" )
return
}
if len (args ) != 1 {
errorf ("go directive expects exactly one argument" )
return
} else if !GoVersionRE .MatchString (args [0 ]) {
errorf ("invalid go version '%s': must match format 1.23.0" , args [0 ])
return
}
f .Go = &Go {Syntax : line }
f .Go .Version = args [0 ]
case "toolchain" :
if f .Toolchain != nil {
errorf ("repeated toolchain statement" )
return
}
if len (args ) != 1 {
errorf ("toolchain directive expects exactly one argument" )
return
} else if !ToolchainRE .MatchString (args [0 ]) {
errorf ("invalid toolchain version '%s': must match format go1.23.0 or default" , args [0 ])
return
}
f .Toolchain = &Toolchain {Syntax : line }
f .Toolchain .Name = args [0 ]
case "godebug" :
if len (args ) != 1 || strings .ContainsAny (args [0 ], "\"`'," ) {
errorf ("usage: godebug key=value" )
return
}
key , value , ok := strings .Cut (args [0 ], "=" )
if !ok {
errorf ("usage: godebug key=value" )
return
}
f .Godebug = append (f .Godebug , &Godebug {
Key : key ,
Value : value ,
Syntax : line ,
})
case "use" :
if len (args ) != 1 {
errorf ("usage: %s local/dir" , verb )
return
}
s , err := parseString (&args [0 ])
if err != nil {
errorf ("invalid quoted string: %v" , err )
return
}
f .Use = append (f .Use , &Use {
Path : s ,
Syntax : line ,
})
case "replace" :
replace , wrappederr := parseReplace (f .Syntax .Name , line , verb , args , fix )
if wrappederr != nil {
*errs = append (*errs , *wrappederr )
return
}
f .Replace = append (f .Replace , replace )
}
}
func IsDirectoryPath (ns string ) bool {
return ns == "." || strings .HasPrefix (ns , "./" ) || strings .HasPrefix (ns , `.\` ) ||
ns == ".." || strings .HasPrefix (ns , "../" ) || strings .HasPrefix (ns , `..\` ) ||
strings .HasPrefix (ns , "/" ) || strings .HasPrefix (ns , `\` ) ||
len (ns ) >= 2 && ('A' <= ns [0 ] && ns [0 ] <= 'Z' || 'a' <= ns [0 ] && ns [0 ] <= 'z' ) && ns [1 ] == ':'
}
func MustQuote (s string ) bool {
for _ , r := range s {
switch r {
case ' ' , '"' , '\'' , '`' :
return true
case '(' , ')' , '[' , ']' , '{' , '}' , ',' :
if len (s ) > 1 {
return true
}
default :
if !unicode .IsPrint (r ) {
return true
}
}
}
return s == "" || strings .Contains (s , "//" ) || strings .Contains (s , "/*" )
}
func AutoQuote (s string ) string {
if MustQuote (s ) {
return strconv .Quote (s )
}
return s
}
func parseVersionInterval (verb string , path string , args *[]string , fix VersionFixer ) (VersionInterval , error ) {
toks := *args
if len (toks ) == 0 || toks [0 ] == "(" {
return VersionInterval {}, fmt .Errorf ("expected '[' or version" )
}
if toks [0 ] != "[" {
v , err := parseVersion (verb , path , &toks [0 ], fix )
if err != nil {
return VersionInterval {}, err
}
*args = toks [1 :]
return VersionInterval {Low : v , High : v }, nil
}
toks = toks [1 :]
if len (toks ) == 0 {
return VersionInterval {}, fmt .Errorf ("expected version after '['" )
}
low , err := parseVersion (verb , path , &toks [0 ], fix )
if err != nil {
return VersionInterval {}, err
}
toks = toks [1 :]
if len (toks ) == 0 || toks [0 ] != "," {
return VersionInterval {}, fmt .Errorf ("expected ',' after version" )
}
toks = toks [1 :]
if len (toks ) == 0 {
return VersionInterval {}, fmt .Errorf ("expected version after ','" )
}
high , err := parseVersion (verb , path , &toks [0 ], fix )
if err != nil {
return VersionInterval {}, err
}
toks = toks [1 :]
if len (toks ) == 0 || toks [0 ] != "]" {
return VersionInterval {}, fmt .Errorf ("expected ']' after version" )
}
toks = toks [1 :]
*args = toks
return VersionInterval {Low : low , High : high }, nil
}
func parseString (s *string ) (string , error ) {
t := *s
if strings .HasPrefix (t , `"` ) {
var err error
if t , err = strconv .Unquote (t ); err != nil {
return "" , err
}
} else if strings .ContainsAny (t , "\"'`" ) {
return "" , fmt .Errorf ("unquoted string cannot contain quote" )
}
*s = AutoQuote (t )
return t , nil
}
var deprecatedRE = lazyregexp .New (`(?s)(?:^|\n\n)Deprecated: *(.*?)(?:$|\n\n)` )
func parseDeprecation (block *LineBlock , line *Line ) string {
text := parseDirectiveComment (block , line )
m := deprecatedRE .FindStringSubmatch (text )
if m == nil {
return ""
}
return m [1 ]
}
func parseDirectiveComment (block *LineBlock , line *Line ) string {
comments := line .Comment ()
if block != nil && len (comments .Before ) == 0 && len (comments .Suffix ) == 0 {
comments = block .Comment ()
}
groups := [][]Comment {comments .Before , comments .Suffix }
var lines []string
for _ , g := range groups {
for _ , c := range g {
if !strings .HasPrefix (c .Token , "//" ) {
continue
}
lines = append (lines , strings .TrimSpace (strings .TrimPrefix (c .Token , "//" )))
}
}
return strings .Join (lines , "\n" )
}
type ErrorList []Error
func (e ErrorList ) Error () string {
errStrs := make ([]string , len (e ))
for i , err := range e {
errStrs [i ] = err .Error ()
}
return strings .Join (errStrs , "\n" )
}
type Error struct {
Filename string
Pos Position
Verb string
ModPath string
Err error
}
func (e *Error ) Error () string {
var pos string
if e .Pos .LineRune > 1 {
pos = fmt .Sprintf ("%s:%d:%d: " , e .Filename , e .Pos .Line , e .Pos .LineRune )
} else if e .Pos .Line > 0 {
pos = fmt .Sprintf ("%s:%d: " , e .Filename , e .Pos .Line )
} else if e .Filename != "" {
pos = fmt .Sprintf ("%s: " , e .Filename )
}
var directive string
if e .ModPath != "" {
directive = fmt .Sprintf ("%s %s: " , e .Verb , e .ModPath )
} else if e .Verb != "" {
directive = fmt .Sprintf ("%s: " , e .Verb )
}
return pos + directive + e .Err .Error()
}
func (e *Error ) Unwrap () error { return e .Err }
func parseVersion (verb string , path string , s *string , fix VersionFixer ) (string , error ) {
t , err := parseString (s )
if err != nil {
return "" , &Error {
Verb : verb ,
ModPath : path ,
Err : &module .InvalidVersionError {
Version : *s ,
Err : err ,
},
}
}
if fix != nil {
fixed , err := fix (path , t )
if err != nil {
if err , ok := err .(*module .ModuleError ); ok {
return "" , &Error {
Verb : verb ,
ModPath : path ,
Err : err .Err ,
}
}
return "" , err
}
t = fixed
} else {
cv := module .CanonicalVersion (t )
if cv == "" {
return "" , &Error {
Verb : verb ,
ModPath : path ,
Err : &module .InvalidVersionError {
Version : t ,
Err : errors .New ("must be of the form v1.2.3" ),
},
}
}
t = cv
}
*s = t
return *s , nil
}
func modulePathMajor (path string ) (string , error ) {
_ , major , ok := module .SplitPathVersion (path )
if !ok {
return "" , fmt .Errorf ("invalid module path" )
}
return major , nil
}
func (f *File ) Format () ([]byte , error ) {
return Format (f .Syntax ), nil
}
func (f *File ) Cleanup () {
w := 0
for _ , g := range f .Godebug {
if g .Key != "" {
f .Godebug [w ] = g
w ++
}
}
f .Godebug = f .Godebug [:w ]
w = 0
for _ , r := range f .Require {
if r .Mod .Path != "" {
f .Require [w ] = r
w ++
}
}
f .Require = f .Require [:w ]
w = 0
for _ , x := range f .Exclude {
if x .Mod .Path != "" {
f .Exclude [w ] = x
w ++
}
}
f .Exclude = f .Exclude [:w ]
w = 0
for _ , r := range f .Replace {
if r .Old .Path != "" {
f .Replace [w ] = r
w ++
}
}
f .Replace = f .Replace [:w ]
w = 0
for _ , r := range f .Retract {
if r .Low != "" || r .High != "" {
f .Retract [w ] = r
w ++
}
}
f .Retract = f .Retract [:w ]
f .Syntax .Cleanup ()
}
func (f *File ) AddGoStmt (version string ) error {
if !GoVersionRE .MatchString (version ) {
return fmt .Errorf ("invalid language version %q" , version )
}
if f .Go == nil {
var hint Expr
if f .Module != nil && f .Module .Syntax != nil {
hint = f .Module .Syntax
} else if f .Syntax == nil {
f .Syntax = new (FileSyntax )
}
f .Go = &Go {
Version : version ,
Syntax : f .Syntax .addLine (hint , "go" , version ),
}
} else {
f .Go .Version = version
f .Syntax .updateLine (f .Go .Syntax , "go" , version )
}
return nil
}
func (f *File ) DropGoStmt () {
if f .Go != nil {
f .Go .Syntax .markRemoved ()
f .Go = nil
}
}
func (f *File ) DropToolchainStmt () {
if f .Toolchain != nil {
f .Toolchain .Syntax .markRemoved ()
f .Toolchain = nil
}
}
func (f *File ) AddToolchainStmt (name string ) error {
if !ToolchainRE .MatchString (name ) {
return fmt .Errorf ("invalid toolchain name %q" , name )
}
if f .Toolchain == nil {
var hint Expr
if f .Go != nil && f .Go .Syntax != nil {
hint = f .Go .Syntax
} else if f .Module != nil && f .Module .Syntax != nil {
hint = f .Module .Syntax
}
f .Toolchain = &Toolchain {
Name : name ,
Syntax : f .Syntax .addLine (hint , "toolchain" , name ),
}
} else {
f .Toolchain .Name = name
f .Syntax .updateLine (f .Toolchain .Syntax , "toolchain" , name )
}
return nil
}
func (f *File ) AddGodebug (key , value string ) error {
need := true
for _ , g := range f .Godebug {
if g .Key == key {
if need {
g .Value = value
f .Syntax .updateLine (g .Syntax , "godebug" , key +"=" +value )
need = false
} else {
g .Syntax .markRemoved ()
*g = Godebug {}
}
}
}
if need {
f .addNewGodebug (key , value )
}
return nil
}
func (f *File ) addNewGodebug (key , value string ) {
line := f .Syntax .addLine (nil , "godebug" , key +"=" +value )
g := &Godebug {
Key : key ,
Value : value ,
Syntax : line ,
}
f .Godebug = append (f .Godebug , g )
}
func (f *File ) AddRequire (path , vers string ) error {
need := true
for _ , r := range f .Require {
if r .Mod .Path == path {
if need {
r .Mod .Version = vers
f .Syntax .updateLine (r .Syntax , "require" , AutoQuote (path ), vers )
need = false
} else {
r .Syntax .markRemoved ()
*r = Require {}
}
}
}
if need {
f .AddNewRequire (path , vers , false )
}
return nil
}
func (f *File ) AddNewRequire (path , vers string , indirect bool ) {
line := f .Syntax .addLine (nil , "require" , AutoQuote (path ), vers )
r := &Require {
Mod : module .Version {Path : path , Version : vers },
Syntax : line ,
}
r .setIndirect (indirect )
f .Require = append (f .Require , r )
}
func (f *File ) SetRequire (req []*Require ) {
type elem struct {
version string
indirect bool
}
need := make (map [string ]elem )
for _ , r := range req {
if prev , dup := need [r .Mod .Path ]; dup && prev .version != r .Mod .Version {
panic (fmt .Errorf ("SetRequire called with conflicting versions for path %s (%s and %s)" , r .Mod .Path , prev .version , r .Mod .Version ))
}
need [r .Mod .Path ] = elem {r .Mod .Version , r .Indirect }
}
for _ , r := range f .Require {
e , ok := need [r .Mod .Path ]
if ok {
r .setVersion (e .version )
r .setIndirect (e .indirect )
} else {
r .markRemoved ()
}
delete (need , r .Mod .Path )
}
for path , e := range need {
f .AddNewRequire (path , e .version , e .indirect )
}
f .SortBlocks ()
}
func (f *File ) SetRequireSeparateIndirect (req []*Require ) {
f .setRequireSeparateIndirect (req , false )
}
func (f *File ) SetRequireAtMostTwo (req []*Require ) {
f .setRequireSeparateIndirect (req , true )
}
func (f *File ) setRequireSeparateIndirect (req []*Require , simplify bool ) {
hasComments := func (c Comments ) bool {
return len (c .Before ) > 0 || len (c .After ) > 0 || len (c .Suffix ) > 1 ||
(len (c .Suffix ) == 1 &&
strings .TrimSpace (strings .TrimPrefix (c .Suffix [0 ].Token , string (slashSlash ))) != "indirect" )
}
moveReq := func (r *Require , block *LineBlock ) {
var line *Line
if r .Syntax == nil {
line = &Line {Token : []string {AutoQuote (r .Mod .Path ), r .Mod .Version }}
r .Syntax = line
if r .Indirect {
r .setIndirect (true )
}
} else {
line = new (Line )
*line = *r .Syntax
if !line .InBlock && len (line .Token ) > 0 && line .Token [0 ] == "require" {
line .Token = line .Token [1 :]
}
r .Syntax .Token = nil
r .Syntax = line
}
line .InBlock = true
block .Line = append (block .Line , line )
}
need := make (map [string ]*Require )
for _ , r := range req {
need [r .Mod .Path ] = r
}
lineIndirect := make (map [*Line ]bool )
for _ , r := range f .Require {
if n := need [r .Mod .Path ]; n != nil {
lineIndirect [r .Syntax ] = n .Indirect
}
}
var (
lastDirectIndex = -1
lastIndirectIndex = -1
lastRequireIndex = -1
requireLineOrBlockCount = 0
lineToBlock = make (map [*Line ]*LineBlock )
directBlockComments []Comment
indirectBlockComments []Comment
)
for i , stmt := range f .Syntax .Stmt {
switch stmt := stmt .(type ) {
case *Line :
if len (stmt .Token ) == 0 || stmt .Token [0 ] != "require" {
continue
}
lastRequireIndex = i
requireLineOrBlockCount ++
if !hasComments (stmt .Comments ) {
if isIndirect (stmt ) {
lastIndirectIndex = i
} else {
lastDirectIndex = i
}
}
case *LineBlock :
if len (stmt .Token ) == 0 || stmt .Token [0 ] != "require" {
continue
}
lastRequireIndex = i
requireLineOrBlockCount ++
allDirect := len (stmt .Line ) > 0 && !hasComments (stmt .Comments )
allIndirect := len (stmt .Line ) > 0 && !hasComments (stmt .Comments )
for _ , line := range stmt .Line {
lineToBlock [line ] = stmt
if hasComments (line .Comments ) {
allDirect = false
allIndirect = false
} else if isIndirect (line ) {
allDirect = false
} else {
allIndirect = false
}
}
if allDirect {
lastDirectIndex = i
}
if allIndirect {
lastIndirectIndex = i
}
if simplify {
anyDirect := false
for _ , line := range stmt .Line {
if ind , ok := lineIndirect [line ]; ok && !ind {
anyDirect = true
break
}
}
target := &directBlockComments
if !anyDirect && len (stmt .Line ) > 0 {
target = &indirectBlockComments
}
if len (*target ) > 0 && len (stmt .Comments .Before ) > 0 {
*target = append (*target , Comment {Token : "//" })
}
*target = append (*target , stmt .Comments .Before ...)
stmt .Comments .Before = nil
}
}
}
oneFlatUncommentedBlock := requireLineOrBlockCount == 1 &&
!hasComments (*f .Syntax .Stmt [lastRequireIndex ].Comment ())
insertBlock := func (i int ) *LineBlock {
block := &LineBlock {Token : []string {"require" }}
f .Syntax .Stmt = append (f .Syntax .Stmt , nil )
copy (f .Syntax .Stmt [i +1 :], f .Syntax .Stmt [i :])
f .Syntax .Stmt [i ] = block
return block
}
ensureBlock := func (i int ) *LineBlock {
switch stmt := f .Syntax .Stmt [i ].(type ) {
case *LineBlock :
return stmt
case *Line :
block := &LineBlock {
Token : []string {"require" },
Line : []*Line {stmt },
}
stmt .Token = stmt .Token [1 :]
stmt .InBlock = true
f .Syntax .Stmt [i ] = block
return block
default :
panic (fmt .Sprintf ("unexpected statement: %v" , stmt ))
}
}
var lastDirectBlock *LineBlock
if lastDirectIndex < 0 {
if lastIndirectIndex >= 0 {
lastDirectIndex = lastIndirectIndex
lastIndirectIndex ++
} else if lastRequireIndex >= 0 {
lastDirectIndex = lastRequireIndex + 1
} else {
lastDirectIndex = len (f .Syntax .Stmt )
}
lastDirectBlock = insertBlock (lastDirectIndex )
} else {
lastDirectBlock = ensureBlock (lastDirectIndex )
}
var lastIndirectBlock *LineBlock
if lastIndirectIndex < 0 {
lastIndirectIndex = lastDirectIndex + 1
lastIndirectBlock = insertBlock (lastIndirectIndex )
} else {
lastIndirectBlock = ensureBlock (lastIndirectIndex )
}
if simplify {
if len (directBlockComments ) > 0 {
lastDirectBlock .Comments .Before = append (lastDirectBlock .Comments .Before , directBlockComments ...)
}
if len (indirectBlockComments ) > 0 {
lastIndirectBlock .Comments .Before = append (lastIndirectBlock .Comments .Before , indirectBlockComments ...)
}
}
have := make (map [string ]*Require )
for _ , r := range f .Require {
path := r .Mod .Path
if need [path ] == nil || have [path ] != nil {
r .markRemoved ()
continue
}
have [r .Mod .Path ] = r
r .setVersion (need [path ].Mod .Version )
r .setIndirect (need [path ].Indirect )
if need [path ].Indirect &&
(simplify || oneFlatUncommentedBlock || lineToBlock [r .Syntax ] == lastDirectBlock ) {
moveReq (r , lastIndirectBlock )
} else if !need [path ].Indirect &&
(simplify || oneFlatUncommentedBlock || lineToBlock [r .Syntax ] == lastIndirectBlock ) {
moveReq (r , lastDirectBlock )
}
}
for path , r := range need {
if have [path ] == nil {
if r .Indirect {
moveReq (r , lastIndirectBlock )
} else {
moveReq (r , lastDirectBlock )
}
f .Require = append (f .Require , r )
}
}
f .SortBlocks ()
}
func (f *File ) DropGodebug (key string ) error {
for _ , g := range f .Godebug {
if g .Key == key {
g .Syntax .markRemoved ()
*g = Godebug {}
}
}
return nil
}
func (f *File ) DropRequire (path string ) error {
for _ , r := range f .Require {
if r .Mod .Path == path {
r .Syntax .markRemoved ()
*r = Require {}
}
}
return nil
}
func (f *File ) AddExclude (path , vers string ) error {
if err := checkCanonicalVersion (path , vers ); err != nil {
return err
}
var hint *Line
for _ , x := range f .Exclude {
if x .Mod .Path == path && x .Mod .Version == vers {
return nil
}
if x .Mod .Path == path {
hint = x .Syntax
}
}
f .Exclude = append (f .Exclude , &Exclude {Mod : module .Version {Path : path , Version : vers }, Syntax : f .Syntax .addLine (hint , "exclude" , AutoQuote (path ), vers )})
return nil
}
func (f *File ) DropExclude (path , vers string ) error {
for _ , x := range f .Exclude {
if x .Mod .Path == path && x .Mod .Version == vers {
x .Syntax .markRemoved ()
*x = Exclude {}
}
}
return nil
}
func (f *File ) AddReplace (oldPath , oldVers , newPath , newVers string ) error {
return addReplace (f .Syntax , &f .Replace , oldPath , oldVers , newPath , newVers )
}
func addReplace (syntax *FileSyntax , replace *[]*Replace , oldPath , oldVers , newPath , newVers string ) error {
need := true
old := module .Version {Path : oldPath , Version : oldVers }
new := module .Version {Path : newPath , Version : newVers }
tokens := []string {"replace" , AutoQuote (oldPath )}
if oldVers != "" {
tokens = append (tokens , oldVers )
}
tokens = append (tokens , "=>" , AutoQuote (newPath ))
if newVers != "" {
tokens = append (tokens , newVers )
}
var hint *Line
for _ , r := range *replace {
if r .Old .Path == oldPath && (oldVers == "" || r .Old .Version == oldVers ) {
if need {
r .New = new
syntax .updateLine (r .Syntax , tokens ...)
need = false
continue
}
r .Syntax .markRemoved ()
*r = Replace {}
}
if r .Old .Path == oldPath {
hint = r .Syntax
}
}
if need {
*replace = append (*replace , &Replace {Old : old , New : new , Syntax : syntax .addLine (hint , tokens ...)})
}
return nil
}
func (f *File ) DropReplace (oldPath , oldVers string ) error {
for _ , r := range f .Replace {
if r .Old .Path == oldPath && r .Old .Version == oldVers {
r .Syntax .markRemoved ()
*r = Replace {}
}
}
return nil
}
func (f *File ) AddRetract (vi VersionInterval , rationale string ) error {
var path string
if f .Module != nil {
path = f .Module .Mod .Path
}
if err := checkCanonicalVersion (path , vi .High ); err != nil {
return err
}
if err := checkCanonicalVersion (path , vi .Low ); err != nil {
return err
}
r := &Retract {
VersionInterval : vi ,
}
if vi .Low == vi .High {
r .Syntax = f .Syntax .addLine (nil , "retract" , AutoQuote (vi .Low ))
} else {
r .Syntax = f .Syntax .addLine (nil , "retract" , "[" , AutoQuote (vi .Low ), "," , AutoQuote (vi .High ), "]" )
}
if rationale != "" {
for line := range strings .SplitSeq (rationale , "\n" ) {
com := Comment {Token : "// " + line }
r .Syntax .Comment ().Before = append (r .Syntax .Comment ().Before , com )
}
}
return nil
}
func (f *File ) DropRetract (vi VersionInterval ) error {
for _ , r := range f .Retract {
if r .VersionInterval == vi {
r .Syntax .markRemoved ()
*r = Retract {}
}
}
return nil
}
func (f *File ) AddTool (path string ) error {
for _ , t := range f .Tool {
if t .Path == path {
return nil
}
}
f .Tool = append (f .Tool , &Tool {
Path : path ,
Syntax : f .Syntax .addLine (nil , "tool" , path ),
})
f .SortBlocks ()
return nil
}
func (f *File ) DropTool (path string ) error {
for _ , t := range f .Tool {
if t .Path == path {
t .Syntax .markRemoved ()
*t = Tool {}
}
}
return nil
}
func (f *File ) AddIgnore (path string ) error {
for _ , t := range f .Ignore {
if t .Path == path {
return nil
}
}
f .Ignore = append (f .Ignore , &Ignore {
Path : path ,
Syntax : f .Syntax .addLine (nil , "ignore" , path ),
})
f .SortBlocks ()
return nil
}
func (f *File ) DropIgnore (path string ) error {
for _ , t := range f .Ignore {
if t .Path == path {
t .Syntax .markRemoved ()
*t = Ignore {}
}
}
return nil
}
func (f *File ) SortBlocks () {
f .removeDups ()
const semanticSortForExcludeVersionV = "v1.21"
useSemanticSortForExclude := f .Go != nil && semver .Compare ("v" +f .Go .Version , semanticSortForExcludeVersionV ) >= 0
for _ , stmt := range f .Syntax .Stmt {
block , ok := stmt .(*LineBlock )
if !ok {
continue
}
less := compareLine
if block .Token [0 ] == "exclude" && useSemanticSortForExclude {
less = compareLineExclude
} else if block .Token [0 ] == "retract" {
less = compareLineRetract
}
slices .SortStableFunc (block .Line , less )
}
}
func (f *File ) removeDups () {
removeDups (f .Syntax , &f .Exclude , &f .Replace , &f .Tool , &f .Ignore )
}
func removeDups (syntax *FileSyntax , exclude *[]*Exclude , replace *[]*Replace , tool *[]*Tool , ignore *[]*Ignore ) {
kill := make (map [*Line ]bool )
if exclude != nil {
haveExclude := make (map [module .Version ]bool )
for _ , x := range *exclude {
if haveExclude [x .Mod ] {
kill [x .Syntax ] = true
continue
}
haveExclude [x .Mod ] = true
}
var excl []*Exclude
for _ , x := range *exclude {
if !kill [x .Syntax ] {
excl = append (excl , x )
}
}
*exclude = excl
}
haveReplace := make (map [module .Version ]bool )
for _ , x := range slices .Backward (*replace ) {
if haveReplace [x .Old ] {
kill [x .Syntax ] = true
continue
}
haveReplace [x .Old ] = true
}
var repl []*Replace
for _ , x := range *replace {
if !kill [x .Syntax ] {
repl = append (repl , x )
}
}
*replace = repl
if tool != nil {
haveTool := make (map [string ]bool )
for _ , t := range *tool {
if haveTool [t .Path ] {
kill [t .Syntax ] = true
continue
}
haveTool [t .Path ] = true
}
var newTool []*Tool
for _ , t := range *tool {
if !kill [t .Syntax ] {
newTool = append (newTool , t )
}
}
*tool = newTool
}
if ignore != nil {
haveIgnore := make (map [string ]bool )
for _ , i := range *ignore {
if haveIgnore [i .Path ] {
kill [i .Syntax ] = true
continue
}
haveIgnore [i .Path ] = true
}
var newIgnore []*Ignore
for _ , i := range *ignore {
if !kill [i .Syntax ] {
newIgnore = append (newIgnore , i )
}
}
*ignore = newIgnore
}
var stmts []Expr
for _ , stmt := range syntax .Stmt {
switch stmt := stmt .(type ) {
case *Line :
if kill [stmt ] {
continue
}
case *LineBlock :
var lines []*Line
for _ , line := range stmt .Line {
if !kill [line ] {
lines = append (lines , line )
}
}
stmt .Line = lines
if len (lines ) == 0 {
continue
}
}
stmts = append (stmts , stmt )
}
syntax .Stmt = stmts
}
func compareLine (li , lj *Line ) int {
for k := 0 ; k < len (li .Token ) && k < len (lj .Token ); k ++ {
if li .Token [k ] != lj .Token [k ] {
return cmp .Compare (li .Token [k ], lj .Token [k ])
}
}
return cmp .Compare (len (li .Token ), len (lj .Token ))
}
func compareLineExclude (li , lj *Line ) int {
if len (li .Token ) != 2 || len (lj .Token ) != 2 {
return compareLine (li , lj )
}
if pi , pj := li .Token [0 ], lj .Token [0 ]; pi != pj {
return cmp .Compare (pi , pj )
}
return semver .Compare (li .Token [1 ], lj .Token [1 ])
}
func compareLineRetract (li , lj *Line ) int {
interval := func (l *Line ) VersionInterval {
if len (l .Token ) == 1 {
return VersionInterval {Low : l .Token [0 ], High : l .Token [0 ]}
} else if len (l .Token ) == 5 && l .Token [0 ] == "[" && l .Token [2 ] == "," && l .Token [4 ] == "]" {
return VersionInterval {Low : l .Token [1 ], High : l .Token [3 ]}
} else {
return VersionInterval {}
}
}
vii := interval (li )
vij := interval (lj )
if cmp := semver .Compare (vii .Low , vij .Low ); cmp != 0 {
return -cmp
}
return -semver .Compare (vii .High , vij .High )
}
func checkCanonicalVersion (path , vers string ) error {
_ , pathMajor , pathMajorOk := module .SplitPathVersion (path )
if vers == "" || vers != module .CanonicalVersion (vers ) {
if pathMajor == "" {
return &module .InvalidVersionError {
Version : vers ,
Err : fmt .Errorf ("must be of the form v1.2.3" ),
}
}
return &module .InvalidVersionError {
Version : vers ,
Err : fmt .Errorf ("must be of the form %s.2.3" , module .PathMajorPrefix (pathMajor )),
}
}
if pathMajorOk {
if err := module .CheckPathMajor (vers , pathMajor ); err != nil {
if pathMajor == "" {
return &module .InvalidVersionError {
Version : vers ,
Err : fmt .Errorf ("should be %s+incompatible (or module %s/%v)" , vers , path , semver .Major (vers )),
}
}
return err
}
}
return nil
}