1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
17 "golang.org/x/mod/internal/lazyregexp"
18 "golang.org/x/mod/module"
21 // A File is the parsed, interpreted form of a go.mod file.
32 // A Module is the module statement.
38 // A Go is the go statement.
40 Version string // "1.23"
44 // A Require is a single require statement.
47 Indirect bool // has "// indirect" comment
51 // An Exclude is a single exclude statement.
57 // A Replace is a single replace statement.
64 func (f *File) AddModuleStmt(path string) error {
66 f.Syntax = new(FileSyntax)
70 Mod: module.Version{Path: path},
71 Syntax: f.Syntax.addLine(nil, "module", AutoQuote(path)),
74 f.Module.Mod.Path = path
75 f.Syntax.updateLine(f.Module.Syntax, "module", AutoQuote(path))
80 func (f *File) AddComment(text string) {
82 f.Syntax = new(FileSyntax)
84 f.Syntax.Stmt = append(f.Syntax.Stmt, &CommentBlock{
95 type VersionFixer func(path, version string) (string, error)
97 // Parse parses the data, reported in errors as being from file,
98 // into a File struct. It applies fix, if non-nil, to canonicalize all module versions found.
99 func Parse(file string, data []byte, fix VersionFixer) (*File, error) {
100 return parseToFile(file, data, fix, true)
103 // ParseLax is like Parse but ignores unknown statements.
104 // It is used when parsing go.mod files other than the main module,
105 // under the theory that most statement types we add in the future will
106 // only apply in the main module, like exclude and replace,
107 // and so we get better gradual deployments if old go commands
108 // simply ignore those statements when found in go.mod files
110 func ParseLax(file string, data []byte, fix VersionFixer) (*File, error) {
111 return parseToFile(file, data, fix, false)
114 func parseToFile(file string, data []byte, fix VersionFixer, strict bool) (*File, error) {
115 fs, err := parse(file, data)
123 var errs bytes.Buffer
124 for _, x := range fs.Stmt {
125 switch x := x.(type) {
127 f.add(&errs, x, x.Token[0], x.Token[1:], fix, strict)
130 if len(x.Token) > 1 {
132 fmt.Fprintf(&errs, "%s:%d: unknown block type: %s\n", file, x.Start.Line, strings.Join(x.Token, " "))
139 fmt.Fprintf(&errs, "%s:%d: unknown block type: %s\n", file, x.Start.Line, strings.Join(x.Token, " "))
142 case "module", "require", "exclude", "replace":
143 for _, l := range x.Line {
144 f.add(&errs, l, x.Token[0], l.Token, fix, strict)
151 return nil, errors.New(strings.TrimRight(errs.String(), "\n"))
156 var GoVersionRE = lazyregexp.New(`^([1-9][0-9]*)\.(0|[1-9][0-9]*)$`)
158 func (f *File) add(errs *bytes.Buffer, line *Line, verb string, args []string, fix VersionFixer, strict bool) {
159 // If strict is false, this module is a dependency.
160 // We ignore all unknown directives as well as main-module-only
161 // directives like replace and exclude. It will work better for
162 // forward compatibility if we can depend on modules that have unknown
163 // statements (presumed relevant only when acting as the main module)
164 // and simply ignore those statements.
167 case "module", "require", "go":
168 // want these even for dependency go.mods
176 fmt.Fprintf(errs, "%s:%d: unknown directive: %s\n", f.Syntax.Name, line.Start.Line, verb)
180 fmt.Fprintf(errs, "%s:%d: repeated go statement\n", f.Syntax.Name, line.Start.Line)
183 if len(args) != 1 || !GoVersionRE.MatchString(args[0]) {
184 fmt.Fprintf(errs, "%s:%d: usage: go 1.23\n", f.Syntax.Name, line.Start.Line)
187 f.Go = &Go{Syntax: line}
188 f.Go.Version = args[0]
191 fmt.Fprintf(errs, "%s:%d: repeated module statement\n", f.Syntax.Name, line.Start.Line)
194 f.Module = &Module{Syntax: line}
197 fmt.Fprintf(errs, "%s:%d: usage: module module/path\n", f.Syntax.Name, line.Start.Line)
200 s, err := parseString(&args[0])
202 fmt.Fprintf(errs, "%s:%d: invalid quoted string: %v\n", f.Syntax.Name, line.Start.Line, err)
205 f.Module.Mod = module.Version{Path: s}
206 case "require", "exclude":
208 fmt.Fprintf(errs, "%s:%d: usage: %s module/path v1.2.3\n", f.Syntax.Name, line.Start.Line, verb)
211 s, err := parseString(&args[0])
213 fmt.Fprintf(errs, "%s:%d: invalid quoted string: %v\n", f.Syntax.Name, line.Start.Line, err)
216 v, err := parseVersion(verb, s, &args[1], fix)
218 fmt.Fprintf(errs, "%s:%d: %v\n", f.Syntax.Name, line.Start.Line, err)
221 pathMajor, err := modulePathMajor(s)
223 fmt.Fprintf(errs, "%s:%d: %v\n", f.Syntax.Name, line.Start.Line, err)
226 if err := module.CheckPathMajor(v, pathMajor); err != nil {
227 fmt.Fprintf(errs, "%s:%d: %v\n", f.Syntax.Name, line.Start.Line, &Error{Verb: verb, ModPath: s, Err: err})
230 if verb == "require" {
231 f.Require = append(f.Require, &Require{
232 Mod: module.Version{Path: s, Version: v},
234 Indirect: isIndirect(line),
237 f.Exclude = append(f.Exclude, &Exclude{
238 Mod: module.Version{Path: s, Version: v},
244 if len(args) >= 2 && args[1] == "=>" {
247 if len(args) < arrow+2 || len(args) > arrow+3 || args[arrow] != "=>" {
248 fmt.Fprintf(errs, "%s:%d: usage: %s module/path [v1.2.3] => other/module v1.4\n\t or %s module/path [v1.2.3] => ../local/directory\n", f.Syntax.Name, line.Start.Line, verb, verb)
251 s, err := parseString(&args[0])
253 fmt.Fprintf(errs, "%s:%d: invalid quoted string: %v\n", f.Syntax.Name, line.Start.Line, err)
256 pathMajor, err := modulePathMajor(s)
258 fmt.Fprintf(errs, "%s:%d: %v\n", f.Syntax.Name, line.Start.Line, err)
263 v, err = parseVersion(verb, s, &args[1], fix)
265 fmt.Fprintf(errs, "%s:%d: %v\n", f.Syntax.Name, line.Start.Line, err)
268 if err := module.CheckPathMajor(v, pathMajor); err != nil {
269 fmt.Fprintf(errs, "%s:%d: %v\n", f.Syntax.Name, line.Start.Line, &Error{Verb: verb, ModPath: s, Err: err})
273 ns, err := parseString(&args[arrow+1])
275 fmt.Fprintf(errs, "%s:%d: invalid quoted string: %v\n", f.Syntax.Name, line.Start.Line, err)
279 if len(args) == arrow+2 {
280 if !IsDirectoryPath(ns) {
281 fmt.Fprintf(errs, "%s:%d: replacement module without version must be directory path (rooted or starting with ./ or ../)\n", f.Syntax.Name, line.Start.Line)
284 if filepath.Separator == '/' && strings.Contains(ns, `\`) {
285 fmt.Fprintf(errs, "%s:%d: replacement directory appears to be Windows path (on a non-windows system)\n", f.Syntax.Name, line.Start.Line)
289 if len(args) == arrow+3 {
290 nv, err = parseVersion(verb, ns, &args[arrow+2], fix)
292 fmt.Fprintf(errs, "%s:%d: %v\n", f.Syntax.Name, line.Start.Line, err)
295 if IsDirectoryPath(ns) {
296 fmt.Fprintf(errs, "%s:%d: replacement module directory path %q cannot have version\n", f.Syntax.Name, line.Start.Line, ns)
300 f.Replace = append(f.Replace, &Replace{
301 Old: module.Version{Path: s, Version: v},
302 New: module.Version{Path: ns, Version: nv},
308 // isIndirect reports whether line has a "// indirect" comment,
309 // meaning it is in go.mod only for its effect on indirect dependencies,
310 // so that it can be dropped entirely once the effective version of the
311 // indirect dependency reaches the given minimum version.
312 func isIndirect(line *Line) bool {
313 if len(line.Suffix) == 0 {
316 f := strings.Fields(strings.TrimPrefix(line.Suffix[0].Token, string(slashSlash)))
317 return (len(f) == 1 && f[0] == "indirect" || len(f) > 1 && f[0] == "indirect;")
320 // setIndirect sets line to have (or not have) a "// indirect" comment.
321 func setIndirect(line *Line, indirect bool) {
322 if isIndirect(line) == indirect {
327 if len(line.Suffix) == 0 {
329 line.Suffix = []Comment{{Token: "// indirect", Suffix: true}}
333 com := &line.Suffix[0]
334 text := strings.TrimSpace(strings.TrimPrefix(com.Token, string(slashSlash)))
337 com.Token = "// indirect"
341 // Insert at beginning of existing comment.
342 com.Token = "// indirect; " + text
347 f := strings.Fields(line.Suffix[0].Token)
349 // Remove whole comment.
354 // Remove comment prefix.
355 com := &line.Suffix[0]
356 i := strings.Index(com.Token, "indirect;")
357 com.Token = "//" + com.Token[i+len("indirect;"):]
360 // IsDirectoryPath reports whether the given path should be interpreted
361 // as a directory path. Just like on the go command line, relative paths
362 // and rooted paths are directory paths; the rest are module paths.
363 func IsDirectoryPath(ns string) bool {
364 // Because go.mod files can move from one system to another,
365 // we check all known path syntaxes, both Unix and Windows.
366 return strings.HasPrefix(ns, "./") || strings.HasPrefix(ns, "../") || strings.HasPrefix(ns, "/") ||
367 strings.HasPrefix(ns, `.\`) || strings.HasPrefix(ns, `..\`) || strings.HasPrefix(ns, `\`) ||
368 len(ns) >= 2 && ('A' <= ns[0] && ns[0] <= 'Z' || 'a' <= ns[0] && ns[0] <= 'z') && ns[1] == ':'
371 // MustQuote reports whether s must be quoted in order to appear as
372 // a single token in a go.mod line.
373 func MustQuote(s string) bool {
374 for _, r := range s {
375 if !unicode.IsPrint(r) || r == ' ' || r == '"' || r == '\'' || r == '`' {
379 return s == "" || strings.Contains(s, "//") || strings.Contains(s, "/*")
382 // AutoQuote returns s or, if quoting is required for s to appear in a go.mod,
383 // the quotation of s.
384 func AutoQuote(s string) string {
386 return strconv.Quote(s)
391 func parseString(s *string) (string, error) {
393 if strings.HasPrefix(t, `"`) {
395 if t, err = strconv.Unquote(t); err != nil {
398 } else if strings.ContainsAny(t, "\"'`") {
399 // Other quotes are reserved both for possible future expansion
400 // and to avoid confusion. For example if someone types 'x'
401 // we want that to be a syntax error and not a literal x in literal quotation marks.
402 return "", fmt.Errorf("unquoted string cannot contain quote")
414 func (e *Error) Error() string {
415 return fmt.Sprintf("%s %s: %v", e.Verb, e.ModPath, e.Err)
418 func (e *Error) Unwrap() error { return e.Err }
420 func parseVersion(verb string, path string, s *string, fix VersionFixer) (string, error) {
421 t, err := parseString(s)
426 Err: &module.InvalidVersionError{
434 t, err = fix(path, t)
436 if err, ok := err.(*module.ModuleError); ok {
446 if v := module.CanonicalVersion(t); v != "" {
453 Err: &module.InvalidVersionError{
455 Err: errors.New("must be of the form v1.2.3"),
460 func modulePathMajor(path string) (string, error) {
461 _, major, ok := module.SplitPathVersion(path)
463 return "", fmt.Errorf("invalid module path")
468 func (f *File) Format() ([]byte, error) {
469 return Format(f.Syntax), nil
472 // Cleanup cleans up the file f after any edit operations.
473 // To avoid quadratic behavior, modifications like DropRequire
474 // clear the entry but do not remove it from the slice.
475 // Cleanup cleans out all the cleared entries.
476 func (f *File) Cleanup() {
478 for _, r := range f.Require {
479 if r.Mod.Path != "" {
484 f.Require = f.Require[:w]
487 for _, x := range f.Exclude {
488 if x.Mod.Path != "" {
493 f.Exclude = f.Exclude[:w]
496 for _, r := range f.Replace {
497 if r.Old.Path != "" {
502 f.Replace = f.Replace[:w]
507 func (f *File) AddGoStmt(version string) error {
508 if !GoVersionRE.MatchString(version) {
509 return fmt.Errorf("invalid language version string %q", version)
513 if f.Module != nil && f.Module.Syntax != nil {
514 hint = f.Module.Syntax
518 Syntax: f.Syntax.addLine(hint, "go", version),
521 f.Go.Version = version
522 f.Syntax.updateLine(f.Go.Syntax, "go", version)
527 func (f *File) AddRequire(path, vers string) error {
529 for _, r := range f.Require {
530 if r.Mod.Path == path {
533 f.Syntax.updateLine(r.Syntax, "require", AutoQuote(path), vers)
536 f.Syntax.removeLine(r.Syntax)
543 f.AddNewRequire(path, vers, false)
548 func (f *File) AddNewRequire(path, vers string, indirect bool) {
549 line := f.Syntax.addLine(nil, "require", AutoQuote(path), vers)
550 setIndirect(line, indirect)
551 f.Require = append(f.Require, &Require{module.Version{Path: path, Version: vers}, indirect, line})
554 func (f *File) SetRequire(req []*Require) {
555 need := make(map[string]string)
556 indirect := make(map[string]bool)
557 for _, r := range req {
558 need[r.Mod.Path] = r.Mod.Version
559 indirect[r.Mod.Path] = r.Indirect
562 for _, r := range f.Require {
563 if v, ok := need[r.Mod.Path]; ok {
565 r.Indirect = indirect[r.Mod.Path]
572 for _, stmt := range f.Syntax.Stmt {
573 switch stmt := stmt.(type) {
575 if len(stmt.Token) > 0 && stmt.Token[0] == "require" {
577 for _, line := range stmt.Line {
578 if p, err := parseString(&line.Token[0]); err == nil && need[p] != "" {
579 if len(line.Comments.Before) == 1 && len(line.Comments.Before[0].Token) == 0 {
580 line.Comments.Before = line.Comments.Before[:0]
582 line.Token[1] = need[p]
584 setIndirect(line, indirect[p])
585 newLines = append(newLines, line)
588 if len(newLines) == 0 {
589 continue // drop stmt
595 if len(stmt.Token) > 0 && stmt.Token[0] == "require" {
596 if p, err := parseString(&stmt.Token[1]); err == nil && need[p] != "" {
597 stmt.Token[2] = need[p]
599 setIndirect(stmt, indirect[p])
601 continue // drop stmt
605 newStmts = append(newStmts, stmt)
607 f.Syntax.Stmt = newStmts
609 for path, vers := range need {
610 f.AddNewRequire(path, vers, indirect[path])
615 func (f *File) DropRequire(path string) error {
616 for _, r := range f.Require {
617 if r.Mod.Path == path {
618 f.Syntax.removeLine(r.Syntax)
625 func (f *File) AddExclude(path, vers string) error {
627 for _, x := range f.Exclude {
628 if x.Mod.Path == path && x.Mod.Version == vers {
631 if x.Mod.Path == path {
636 f.Exclude = append(f.Exclude, &Exclude{Mod: module.Version{Path: path, Version: vers}, Syntax: f.Syntax.addLine(hint, "exclude", AutoQuote(path), vers)})
640 func (f *File) DropExclude(path, vers string) error {
641 for _, x := range f.Exclude {
642 if x.Mod.Path == path && x.Mod.Version == vers {
643 f.Syntax.removeLine(x.Syntax)
650 func (f *File) AddReplace(oldPath, oldVers, newPath, newVers string) error {
652 old := module.Version{Path: oldPath, Version: oldVers}
653 new := module.Version{Path: newPath, Version: newVers}
654 tokens := []string{"replace", AutoQuote(oldPath)}
656 tokens = append(tokens, oldVers)
658 tokens = append(tokens, "=>", AutoQuote(newPath))
660 tokens = append(tokens, newVers)
664 for _, r := range f.Replace {
665 if r.Old.Path == oldPath && (oldVers == "" || r.Old.Version == oldVers) {
667 // Found replacement for old; update to use new.
669 f.Syntax.updateLine(r.Syntax, tokens...)
673 // Already added; delete other replacements for same.
674 f.Syntax.removeLine(r.Syntax)
677 if r.Old.Path == oldPath {
682 f.Replace = append(f.Replace, &Replace{Old: old, New: new, Syntax: f.Syntax.addLine(hint, tokens...)})
687 func (f *File) DropReplace(oldPath, oldVers string) error {
688 for _, r := range f.Replace {
689 if r.Old.Path == oldPath && r.Old.Version == oldVers {
690 f.Syntax.removeLine(r.Syntax)
697 func (f *File) SortBlocks() {
698 f.removeDups() // otherwise sorting is unsafe
700 for _, stmt := range f.Syntax.Stmt {
701 block, ok := stmt.(*LineBlock)
705 sort.Slice(block.Line, func(i, j int) bool {
708 for k := 0; k < len(li.Token) && k < len(lj.Token); k++ {
709 if li.Token[k] != lj.Token[k] {
710 return li.Token[k] < lj.Token[k]
713 return len(li.Token) < len(lj.Token)
718 func (f *File) removeDups() {
719 have := make(map[module.Version]bool)
720 kill := make(map[*Line]bool)
721 for _, x := range f.Exclude {
723 kill[x.Syntax] = true
729 for _, x := range f.Exclude {
731 excl = append(excl, x)
736 have = make(map[module.Version]bool)
737 // Later replacements take priority over earlier ones.
738 for i := len(f.Replace) - 1; i >= 0; i-- {
741 kill[x.Syntax] = true
747 for _, x := range f.Replace {
749 repl = append(repl, x)
755 for _, stmt := range f.Syntax.Stmt {
756 switch stmt := stmt.(type) {
763 for _, line := range stmt.Line {
765 lines = append(lines, line)
773 stmts = append(stmts, stmt)
775 f.Syntax.Stmt = stmts