rule.go 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663
  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.
  4. // Package modfile implements a parser and formatter for go.mod files.
  5. //
  6. // The go.mod syntax is described in
  7. // https://golang.org/cmd/go/#hdr-The_go_mod_file.
  8. //
  9. // The Parse and ParseLax functions both parse a go.mod file and return an
  10. // abstract syntax tree. ParseLax ignores unknown statements and may be used to
  11. // parse go.mod files that may have been developed with newer versions of Go.
  12. //
  13. // The File struct returned by Parse and ParseLax represent an abstract
  14. // go.mod file. File has several methods like AddNewRequire and DropReplace
  15. // that can be used to programmatically edit a file.
  16. //
  17. // The Format function formats a File back to a byte slice which can be
  18. // written to a file.
  19. package modfile
  20. import (
  21. "errors"
  22. "fmt"
  23. "path/filepath"
  24. "sort"
  25. "strconv"
  26. "strings"
  27. "unicode"
  28. "golang.org/x/mod/internal/lazyregexp"
  29. "golang.org/x/mod/module"
  30. "golang.org/x/mod/semver"
  31. )
  32. // A File is the parsed, interpreted form of a go.mod file.
  33. type File struct {
  34. Module *Module
  35. Go *Go
  36. Toolchain *Toolchain
  37. Require []*Require
  38. Exclude []*Exclude
  39. Replace []*Replace
  40. Retract []*Retract
  41. Syntax *FileSyntax
  42. }
  43. // A Module is the module statement.
  44. type Module struct {
  45. Mod module.Version
  46. Deprecated string
  47. Syntax *Line
  48. }
  49. // A Go is the go statement.
  50. type Go struct {
  51. Version string // "1.23"
  52. Syntax *Line
  53. }
  54. // A Toolchain is the toolchain statement.
  55. type Toolchain struct {
  56. Name string // "go1.21rc1"
  57. Syntax *Line
  58. }
  59. // An Exclude is a single exclude statement.
  60. type Exclude struct {
  61. Mod module.Version
  62. Syntax *Line
  63. }
  64. // A Replace is a single replace statement.
  65. type Replace struct {
  66. Old module.Version
  67. New module.Version
  68. Syntax *Line
  69. }
  70. // A Retract is a single retract statement.
  71. type Retract struct {
  72. VersionInterval
  73. Rationale string
  74. Syntax *Line
  75. }
  76. // A VersionInterval represents a range of versions with upper and lower bounds.
  77. // Intervals are closed: both bounds are included. When Low is equal to High,
  78. // the interval may refer to a single version ('v1.2.3') or an interval
  79. // ('[v1.2.3, v1.2.3]'); both have the same representation.
  80. type VersionInterval struct {
  81. Low, High string
  82. }
  83. // A Require is a single require statement.
  84. type Require struct {
  85. Mod module.Version
  86. Indirect bool // has "// indirect" comment
  87. Syntax *Line
  88. }
  89. func (r *Require) markRemoved() {
  90. r.Syntax.markRemoved()
  91. *r = Require{}
  92. }
  93. func (r *Require) setVersion(v string) {
  94. r.Mod.Version = v
  95. if line := r.Syntax; len(line.Token) > 0 {
  96. if line.InBlock {
  97. // If the line is preceded by an empty line, remove it; see
  98. // https://golang.org/issue/33779.
  99. if len(line.Comments.Before) == 1 && len(line.Comments.Before[0].Token) == 0 {
  100. line.Comments.Before = line.Comments.Before[:0]
  101. }
  102. if len(line.Token) >= 2 { // example.com v1.2.3
  103. line.Token[1] = v
  104. }
  105. } else {
  106. if len(line.Token) >= 3 { // require example.com v1.2.3
  107. line.Token[2] = v
  108. }
  109. }
  110. }
  111. }
  112. // setIndirect sets line to have (or not have) a "// indirect" comment.
  113. func (r *Require) setIndirect(indirect bool) {
  114. r.Indirect = indirect
  115. line := r.Syntax
  116. if isIndirect(line) == indirect {
  117. return
  118. }
  119. if indirect {
  120. // Adding comment.
  121. if len(line.Suffix) == 0 {
  122. // New comment.
  123. line.Suffix = []Comment{{Token: "// indirect", Suffix: true}}
  124. return
  125. }
  126. com := &line.Suffix[0]
  127. text := strings.TrimSpace(strings.TrimPrefix(com.Token, string(slashSlash)))
  128. if text == "" {
  129. // Empty comment.
  130. com.Token = "// indirect"
  131. return
  132. }
  133. // Insert at beginning of existing comment.
  134. com.Token = "// indirect; " + text
  135. return
  136. }
  137. // Removing comment.
  138. f := strings.TrimSpace(strings.TrimPrefix(line.Suffix[0].Token, string(slashSlash)))
  139. if f == "indirect" {
  140. // Remove whole comment.
  141. line.Suffix = nil
  142. return
  143. }
  144. // Remove comment prefix.
  145. com := &line.Suffix[0]
  146. i := strings.Index(com.Token, "indirect;")
  147. com.Token = "//" + com.Token[i+len("indirect;"):]
  148. }
  149. // isIndirect reports whether line has a "// indirect" comment,
  150. // meaning it is in go.mod only for its effect on indirect dependencies,
  151. // so that it can be dropped entirely once the effective version of the
  152. // indirect dependency reaches the given minimum version.
  153. func isIndirect(line *Line) bool {
  154. if len(line.Suffix) == 0 {
  155. return false
  156. }
  157. f := strings.Fields(strings.TrimPrefix(line.Suffix[0].Token, string(slashSlash)))
  158. return (len(f) == 1 && f[0] == "indirect" || len(f) > 1 && f[0] == "indirect;")
  159. }
  160. func (f *File) AddModuleStmt(path string) error {
  161. if f.Syntax == nil {
  162. f.Syntax = new(FileSyntax)
  163. }
  164. if f.Module == nil {
  165. f.Module = &Module{
  166. Mod: module.Version{Path: path},
  167. Syntax: f.Syntax.addLine(nil, "module", AutoQuote(path)),
  168. }
  169. } else {
  170. f.Module.Mod.Path = path
  171. f.Syntax.updateLine(f.Module.Syntax, "module", AutoQuote(path))
  172. }
  173. return nil
  174. }
  175. func (f *File) AddComment(text string) {
  176. if f.Syntax == nil {
  177. f.Syntax = new(FileSyntax)
  178. }
  179. f.Syntax.Stmt = append(f.Syntax.Stmt, &CommentBlock{
  180. Comments: Comments{
  181. Before: []Comment{
  182. {
  183. Token: text,
  184. },
  185. },
  186. },
  187. })
  188. }
  189. type VersionFixer func(path, version string) (string, error)
  190. // errDontFix is returned by a VersionFixer to indicate the version should be
  191. // left alone, even if it's not canonical.
  192. var dontFixRetract VersionFixer = func(_, vers string) (string, error) {
  193. return vers, nil
  194. }
  195. // Parse parses and returns a go.mod file.
  196. //
  197. // file is the name of the file, used in positions and errors.
  198. //
  199. // data is the content of the file.
  200. //
  201. // fix is an optional function that canonicalizes module versions.
  202. // If fix is nil, all module versions must be canonical (module.CanonicalVersion
  203. // must return the same string).
  204. func Parse(file string, data []byte, fix VersionFixer) (*File, error) {
  205. return parseToFile(file, data, fix, true)
  206. }
  207. // ParseLax is like Parse but ignores unknown statements.
  208. // It is used when parsing go.mod files other than the main module,
  209. // under the theory that most statement types we add in the future will
  210. // only apply in the main module, like exclude and replace,
  211. // and so we get better gradual deployments if old go commands
  212. // simply ignore those statements when found in go.mod files
  213. // in dependencies.
  214. func ParseLax(file string, data []byte, fix VersionFixer) (*File, error) {
  215. return parseToFile(file, data, fix, false)
  216. }
  217. func parseToFile(file string, data []byte, fix VersionFixer, strict bool) (parsed *File, err error) {
  218. fs, err := parse(file, data)
  219. if err != nil {
  220. return nil, err
  221. }
  222. f := &File{
  223. Syntax: fs,
  224. }
  225. var errs ErrorList
  226. // fix versions in retract directives after the file is parsed.
  227. // We need the module path to fix versions, and it might be at the end.
  228. defer func() {
  229. oldLen := len(errs)
  230. f.fixRetract(fix, &errs)
  231. if len(errs) > oldLen {
  232. parsed, err = nil, errs
  233. }
  234. }()
  235. for _, x := range fs.Stmt {
  236. switch x := x.(type) {
  237. case *Line:
  238. f.add(&errs, nil, x, x.Token[0], x.Token[1:], fix, strict)
  239. case *LineBlock:
  240. if len(x.Token) > 1 {
  241. if strict {
  242. errs = append(errs, Error{
  243. Filename: file,
  244. Pos: x.Start,
  245. Err: fmt.Errorf("unknown block type: %s", strings.Join(x.Token, " ")),
  246. })
  247. }
  248. continue
  249. }
  250. switch x.Token[0] {
  251. default:
  252. if strict {
  253. errs = append(errs, Error{
  254. Filename: file,
  255. Pos: x.Start,
  256. Err: fmt.Errorf("unknown block type: %s", strings.Join(x.Token, " ")),
  257. })
  258. }
  259. continue
  260. case "module", "require", "exclude", "replace", "retract":
  261. for _, l := range x.Line {
  262. f.add(&errs, x, l, x.Token[0], l.Token, fix, strict)
  263. }
  264. }
  265. }
  266. }
  267. if len(errs) > 0 {
  268. return nil, errs
  269. }
  270. return f, nil
  271. }
  272. var GoVersionRE = lazyregexp.New(`^([1-9][0-9]*)\.(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))?([a-z]+[0-9]+)?$`)
  273. var laxGoVersionRE = lazyregexp.New(`^v?(([1-9][0-9]*)\.(0|[1-9][0-9]*))([^0-9].*)$`)
  274. // Toolchains must be named beginning with `go1`,
  275. // like "go1.20.3" or "go1.20.3-gccgo". As a special case, "default" is also permitted.
  276. var ToolchainRE = lazyregexp.New(`^default$|^go1($|\.)`)
  277. func (f *File) add(errs *ErrorList, block *LineBlock, line *Line, verb string, args []string, fix VersionFixer, strict bool) {
  278. // If strict is false, this module is a dependency.
  279. // We ignore all unknown directives as well as main-module-only
  280. // directives like replace and exclude. It will work better for
  281. // forward compatibility if we can depend on modules that have unknown
  282. // statements (presumed relevant only when acting as the main module)
  283. // and simply ignore those statements.
  284. if !strict {
  285. switch verb {
  286. case "go", "module", "retract", "require":
  287. // want these even for dependency go.mods
  288. default:
  289. return
  290. }
  291. }
  292. wrapModPathError := func(modPath string, err error) {
  293. *errs = append(*errs, Error{
  294. Filename: f.Syntax.Name,
  295. Pos: line.Start,
  296. ModPath: modPath,
  297. Verb: verb,
  298. Err: err,
  299. })
  300. }
  301. wrapError := func(err error) {
  302. *errs = append(*errs, Error{
  303. Filename: f.Syntax.Name,
  304. Pos: line.Start,
  305. Err: err,
  306. })
  307. }
  308. errorf := func(format string, args ...interface{}) {
  309. wrapError(fmt.Errorf(format, args...))
  310. }
  311. switch verb {
  312. default:
  313. errorf("unknown directive: %s", verb)
  314. case "go":
  315. if f.Go != nil {
  316. errorf("repeated go statement")
  317. return
  318. }
  319. if len(args) != 1 {
  320. errorf("go directive expects exactly one argument")
  321. return
  322. } else if !GoVersionRE.MatchString(args[0]) {
  323. fixed := false
  324. if !strict {
  325. if m := laxGoVersionRE.FindStringSubmatch(args[0]); m != nil {
  326. args[0] = m[1]
  327. fixed = true
  328. }
  329. }
  330. if !fixed {
  331. errorf("invalid go version '%s': must match format 1.23", args[0])
  332. return
  333. }
  334. }
  335. f.Go = &Go{Syntax: line}
  336. f.Go.Version = args[0]
  337. case "toolchain":
  338. if f.Toolchain != nil {
  339. errorf("repeated toolchain statement")
  340. return
  341. }
  342. if len(args) != 1 {
  343. errorf("toolchain directive expects exactly one argument")
  344. return
  345. } else if strict && !ToolchainRE.MatchString(args[0]) {
  346. errorf("invalid toolchain version '%s': must match format go1.23 or local", args[0])
  347. return
  348. }
  349. f.Toolchain = &Toolchain{Syntax: line}
  350. f.Toolchain.Name = args[0]
  351. case "module":
  352. if f.Module != nil {
  353. errorf("repeated module statement")
  354. return
  355. }
  356. deprecated := parseDeprecation(block, line)
  357. f.Module = &Module{
  358. Syntax: line,
  359. Deprecated: deprecated,
  360. }
  361. if len(args) != 1 {
  362. errorf("usage: module module/path")
  363. return
  364. }
  365. s, err := parseString(&args[0])
  366. if err != nil {
  367. errorf("invalid quoted string: %v", err)
  368. return
  369. }
  370. f.Module.Mod = module.Version{Path: s}
  371. case "require", "exclude":
  372. if len(args) != 2 {
  373. errorf("usage: %s module/path v1.2.3", verb)
  374. return
  375. }
  376. s, err := parseString(&args[0])
  377. if err != nil {
  378. errorf("invalid quoted string: %v", err)
  379. return
  380. }
  381. v, err := parseVersion(verb, s, &args[1], fix)
  382. if err != nil {
  383. wrapError(err)
  384. return
  385. }
  386. pathMajor, err := modulePathMajor(s)
  387. if err != nil {
  388. wrapError(err)
  389. return
  390. }
  391. if err := module.CheckPathMajor(v, pathMajor); err != nil {
  392. wrapModPathError(s, err)
  393. return
  394. }
  395. if verb == "require" {
  396. f.Require = append(f.Require, &Require{
  397. Mod: module.Version{Path: s, Version: v},
  398. Syntax: line,
  399. Indirect: isIndirect(line),
  400. })
  401. } else {
  402. f.Exclude = append(f.Exclude, &Exclude{
  403. Mod: module.Version{Path: s, Version: v},
  404. Syntax: line,
  405. })
  406. }
  407. case "replace":
  408. replace, wrappederr := parseReplace(f.Syntax.Name, line, verb, args, fix)
  409. if wrappederr != nil {
  410. *errs = append(*errs, *wrappederr)
  411. return
  412. }
  413. f.Replace = append(f.Replace, replace)
  414. case "retract":
  415. rationale := parseDirectiveComment(block, line)
  416. vi, err := parseVersionInterval(verb, "", &args, dontFixRetract)
  417. if err != nil {
  418. if strict {
  419. wrapError(err)
  420. return
  421. } else {
  422. // Only report errors parsing intervals in the main module. We may
  423. // support additional syntax in the future, such as open and half-open
  424. // intervals. Those can't be supported now, because they break the
  425. // go.mod parser, even in lax mode.
  426. return
  427. }
  428. }
  429. if len(args) > 0 && strict {
  430. // In the future, there may be additional information after the version.
  431. errorf("unexpected token after version: %q", args[0])
  432. return
  433. }
  434. retract := &Retract{
  435. VersionInterval: vi,
  436. Rationale: rationale,
  437. Syntax: line,
  438. }
  439. f.Retract = append(f.Retract, retract)
  440. }
  441. }
  442. func parseReplace(filename string, line *Line, verb string, args []string, fix VersionFixer) (*Replace, *Error) {
  443. wrapModPathError := func(modPath string, err error) *Error {
  444. return &Error{
  445. Filename: filename,
  446. Pos: line.Start,
  447. ModPath: modPath,
  448. Verb: verb,
  449. Err: err,
  450. }
  451. }
  452. wrapError := func(err error) *Error {
  453. return &Error{
  454. Filename: filename,
  455. Pos: line.Start,
  456. Err: err,
  457. }
  458. }
  459. errorf := func(format string, args ...interface{}) *Error {
  460. return wrapError(fmt.Errorf(format, args...))
  461. }
  462. arrow := 2
  463. if len(args) >= 2 && args[1] == "=>" {
  464. arrow = 1
  465. }
  466. if len(args) < arrow+2 || len(args) > arrow+3 || args[arrow] != "=>" {
  467. 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)
  468. }
  469. s, err := parseString(&args[0])
  470. if err != nil {
  471. return nil, errorf("invalid quoted string: %v", err)
  472. }
  473. pathMajor, err := modulePathMajor(s)
  474. if err != nil {
  475. return nil, wrapModPathError(s, err)
  476. }
  477. var v string
  478. if arrow == 2 {
  479. v, err = parseVersion(verb, s, &args[1], fix)
  480. if err != nil {
  481. return nil, wrapError(err)
  482. }
  483. if err := module.CheckPathMajor(v, pathMajor); err != nil {
  484. return nil, wrapModPathError(s, err)
  485. }
  486. }
  487. ns, err := parseString(&args[arrow+1])
  488. if err != nil {
  489. return nil, errorf("invalid quoted string: %v", err)
  490. }
  491. nv := ""
  492. if len(args) == arrow+2 {
  493. if !IsDirectoryPath(ns) {
  494. if strings.Contains(ns, "@") {
  495. return nil, errorf("replacement module must match format 'path version', not 'path@version'")
  496. }
  497. return nil, errorf("replacement module without version must be directory path (rooted or starting with ./ or ../)")
  498. }
  499. if filepath.Separator == '/' && strings.Contains(ns, `\`) {
  500. return nil, errorf("replacement directory appears to be Windows path (on a non-windows system)")
  501. }
  502. }
  503. if len(args) == arrow+3 {
  504. nv, err = parseVersion(verb, ns, &args[arrow+2], fix)
  505. if err != nil {
  506. return nil, wrapError(err)
  507. }
  508. if IsDirectoryPath(ns) {
  509. return nil, errorf("replacement module directory path %q cannot have version", ns)
  510. }
  511. }
  512. return &Replace{
  513. Old: module.Version{Path: s, Version: v},
  514. New: module.Version{Path: ns, Version: nv},
  515. Syntax: line,
  516. }, nil
  517. }
  518. // fixRetract applies fix to each retract directive in f, appending any errors
  519. // to errs.
  520. //
  521. // Most versions are fixed as we parse the file, but for retract directives,
  522. // the relevant module path is the one specified with the module directive,
  523. // and that might appear at the end of the file (or not at all).
  524. func (f *File) fixRetract(fix VersionFixer, errs *ErrorList) {
  525. if fix == nil {
  526. return
  527. }
  528. path := ""
  529. if f.Module != nil {
  530. path = f.Module.Mod.Path
  531. }
  532. var r *Retract
  533. wrapError := func(err error) {
  534. *errs = append(*errs, Error{
  535. Filename: f.Syntax.Name,
  536. Pos: r.Syntax.Start,
  537. Err: err,
  538. })
  539. }
  540. for _, r = range f.Retract {
  541. if path == "" {
  542. wrapError(errors.New("no module directive found, so retract cannot be used"))
  543. return // only print the first one of these
  544. }
  545. args := r.Syntax.Token
  546. if args[0] == "retract" {
  547. args = args[1:]
  548. }
  549. vi, err := parseVersionInterval("retract", path, &args, fix)
  550. if err != nil {
  551. wrapError(err)
  552. }
  553. r.VersionInterval = vi
  554. }
  555. }
  556. func (f *WorkFile) add(errs *ErrorList, line *Line, verb string, args []string, fix VersionFixer) {
  557. wrapError := func(err error) {
  558. *errs = append(*errs, Error{
  559. Filename: f.Syntax.Name,
  560. Pos: line.Start,
  561. Err: err,
  562. })
  563. }
  564. errorf := func(format string, args ...interface{}) {
  565. wrapError(fmt.Errorf(format, args...))
  566. }
  567. switch verb {
  568. default:
  569. errorf("unknown directive: %s", verb)
  570. case "go":
  571. if f.Go != nil {
  572. errorf("repeated go statement")
  573. return
  574. }
  575. if len(args) != 1 {
  576. errorf("go directive expects exactly one argument")
  577. return
  578. } else if !GoVersionRE.MatchString(args[0]) {
  579. errorf("invalid go version '%s': must match format 1.23", args[0])
  580. return
  581. }
  582. f.Go = &Go{Syntax: line}
  583. f.Go.Version = args[0]
  584. case "toolchain":
  585. if f.Toolchain != nil {
  586. errorf("repeated toolchain statement")
  587. return
  588. }
  589. if len(args) != 1 {
  590. errorf("toolchain directive expects exactly one argument")
  591. return
  592. } else if !ToolchainRE.MatchString(args[0]) {
  593. errorf("invalid toolchain version '%s': must match format go1.23 or local", args[0])
  594. return
  595. }
  596. f.Toolchain = &Toolchain{Syntax: line}
  597. f.Toolchain.Name = args[0]
  598. case "use":
  599. if len(args) != 1 {
  600. errorf("usage: %s local/dir", verb)
  601. return
  602. }
  603. s, err := parseString(&args[0])
  604. if err != nil {
  605. errorf("invalid quoted string: %v", err)
  606. return
  607. }
  608. f.Use = append(f.Use, &Use{
  609. Path: s,
  610. Syntax: line,
  611. })
  612. case "replace":
  613. replace, wrappederr := parseReplace(f.Syntax.Name, line, verb, args, fix)
  614. if wrappederr != nil {
  615. *errs = append(*errs, *wrappederr)
  616. return
  617. }
  618. f.Replace = append(f.Replace, replace)
  619. }
  620. }
  621. // IsDirectoryPath reports whether the given path should be interpreted
  622. // as a directory path. Just like on the go command line, relative paths
  623. // and rooted paths are directory paths; the rest are module paths.
  624. func IsDirectoryPath(ns string) bool {
  625. // Because go.mod files can move from one system to another,
  626. // we check all known path syntaxes, both Unix and Windows.
  627. return strings.HasPrefix(ns, "./") || strings.HasPrefix(ns, "../") || strings.HasPrefix(ns, "/") ||
  628. strings.HasPrefix(ns, `.\`) || strings.HasPrefix(ns, `..\`) || strings.HasPrefix(ns, `\`) ||
  629. len(ns) >= 2 && ('A' <= ns[0] && ns[0] <= 'Z' || 'a' <= ns[0] && ns[0] <= 'z') && ns[1] == ':'
  630. }
  631. // MustQuote reports whether s must be quoted in order to appear as
  632. // a single token in a go.mod line.
  633. func MustQuote(s string) bool {
  634. for _, r := range s {
  635. switch r {
  636. case ' ', '"', '\'', '`':
  637. return true
  638. case '(', ')', '[', ']', '{', '}', ',':
  639. if len(s) > 1 {
  640. return true
  641. }
  642. default:
  643. if !unicode.IsPrint(r) {
  644. return true
  645. }
  646. }
  647. }
  648. return s == "" || strings.Contains(s, "//") || strings.Contains(s, "/*")
  649. }
  650. // AutoQuote returns s or, if quoting is required for s to appear in a go.mod,
  651. // the quotation of s.
  652. func AutoQuote(s string) string {
  653. if MustQuote(s) {
  654. return strconv.Quote(s)
  655. }
  656. return s
  657. }
  658. func parseVersionInterval(verb string, path string, args *[]string, fix VersionFixer) (VersionInterval, error) {
  659. toks := *args
  660. if len(toks) == 0 || toks[0] == "(" {
  661. return VersionInterval{}, fmt.Errorf("expected '[' or version")
  662. }
  663. if toks[0] != "[" {
  664. v, err := parseVersion(verb, path, &toks[0], fix)
  665. if err != nil {
  666. return VersionInterval{}, err
  667. }
  668. *args = toks[1:]
  669. return VersionInterval{Low: v, High: v}, nil
  670. }
  671. toks = toks[1:]
  672. if len(toks) == 0 {
  673. return VersionInterval{}, fmt.Errorf("expected version after '['")
  674. }
  675. low, err := parseVersion(verb, path, &toks[0], fix)
  676. if err != nil {
  677. return VersionInterval{}, err
  678. }
  679. toks = toks[1:]
  680. if len(toks) == 0 || toks[0] != "," {
  681. return VersionInterval{}, fmt.Errorf("expected ',' after version")
  682. }
  683. toks = toks[1:]
  684. if len(toks) == 0 {
  685. return VersionInterval{}, fmt.Errorf("expected version after ','")
  686. }
  687. high, err := parseVersion(verb, path, &toks[0], fix)
  688. if err != nil {
  689. return VersionInterval{}, err
  690. }
  691. toks = toks[1:]
  692. if len(toks) == 0 || toks[0] != "]" {
  693. return VersionInterval{}, fmt.Errorf("expected ']' after version")
  694. }
  695. toks = toks[1:]
  696. *args = toks
  697. return VersionInterval{Low: low, High: high}, nil
  698. }
  699. func parseString(s *string) (string, error) {
  700. t := *s
  701. if strings.HasPrefix(t, `"`) {
  702. var err error
  703. if t, err = strconv.Unquote(t); err != nil {
  704. return "", err
  705. }
  706. } else if strings.ContainsAny(t, "\"'`") {
  707. // Other quotes are reserved both for possible future expansion
  708. // and to avoid confusion. For example if someone types 'x'
  709. // we want that to be a syntax error and not a literal x in literal quotation marks.
  710. return "", fmt.Errorf("unquoted string cannot contain quote")
  711. }
  712. *s = AutoQuote(t)
  713. return t, nil
  714. }
  715. var deprecatedRE = lazyregexp.New(`(?s)(?:^|\n\n)Deprecated: *(.*?)(?:$|\n\n)`)
  716. // parseDeprecation extracts the text of comments on a "module" directive and
  717. // extracts a deprecation message from that.
  718. //
  719. // A deprecation message is contained in a paragraph within a block of comments
  720. // that starts with "Deprecated:" (case sensitive). The message runs until the
  721. // end of the paragraph and does not include the "Deprecated:" prefix. If the
  722. // comment block has multiple paragraphs that start with "Deprecated:",
  723. // parseDeprecation returns the message from the first.
  724. func parseDeprecation(block *LineBlock, line *Line) string {
  725. text := parseDirectiveComment(block, line)
  726. m := deprecatedRE.FindStringSubmatch(text)
  727. if m == nil {
  728. return ""
  729. }
  730. return m[1]
  731. }
  732. // parseDirectiveComment extracts the text of comments on a directive.
  733. // If the directive's line does not have comments and is part of a block that
  734. // does have comments, the block's comments are used.
  735. func parseDirectiveComment(block *LineBlock, line *Line) string {
  736. comments := line.Comment()
  737. if block != nil && len(comments.Before) == 0 && len(comments.Suffix) == 0 {
  738. comments = block.Comment()
  739. }
  740. groups := [][]Comment{comments.Before, comments.Suffix}
  741. var lines []string
  742. for _, g := range groups {
  743. for _, c := range g {
  744. if !strings.HasPrefix(c.Token, "//") {
  745. continue // blank line
  746. }
  747. lines = append(lines, strings.TrimSpace(strings.TrimPrefix(c.Token, "//")))
  748. }
  749. }
  750. return strings.Join(lines, "\n")
  751. }
  752. type ErrorList []Error
  753. func (e ErrorList) Error() string {
  754. errStrs := make([]string, len(e))
  755. for i, err := range e {
  756. errStrs[i] = err.Error()
  757. }
  758. return strings.Join(errStrs, "\n")
  759. }
  760. type Error struct {
  761. Filename string
  762. Pos Position
  763. Verb string
  764. ModPath string
  765. Err error
  766. }
  767. func (e *Error) Error() string {
  768. var pos string
  769. if e.Pos.LineRune > 1 {
  770. // Don't print LineRune if it's 1 (beginning of line).
  771. // It's always 1 except in scanner errors, which are rare.
  772. pos = fmt.Sprintf("%s:%d:%d: ", e.Filename, e.Pos.Line, e.Pos.LineRune)
  773. } else if e.Pos.Line > 0 {
  774. pos = fmt.Sprintf("%s:%d: ", e.Filename, e.Pos.Line)
  775. } else if e.Filename != "" {
  776. pos = fmt.Sprintf("%s: ", e.Filename)
  777. }
  778. var directive string
  779. if e.ModPath != "" {
  780. directive = fmt.Sprintf("%s %s: ", e.Verb, e.ModPath)
  781. } else if e.Verb != "" {
  782. directive = fmt.Sprintf("%s: ", e.Verb)
  783. }
  784. return pos + directive + e.Err.Error()
  785. }
  786. func (e *Error) Unwrap() error { return e.Err }
  787. func parseVersion(verb string, path string, s *string, fix VersionFixer) (string, error) {
  788. t, err := parseString(s)
  789. if err != nil {
  790. return "", &Error{
  791. Verb: verb,
  792. ModPath: path,
  793. Err: &module.InvalidVersionError{
  794. Version: *s,
  795. Err: err,
  796. },
  797. }
  798. }
  799. if fix != nil {
  800. fixed, err := fix(path, t)
  801. if err != nil {
  802. if err, ok := err.(*module.ModuleError); ok {
  803. return "", &Error{
  804. Verb: verb,
  805. ModPath: path,
  806. Err: err.Err,
  807. }
  808. }
  809. return "", err
  810. }
  811. t = fixed
  812. } else {
  813. cv := module.CanonicalVersion(t)
  814. if cv == "" {
  815. return "", &Error{
  816. Verb: verb,
  817. ModPath: path,
  818. Err: &module.InvalidVersionError{
  819. Version: t,
  820. Err: errors.New("must be of the form v1.2.3"),
  821. },
  822. }
  823. }
  824. t = cv
  825. }
  826. *s = t
  827. return *s, nil
  828. }
  829. func modulePathMajor(path string) (string, error) {
  830. _, major, ok := module.SplitPathVersion(path)
  831. if !ok {
  832. return "", fmt.Errorf("invalid module path")
  833. }
  834. return major, nil
  835. }
  836. func (f *File) Format() ([]byte, error) {
  837. return Format(f.Syntax), nil
  838. }
  839. // Cleanup cleans up the file f after any edit operations.
  840. // To avoid quadratic behavior, modifications like DropRequire
  841. // clear the entry but do not remove it from the slice.
  842. // Cleanup cleans out all the cleared entries.
  843. func (f *File) Cleanup() {
  844. w := 0
  845. for _, r := range f.Require {
  846. if r.Mod.Path != "" {
  847. f.Require[w] = r
  848. w++
  849. }
  850. }
  851. f.Require = f.Require[:w]
  852. w = 0
  853. for _, x := range f.Exclude {
  854. if x.Mod.Path != "" {
  855. f.Exclude[w] = x
  856. w++
  857. }
  858. }
  859. f.Exclude = f.Exclude[:w]
  860. w = 0
  861. for _, r := range f.Replace {
  862. if r.Old.Path != "" {
  863. f.Replace[w] = r
  864. w++
  865. }
  866. }
  867. f.Replace = f.Replace[:w]
  868. w = 0
  869. for _, r := range f.Retract {
  870. if r.Low != "" || r.High != "" {
  871. f.Retract[w] = r
  872. w++
  873. }
  874. }
  875. f.Retract = f.Retract[:w]
  876. f.Syntax.Cleanup()
  877. }
  878. func (f *File) AddGoStmt(version string) error {
  879. if !GoVersionRE.MatchString(version) {
  880. return fmt.Errorf("invalid language version %q", version)
  881. }
  882. if f.Go == nil {
  883. var hint Expr
  884. if f.Module != nil && f.Module.Syntax != nil {
  885. hint = f.Module.Syntax
  886. }
  887. f.Go = &Go{
  888. Version: version,
  889. Syntax: f.Syntax.addLine(hint, "go", version),
  890. }
  891. } else {
  892. f.Go.Version = version
  893. f.Syntax.updateLine(f.Go.Syntax, "go", version)
  894. }
  895. return nil
  896. }
  897. // DropGoStmt deletes the go statement from the file.
  898. func (f *File) DropGoStmt() {
  899. if f.Go != nil {
  900. f.Go.Syntax.markRemoved()
  901. f.Go = nil
  902. }
  903. }
  904. // DropToolchainStmt deletes the toolchain statement from the file.
  905. func (f *File) DropToolchainStmt() {
  906. if f.Toolchain != nil {
  907. f.Toolchain.Syntax.markRemoved()
  908. f.Toolchain = nil
  909. }
  910. }
  911. func (f *File) AddToolchainStmt(name string) error {
  912. if !ToolchainRE.MatchString(name) {
  913. return fmt.Errorf("invalid toolchain name %q", name)
  914. }
  915. if f.Toolchain == nil {
  916. var hint Expr
  917. if f.Go != nil && f.Go.Syntax != nil {
  918. hint = f.Go.Syntax
  919. } else if f.Module != nil && f.Module.Syntax != nil {
  920. hint = f.Module.Syntax
  921. }
  922. f.Toolchain = &Toolchain{
  923. Name: name,
  924. Syntax: f.Syntax.addLine(hint, "toolchain", name),
  925. }
  926. } else {
  927. f.Toolchain.Name = name
  928. f.Syntax.updateLine(f.Toolchain.Syntax, "toolchain", name)
  929. }
  930. return nil
  931. }
  932. // AddRequire sets the first require line for path to version vers,
  933. // preserving any existing comments for that line and removing all
  934. // other lines for path.
  935. //
  936. // If no line currently exists for path, AddRequire adds a new line
  937. // at the end of the last require block.
  938. func (f *File) AddRequire(path, vers string) error {
  939. need := true
  940. for _, r := range f.Require {
  941. if r.Mod.Path == path {
  942. if need {
  943. r.Mod.Version = vers
  944. f.Syntax.updateLine(r.Syntax, "require", AutoQuote(path), vers)
  945. need = false
  946. } else {
  947. r.Syntax.markRemoved()
  948. *r = Require{}
  949. }
  950. }
  951. }
  952. if need {
  953. f.AddNewRequire(path, vers, false)
  954. }
  955. return nil
  956. }
  957. // AddNewRequire adds a new require line for path at version vers at the end of
  958. // the last require block, regardless of any existing require lines for path.
  959. func (f *File) AddNewRequire(path, vers string, indirect bool) {
  960. line := f.Syntax.addLine(nil, "require", AutoQuote(path), vers)
  961. r := &Require{
  962. Mod: module.Version{Path: path, Version: vers},
  963. Syntax: line,
  964. }
  965. r.setIndirect(indirect)
  966. f.Require = append(f.Require, r)
  967. }
  968. // SetRequire updates the requirements of f to contain exactly req, preserving
  969. // the existing block structure and line comment contents (except for 'indirect'
  970. // markings) for the first requirement on each named module path.
  971. //
  972. // The Syntax field is ignored for the requirements in req.
  973. //
  974. // Any requirements not already present in the file are added to the block
  975. // containing the last require line.
  976. //
  977. // The requirements in req must specify at most one distinct version for each
  978. // module path.
  979. //
  980. // If any existing requirements may be removed, the caller should call Cleanup
  981. // after all edits are complete.
  982. func (f *File) SetRequire(req []*Require) {
  983. type elem struct {
  984. version string
  985. indirect bool
  986. }
  987. need := make(map[string]elem)
  988. for _, r := range req {
  989. if prev, dup := need[r.Mod.Path]; dup && prev.version != r.Mod.Version {
  990. panic(fmt.Errorf("SetRequire called with conflicting versions for path %s (%s and %s)", r.Mod.Path, prev.version, r.Mod.Version))
  991. }
  992. need[r.Mod.Path] = elem{r.Mod.Version, r.Indirect}
  993. }
  994. // Update or delete the existing Require entries to preserve
  995. // only the first for each module path in req.
  996. for _, r := range f.Require {
  997. e, ok := need[r.Mod.Path]
  998. if ok {
  999. r.setVersion(e.version)
  1000. r.setIndirect(e.indirect)
  1001. } else {
  1002. r.markRemoved()
  1003. }
  1004. delete(need, r.Mod.Path)
  1005. }
  1006. // Add new entries in the last block of the file for any paths that weren't
  1007. // already present.
  1008. //
  1009. // This step is nondeterministic, but the final result will be deterministic
  1010. // because we will sort the block.
  1011. for path, e := range need {
  1012. f.AddNewRequire(path, e.version, e.indirect)
  1013. }
  1014. f.SortBlocks()
  1015. }
  1016. // SetRequireSeparateIndirect updates the requirements of f to contain the given
  1017. // requirements. Comment contents (except for 'indirect' markings) are retained
  1018. // from the first existing requirement for each module path. Like SetRequire,
  1019. // SetRequireSeparateIndirect adds requirements for new paths in req,
  1020. // updates the version and "// indirect" comment on existing requirements,
  1021. // and deletes requirements on paths not in req. Existing duplicate requirements
  1022. // are deleted.
  1023. //
  1024. // As its name suggests, SetRequireSeparateIndirect puts direct and indirect
  1025. // requirements into two separate blocks, one containing only direct
  1026. // requirements, and the other containing only indirect requirements.
  1027. // SetRequireSeparateIndirect may move requirements between these two blocks
  1028. // when their indirect markings change. However, SetRequireSeparateIndirect
  1029. // won't move requirements from other blocks, especially blocks with comments.
  1030. //
  1031. // If the file initially has one uncommented block of requirements,
  1032. // SetRequireSeparateIndirect will split it into a direct-only and indirect-only
  1033. // block. This aids in the transition to separate blocks.
  1034. func (f *File) SetRequireSeparateIndirect(req []*Require) {
  1035. // hasComments returns whether a line or block has comments
  1036. // other than "indirect".
  1037. hasComments := func(c Comments) bool {
  1038. return len(c.Before) > 0 || len(c.After) > 0 || len(c.Suffix) > 1 ||
  1039. (len(c.Suffix) == 1 &&
  1040. strings.TrimSpace(strings.TrimPrefix(c.Suffix[0].Token, string(slashSlash))) != "indirect")
  1041. }
  1042. // moveReq adds r to block. If r was in another block, moveReq deletes
  1043. // it from that block and transfers its comments.
  1044. moveReq := func(r *Require, block *LineBlock) {
  1045. var line *Line
  1046. if r.Syntax == nil {
  1047. line = &Line{Token: []string{AutoQuote(r.Mod.Path), r.Mod.Version}}
  1048. r.Syntax = line
  1049. if r.Indirect {
  1050. r.setIndirect(true)
  1051. }
  1052. } else {
  1053. line = new(Line)
  1054. *line = *r.Syntax
  1055. if !line.InBlock && len(line.Token) > 0 && line.Token[0] == "require" {
  1056. line.Token = line.Token[1:]
  1057. }
  1058. r.Syntax.Token = nil // Cleanup will delete the old line.
  1059. r.Syntax = line
  1060. }
  1061. line.InBlock = true
  1062. block.Line = append(block.Line, line)
  1063. }
  1064. // Examine existing require lines and blocks.
  1065. var (
  1066. // We may insert new requirements into the last uncommented
  1067. // direct-only and indirect-only blocks. We may also move requirements
  1068. // to the opposite block if their indirect markings change.
  1069. lastDirectIndex = -1
  1070. lastIndirectIndex = -1
  1071. // If there are no direct-only or indirect-only blocks, a new block may
  1072. // be inserted after the last require line or block.
  1073. lastRequireIndex = -1
  1074. // If there's only one require line or block, and it's uncommented,
  1075. // we'll move its requirements to the direct-only or indirect-only blocks.
  1076. requireLineOrBlockCount = 0
  1077. // Track the block each requirement belongs to (if any) so we can
  1078. // move them later.
  1079. lineToBlock = make(map[*Line]*LineBlock)
  1080. )
  1081. for i, stmt := range f.Syntax.Stmt {
  1082. switch stmt := stmt.(type) {
  1083. case *Line:
  1084. if len(stmt.Token) == 0 || stmt.Token[0] != "require" {
  1085. continue
  1086. }
  1087. lastRequireIndex = i
  1088. requireLineOrBlockCount++
  1089. if !hasComments(stmt.Comments) {
  1090. if isIndirect(stmt) {
  1091. lastIndirectIndex = i
  1092. } else {
  1093. lastDirectIndex = i
  1094. }
  1095. }
  1096. case *LineBlock:
  1097. if len(stmt.Token) == 0 || stmt.Token[0] != "require" {
  1098. continue
  1099. }
  1100. lastRequireIndex = i
  1101. requireLineOrBlockCount++
  1102. allDirect := len(stmt.Line) > 0 && !hasComments(stmt.Comments)
  1103. allIndirect := len(stmt.Line) > 0 && !hasComments(stmt.Comments)
  1104. for _, line := range stmt.Line {
  1105. lineToBlock[line] = stmt
  1106. if hasComments(line.Comments) {
  1107. allDirect = false
  1108. allIndirect = false
  1109. } else if isIndirect(line) {
  1110. allDirect = false
  1111. } else {
  1112. allIndirect = false
  1113. }
  1114. }
  1115. if allDirect {
  1116. lastDirectIndex = i
  1117. }
  1118. if allIndirect {
  1119. lastIndirectIndex = i
  1120. }
  1121. }
  1122. }
  1123. oneFlatUncommentedBlock := requireLineOrBlockCount == 1 &&
  1124. !hasComments(*f.Syntax.Stmt[lastRequireIndex].Comment())
  1125. // Create direct and indirect blocks if needed. Convert lines into blocks
  1126. // if needed. If we end up with an empty block or a one-line block,
  1127. // Cleanup will delete it or convert it to a line later.
  1128. insertBlock := func(i int) *LineBlock {
  1129. block := &LineBlock{Token: []string{"require"}}
  1130. f.Syntax.Stmt = append(f.Syntax.Stmt, nil)
  1131. copy(f.Syntax.Stmt[i+1:], f.Syntax.Stmt[i:])
  1132. f.Syntax.Stmt[i] = block
  1133. return block
  1134. }
  1135. ensureBlock := func(i int) *LineBlock {
  1136. switch stmt := f.Syntax.Stmt[i].(type) {
  1137. case *LineBlock:
  1138. return stmt
  1139. case *Line:
  1140. block := &LineBlock{
  1141. Token: []string{"require"},
  1142. Line: []*Line{stmt},
  1143. }
  1144. stmt.Token = stmt.Token[1:] // remove "require"
  1145. stmt.InBlock = true
  1146. f.Syntax.Stmt[i] = block
  1147. return block
  1148. default:
  1149. panic(fmt.Sprintf("unexpected statement: %v", stmt))
  1150. }
  1151. }
  1152. var lastDirectBlock *LineBlock
  1153. if lastDirectIndex < 0 {
  1154. if lastIndirectIndex >= 0 {
  1155. lastDirectIndex = lastIndirectIndex
  1156. lastIndirectIndex++
  1157. } else if lastRequireIndex >= 0 {
  1158. lastDirectIndex = lastRequireIndex + 1
  1159. } else {
  1160. lastDirectIndex = len(f.Syntax.Stmt)
  1161. }
  1162. lastDirectBlock = insertBlock(lastDirectIndex)
  1163. } else {
  1164. lastDirectBlock = ensureBlock(lastDirectIndex)
  1165. }
  1166. var lastIndirectBlock *LineBlock
  1167. if lastIndirectIndex < 0 {
  1168. lastIndirectIndex = lastDirectIndex + 1
  1169. lastIndirectBlock = insertBlock(lastIndirectIndex)
  1170. } else {
  1171. lastIndirectBlock = ensureBlock(lastIndirectIndex)
  1172. }
  1173. // Delete requirements we don't want anymore.
  1174. // Update versions and indirect comments on requirements we want to keep.
  1175. // If a requirement is in last{Direct,Indirect}Block with the wrong
  1176. // indirect marking after this, or if the requirement is in an single
  1177. // uncommented mixed block (oneFlatUncommentedBlock), move it to the
  1178. // correct block.
  1179. //
  1180. // Some blocks may be empty after this. Cleanup will remove them.
  1181. need := make(map[string]*Require)
  1182. for _, r := range req {
  1183. need[r.Mod.Path] = r
  1184. }
  1185. have := make(map[string]*Require)
  1186. for _, r := range f.Require {
  1187. path := r.Mod.Path
  1188. if need[path] == nil || have[path] != nil {
  1189. // Requirement not needed, or duplicate requirement. Delete.
  1190. r.markRemoved()
  1191. continue
  1192. }
  1193. have[r.Mod.Path] = r
  1194. r.setVersion(need[path].Mod.Version)
  1195. r.setIndirect(need[path].Indirect)
  1196. if need[path].Indirect &&
  1197. (oneFlatUncommentedBlock || lineToBlock[r.Syntax] == lastDirectBlock) {
  1198. moveReq(r, lastIndirectBlock)
  1199. } else if !need[path].Indirect &&
  1200. (oneFlatUncommentedBlock || lineToBlock[r.Syntax] == lastIndirectBlock) {
  1201. moveReq(r, lastDirectBlock)
  1202. }
  1203. }
  1204. // Add new requirements.
  1205. for path, r := range need {
  1206. if have[path] == nil {
  1207. if r.Indirect {
  1208. moveReq(r, lastIndirectBlock)
  1209. } else {
  1210. moveReq(r, lastDirectBlock)
  1211. }
  1212. f.Require = append(f.Require, r)
  1213. }
  1214. }
  1215. f.SortBlocks()
  1216. }
  1217. func (f *File) DropRequire(path string) error {
  1218. for _, r := range f.Require {
  1219. if r.Mod.Path == path {
  1220. r.Syntax.markRemoved()
  1221. *r = Require{}
  1222. }
  1223. }
  1224. return nil
  1225. }
  1226. // AddExclude adds a exclude statement to the mod file. Errors if the provided
  1227. // version is not a canonical version string
  1228. func (f *File) AddExclude(path, vers string) error {
  1229. if err := checkCanonicalVersion(path, vers); err != nil {
  1230. return err
  1231. }
  1232. var hint *Line
  1233. for _, x := range f.Exclude {
  1234. if x.Mod.Path == path && x.Mod.Version == vers {
  1235. return nil
  1236. }
  1237. if x.Mod.Path == path {
  1238. hint = x.Syntax
  1239. }
  1240. }
  1241. f.Exclude = append(f.Exclude, &Exclude{Mod: module.Version{Path: path, Version: vers}, Syntax: f.Syntax.addLine(hint, "exclude", AutoQuote(path), vers)})
  1242. return nil
  1243. }
  1244. func (f *File) DropExclude(path, vers string) error {
  1245. for _, x := range f.Exclude {
  1246. if x.Mod.Path == path && x.Mod.Version == vers {
  1247. x.Syntax.markRemoved()
  1248. *x = Exclude{}
  1249. }
  1250. }
  1251. return nil
  1252. }
  1253. func (f *File) AddReplace(oldPath, oldVers, newPath, newVers string) error {
  1254. return addReplace(f.Syntax, &f.Replace, oldPath, oldVers, newPath, newVers)
  1255. }
  1256. func addReplace(syntax *FileSyntax, replace *[]*Replace, oldPath, oldVers, newPath, newVers string) error {
  1257. need := true
  1258. old := module.Version{Path: oldPath, Version: oldVers}
  1259. new := module.Version{Path: newPath, Version: newVers}
  1260. tokens := []string{"replace", AutoQuote(oldPath)}
  1261. if oldVers != "" {
  1262. tokens = append(tokens, oldVers)
  1263. }
  1264. tokens = append(tokens, "=>", AutoQuote(newPath))
  1265. if newVers != "" {
  1266. tokens = append(tokens, newVers)
  1267. }
  1268. var hint *Line
  1269. for _, r := range *replace {
  1270. if r.Old.Path == oldPath && (oldVers == "" || r.Old.Version == oldVers) {
  1271. if need {
  1272. // Found replacement for old; update to use new.
  1273. r.New = new
  1274. syntax.updateLine(r.Syntax, tokens...)
  1275. need = false
  1276. continue
  1277. }
  1278. // Already added; delete other replacements for same.
  1279. r.Syntax.markRemoved()
  1280. *r = Replace{}
  1281. }
  1282. if r.Old.Path == oldPath {
  1283. hint = r.Syntax
  1284. }
  1285. }
  1286. if need {
  1287. *replace = append(*replace, &Replace{Old: old, New: new, Syntax: syntax.addLine(hint, tokens...)})
  1288. }
  1289. return nil
  1290. }
  1291. func (f *File) DropReplace(oldPath, oldVers string) error {
  1292. for _, r := range f.Replace {
  1293. if r.Old.Path == oldPath && r.Old.Version == oldVers {
  1294. r.Syntax.markRemoved()
  1295. *r = Replace{}
  1296. }
  1297. }
  1298. return nil
  1299. }
  1300. // AddRetract adds a retract statement to the mod file. Errors if the provided
  1301. // version interval does not consist of canonical version strings
  1302. func (f *File) AddRetract(vi VersionInterval, rationale string) error {
  1303. var path string
  1304. if f.Module != nil {
  1305. path = f.Module.Mod.Path
  1306. }
  1307. if err := checkCanonicalVersion(path, vi.High); err != nil {
  1308. return err
  1309. }
  1310. if err := checkCanonicalVersion(path, vi.Low); err != nil {
  1311. return err
  1312. }
  1313. r := &Retract{
  1314. VersionInterval: vi,
  1315. }
  1316. if vi.Low == vi.High {
  1317. r.Syntax = f.Syntax.addLine(nil, "retract", AutoQuote(vi.Low))
  1318. } else {
  1319. r.Syntax = f.Syntax.addLine(nil, "retract", "[", AutoQuote(vi.Low), ",", AutoQuote(vi.High), "]")
  1320. }
  1321. if rationale != "" {
  1322. for _, line := range strings.Split(rationale, "\n") {
  1323. com := Comment{Token: "// " + line}
  1324. r.Syntax.Comment().Before = append(r.Syntax.Comment().Before, com)
  1325. }
  1326. }
  1327. return nil
  1328. }
  1329. func (f *File) DropRetract(vi VersionInterval) error {
  1330. for _, r := range f.Retract {
  1331. if r.VersionInterval == vi {
  1332. r.Syntax.markRemoved()
  1333. *r = Retract{}
  1334. }
  1335. }
  1336. return nil
  1337. }
  1338. func (f *File) SortBlocks() {
  1339. f.removeDups() // otherwise sorting is unsafe
  1340. // semanticSortForExcludeVersionV is the Go version (plus leading "v") at which
  1341. // lines in exclude blocks start to use semantic sort instead of lexicographic sort.
  1342. // See go.dev/issue/60028.
  1343. const semanticSortForExcludeVersionV = "v1.21"
  1344. useSemanticSortForExclude := f.Go != nil && semver.Compare("v"+f.Go.Version, semanticSortForExcludeVersionV) >= 0
  1345. for _, stmt := range f.Syntax.Stmt {
  1346. block, ok := stmt.(*LineBlock)
  1347. if !ok {
  1348. continue
  1349. }
  1350. less := lineLess
  1351. if block.Token[0] == "exclude" && useSemanticSortForExclude {
  1352. less = lineExcludeLess
  1353. } else if block.Token[0] == "retract" {
  1354. less = lineRetractLess
  1355. }
  1356. sort.SliceStable(block.Line, func(i, j int) bool {
  1357. return less(block.Line[i], block.Line[j])
  1358. })
  1359. }
  1360. }
  1361. // removeDups removes duplicate exclude and replace directives.
  1362. //
  1363. // Earlier exclude directives take priority.
  1364. //
  1365. // Later replace directives take priority.
  1366. //
  1367. // require directives are not de-duplicated. That's left up to higher-level
  1368. // logic (MVS).
  1369. //
  1370. // retract directives are not de-duplicated since comments are
  1371. // meaningful, and versions may be retracted multiple times.
  1372. func (f *File) removeDups() {
  1373. removeDups(f.Syntax, &f.Exclude, &f.Replace)
  1374. }
  1375. func removeDups(syntax *FileSyntax, exclude *[]*Exclude, replace *[]*Replace) {
  1376. kill := make(map[*Line]bool)
  1377. // Remove duplicate excludes.
  1378. if exclude != nil {
  1379. haveExclude := make(map[module.Version]bool)
  1380. for _, x := range *exclude {
  1381. if haveExclude[x.Mod] {
  1382. kill[x.Syntax] = true
  1383. continue
  1384. }
  1385. haveExclude[x.Mod] = true
  1386. }
  1387. var excl []*Exclude
  1388. for _, x := range *exclude {
  1389. if !kill[x.Syntax] {
  1390. excl = append(excl, x)
  1391. }
  1392. }
  1393. *exclude = excl
  1394. }
  1395. // Remove duplicate replacements.
  1396. // Later replacements take priority over earlier ones.
  1397. haveReplace := make(map[module.Version]bool)
  1398. for i := len(*replace) - 1; i >= 0; i-- {
  1399. x := (*replace)[i]
  1400. if haveReplace[x.Old] {
  1401. kill[x.Syntax] = true
  1402. continue
  1403. }
  1404. haveReplace[x.Old] = true
  1405. }
  1406. var repl []*Replace
  1407. for _, x := range *replace {
  1408. if !kill[x.Syntax] {
  1409. repl = append(repl, x)
  1410. }
  1411. }
  1412. *replace = repl
  1413. // Duplicate require and retract directives are not removed.
  1414. // Drop killed statements from the syntax tree.
  1415. var stmts []Expr
  1416. for _, stmt := range syntax.Stmt {
  1417. switch stmt := stmt.(type) {
  1418. case *Line:
  1419. if kill[stmt] {
  1420. continue
  1421. }
  1422. case *LineBlock:
  1423. var lines []*Line
  1424. for _, line := range stmt.Line {
  1425. if !kill[line] {
  1426. lines = append(lines, line)
  1427. }
  1428. }
  1429. stmt.Line = lines
  1430. if len(lines) == 0 {
  1431. continue
  1432. }
  1433. }
  1434. stmts = append(stmts, stmt)
  1435. }
  1436. syntax.Stmt = stmts
  1437. }
  1438. // lineLess returns whether li should be sorted before lj. It sorts
  1439. // lexicographically without assigning any special meaning to tokens.
  1440. func lineLess(li, lj *Line) bool {
  1441. for k := 0; k < len(li.Token) && k < len(lj.Token); k++ {
  1442. if li.Token[k] != lj.Token[k] {
  1443. return li.Token[k] < lj.Token[k]
  1444. }
  1445. }
  1446. return len(li.Token) < len(lj.Token)
  1447. }
  1448. // lineExcludeLess reports whether li should be sorted before lj for lines in
  1449. // an "exclude" block.
  1450. func lineExcludeLess(li, lj *Line) bool {
  1451. if len(li.Token) != 2 || len(lj.Token) != 2 {
  1452. // Not a known exclude specification.
  1453. // Fall back to sorting lexicographically.
  1454. return lineLess(li, lj)
  1455. }
  1456. // An exclude specification has two tokens: ModulePath and Version.
  1457. // Compare module path by string order and version by semver rules.
  1458. if pi, pj := li.Token[0], lj.Token[0]; pi != pj {
  1459. return pi < pj
  1460. }
  1461. return semver.Compare(li.Token[1], lj.Token[1]) < 0
  1462. }
  1463. // lineRetractLess returns whether li should be sorted before lj for lines in
  1464. // a "retract" block. It treats each line as a version interval. Single versions
  1465. // are compared as if they were intervals with the same low and high version.
  1466. // Intervals are sorted in descending order, first by low version, then by
  1467. // high version, using semver.Compare.
  1468. func lineRetractLess(li, lj *Line) bool {
  1469. interval := func(l *Line) VersionInterval {
  1470. if len(l.Token) == 1 {
  1471. return VersionInterval{Low: l.Token[0], High: l.Token[0]}
  1472. } else if len(l.Token) == 5 && l.Token[0] == "[" && l.Token[2] == "," && l.Token[4] == "]" {
  1473. return VersionInterval{Low: l.Token[1], High: l.Token[3]}
  1474. } else {
  1475. // Line in unknown format. Treat as an invalid version.
  1476. return VersionInterval{}
  1477. }
  1478. }
  1479. vii := interval(li)
  1480. vij := interval(lj)
  1481. if cmp := semver.Compare(vii.Low, vij.Low); cmp != 0 {
  1482. return cmp > 0
  1483. }
  1484. return semver.Compare(vii.High, vij.High) > 0
  1485. }
  1486. // checkCanonicalVersion returns a non-nil error if vers is not a canonical
  1487. // version string or does not match the major version of path.
  1488. //
  1489. // If path is non-empty, the error text suggests a format with a major version
  1490. // corresponding to the path.
  1491. func checkCanonicalVersion(path, vers string) error {
  1492. _, pathMajor, pathMajorOk := module.SplitPathVersion(path)
  1493. if vers == "" || vers != module.CanonicalVersion(vers) {
  1494. if pathMajor == "" {
  1495. return &module.InvalidVersionError{
  1496. Version: vers,
  1497. Err: fmt.Errorf("must be of the form v1.2.3"),
  1498. }
  1499. }
  1500. return &module.InvalidVersionError{
  1501. Version: vers,
  1502. Err: fmt.Errorf("must be of the form %s.2.3", module.PathMajorPrefix(pathMajor)),
  1503. }
  1504. }
  1505. if pathMajorOk {
  1506. if err := module.CheckPathMajor(vers, pathMajor); err != nil {
  1507. if pathMajor == "" {
  1508. // In this context, the user probably wrote "v2.3.4" when they meant
  1509. // "v2.3.4+incompatible". Suggest that instead of "v0 or v1".
  1510. return &module.InvalidVersionError{
  1511. Version: vers,
  1512. Err: fmt.Errorf("should be %s+incompatible (or module %s/%v)", vers, path, semver.Major(vers)),
  1513. }
  1514. }
  1515. return err
  1516. }
  1517. }
  1518. return nil
  1519. }