You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

module.go 24 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  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 module defines the module.Version type along with support code.
  5. //
  6. // The module.Version type is a simple Path, Version pair:
  7. //
  8. // type Version struct {
  9. // Path string
  10. // Version string
  11. // }
  12. //
  13. // There are no restrictions imposed directly by use of this structure,
  14. // but additional checking functions, most notably Check, verify that
  15. // a particular path, version pair is valid.
  16. //
  17. // Escaped Paths
  18. //
  19. // Module paths appear as substrings of file system paths
  20. // (in the download cache) and of web server URLs in the proxy protocol.
  21. // In general we cannot rely on file systems to be case-sensitive,
  22. // nor can we rely on web servers, since they read from file systems.
  23. // That is, we cannot rely on the file system to keep rsc.io/QUOTE
  24. // and rsc.io/quote separate. Windows and macOS don't.
  25. // Instead, we must never require two different casings of a file path.
  26. // Because we want the download cache to match the proxy protocol,
  27. // and because we want the proxy protocol to be possible to serve
  28. // from a tree of static files (which might be stored on a case-insensitive
  29. // file system), the proxy protocol must never require two different casings
  30. // of a URL path either.
  31. //
  32. // One possibility would be to make the escaped form be the lowercase
  33. // hexadecimal encoding of the actual path bytes. This would avoid ever
  34. // needing different casings of a file path, but it would be fairly illegible
  35. // to most programmers when those paths appeared in the file system
  36. // (including in file paths in compiler errors and stack traces)
  37. // in web server logs, and so on. Instead, we want a safe escaped form that
  38. // leaves most paths unaltered.
  39. //
  40. // The safe escaped form is to replace every uppercase letter
  41. // with an exclamation mark followed by the letter's lowercase equivalent.
  42. //
  43. // For example,
  44. //
  45. // github.com/Azure/azure-sdk-for-go -> github.com/!azure/azure-sdk-for-go.
  46. // github.com/GoogleCloudPlatform/cloudsql-proxy -> github.com/!google!cloud!platform/cloudsql-proxy
  47. // github.com/Sirupsen/logrus -> github.com/!sirupsen/logrus.
  48. //
  49. // Import paths that avoid upper-case letters are left unchanged.
  50. // Note that because import paths are ASCII-only and avoid various
  51. // problematic punctuation (like : < and >), the escaped form is also ASCII-only
  52. // and avoids the same problematic punctuation.
  53. //
  54. // Import paths have never allowed exclamation marks, so there is no
  55. // need to define how to escape a literal !.
  56. //
  57. // Unicode Restrictions
  58. //
  59. // Today, paths are disallowed from using Unicode.
  60. //
  61. // Although paths are currently disallowed from using Unicode,
  62. // we would like at some point to allow Unicode letters as well, to assume that
  63. // file systems and URLs are Unicode-safe (storing UTF-8), and apply
  64. // the !-for-uppercase convention for escaping them in the file system.
  65. // But there are at least two subtle considerations.
  66. //
  67. // First, note that not all case-fold equivalent distinct runes
  68. // form an upper/lower pair.
  69. // For example, U+004B ('K'), U+006B ('k'), and U+212A ('K' for Kelvin)
  70. // are three distinct runes that case-fold to each other.
  71. // When we do add Unicode letters, we must not assume that upper/lower
  72. // are the only case-equivalent pairs.
  73. // Perhaps the Kelvin symbol would be disallowed entirely, for example.
  74. // Or perhaps it would escape as "!!k", or perhaps as "(212A)".
  75. //
  76. // Second, it would be nice to allow Unicode marks as well as letters,
  77. // but marks include combining marks, and then we must deal not
  78. // only with case folding but also normalization: both U+00E9 ('é')
  79. // and U+0065 U+0301 ('e' followed by combining acute accent)
  80. // look the same on the page and are treated by some file systems
  81. // as the same path. If we do allow Unicode marks in paths, there
  82. // must be some kind of normalization to allow only one canonical
  83. // encoding of any character used in an import path.
  84. package module
  85. // IMPORTANT NOTE
  86. //
  87. // This file essentially defines the set of valid import paths for the go command.
  88. // There are many subtle considerations, including Unicode ambiguity,
  89. // security, network, and file system representations.
  90. //
  91. // This file also defines the set of valid module path and version combinations,
  92. // another topic with many subtle considerations.
  93. //
  94. // Changes to the semantics in this file require approval from rsc.
  95. import (
  96. "fmt"
  97. "sort"
  98. "strings"
  99. "unicode"
  100. "unicode/utf8"
  101. "golang.org/x/mod/semver"
  102. errors "golang.org/x/xerrors"
  103. )
  104. // A Version (for clients, a module.Version) is defined by a module path and version pair.
  105. // These are stored in their plain (unescaped) form.
  106. type Version struct {
  107. // Path is a module path, like "golang.org/x/text" or "rsc.io/quote/v2".
  108. Path string
  109. // Version is usually a semantic version in canonical form.
  110. // There are three exceptions to this general rule.
  111. // First, the top-level target of a build has no specific version
  112. // and uses Version = "".
  113. // Second, during MVS calculations the version "none" is used
  114. // to represent the decision to take no version of a given module.
  115. // Third, filesystem paths found in "replace" directives are
  116. // represented by a path with an empty version.
  117. Version string `json:",omitempty"`
  118. }
  119. // String returns a representation of the Version suitable for logging
  120. // (Path@Version, or just Path if Version is empty).
  121. func (m Version) String() string {
  122. if m.Version == "" {
  123. return m.Path
  124. }
  125. return m.Path + "@" + m.Version
  126. }
  127. // A ModuleError indicates an error specific to a module.
  128. type ModuleError struct {
  129. Path string
  130. Version string
  131. Err error
  132. }
  133. // VersionError returns a ModuleError derived from a Version and error,
  134. // or err itself if it is already such an error.
  135. func VersionError(v Version, err error) error {
  136. var mErr *ModuleError
  137. if errors.As(err, &mErr) && mErr.Path == v.Path && mErr.Version == v.Version {
  138. return err
  139. }
  140. return &ModuleError{
  141. Path: v.Path,
  142. Version: v.Version,
  143. Err: err,
  144. }
  145. }
  146. func (e *ModuleError) Error() string {
  147. if v, ok := e.Err.(*InvalidVersionError); ok {
  148. return fmt.Sprintf("%s@%s: invalid %s: %v", e.Path, v.Version, v.noun(), v.Err)
  149. }
  150. if e.Version != "" {
  151. return fmt.Sprintf("%s@%s: %v", e.Path, e.Version, e.Err)
  152. }
  153. return fmt.Sprintf("module %s: %v", e.Path, e.Err)
  154. }
  155. func (e *ModuleError) Unwrap() error { return e.Err }
  156. // An InvalidVersionError indicates an error specific to a version, with the
  157. // module path unknown or specified externally.
  158. //
  159. // A ModuleError may wrap an InvalidVersionError, but an InvalidVersionError
  160. // must not wrap a ModuleError.
  161. type InvalidVersionError struct {
  162. Version string
  163. Pseudo bool
  164. Err error
  165. }
  166. // noun returns either "version" or "pseudo-version", depending on whether
  167. // e.Version is a pseudo-version.
  168. func (e *InvalidVersionError) noun() string {
  169. if e.Pseudo {
  170. return "pseudo-version"
  171. }
  172. return "version"
  173. }
  174. func (e *InvalidVersionError) Error() string {
  175. return fmt.Sprintf("%s %q invalid: %s", e.noun(), e.Version, e.Err)
  176. }
  177. func (e *InvalidVersionError) Unwrap() error { return e.Err }
  178. // Check checks that a given module path, version pair is valid.
  179. // In addition to the path being a valid module path
  180. // and the version being a valid semantic version,
  181. // the two must correspond.
  182. // For example, the path "yaml/v2" only corresponds to
  183. // semantic versions beginning with "v2.".
  184. func Check(path, version string) error {
  185. if err := CheckPath(path); err != nil {
  186. return err
  187. }
  188. if !semver.IsValid(version) {
  189. return &ModuleError{
  190. Path: path,
  191. Err: &InvalidVersionError{Version: version, Err: errors.New("not a semantic version")},
  192. }
  193. }
  194. _, pathMajor, _ := SplitPathVersion(path)
  195. if err := CheckPathMajor(version, pathMajor); err != nil {
  196. return &ModuleError{Path: path, Err: err}
  197. }
  198. return nil
  199. }
  200. // firstPathOK reports whether r can appear in the first element of a module path.
  201. // The first element of the path must be an LDH domain name, at least for now.
  202. // To avoid case ambiguity, the domain name must be entirely lower case.
  203. func firstPathOK(r rune) bool {
  204. return r == '-' || r == '.' ||
  205. '0' <= r && r <= '9' ||
  206. 'a' <= r && r <= 'z'
  207. }
  208. // pathOK reports whether r can appear in an import path element.
  209. // Paths can be ASCII letters, ASCII digits, and limited ASCII punctuation: + - . _ and ~.
  210. // This matches what "go get" has historically recognized in import paths.
  211. // TODO(rsc): We would like to allow Unicode letters, but that requires additional
  212. // care in the safe encoding (see "escaped paths" above).
  213. func pathOK(r rune) bool {
  214. if r < utf8.RuneSelf {
  215. return r == '+' || r == '-' || r == '.' || r == '_' || r == '~' ||
  216. '0' <= r && r <= '9' ||
  217. 'A' <= r && r <= 'Z' ||
  218. 'a' <= r && r <= 'z'
  219. }
  220. return false
  221. }
  222. // fileNameOK reports whether r can appear in a file name.
  223. // For now we allow all Unicode letters but otherwise limit to pathOK plus a few more punctuation characters.
  224. // If we expand the set of allowed characters here, we have to
  225. // work harder at detecting potential case-folding and normalization collisions.
  226. // See note about "escaped paths" above.
  227. func fileNameOK(r rune) bool {
  228. if r < utf8.RuneSelf {
  229. // Entire set of ASCII punctuation, from which we remove characters:
  230. // ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~
  231. // We disallow some shell special characters: " ' * < > ? ` |
  232. // (Note that some of those are disallowed by the Windows file system as well.)
  233. // We also disallow path separators / : and \ (fileNameOK is only called on path element characters).
  234. // We allow spaces (U+0020) in file names.
  235. const allowed = "!#$%&()+,-.=@[]^_{}~ "
  236. if '0' <= r && r <= '9' || 'A' <= r && r <= 'Z' || 'a' <= r && r <= 'z' {
  237. return true
  238. }
  239. for i := 0; i < len(allowed); i++ {
  240. if rune(allowed[i]) == r {
  241. return true
  242. }
  243. }
  244. return false
  245. }
  246. // It may be OK to add more ASCII punctuation here, but only carefully.
  247. // For example Windows disallows < > \, and macOS disallows :, so we must not allow those.
  248. return unicode.IsLetter(r)
  249. }
  250. // CheckPath checks that a module path is valid.
  251. // A valid module path is a valid import path, as checked by CheckImportPath,
  252. // with two additional constraints.
  253. // First, the leading path element (up to the first slash, if any),
  254. // by convention a domain name, must contain only lower-case ASCII letters,
  255. // ASCII digits, dots (U+002E), and dashes (U+002D);
  256. // it must contain at least one dot and cannot start with a dash.
  257. // Second, for a final path element of the form /vN, where N looks numeric
  258. // (ASCII digits and dots) must not begin with a leading zero, must not be /v1,
  259. // and must not contain any dots. For paths beginning with "gopkg.in/",
  260. // this second requirement is replaced by a requirement that the path
  261. // follow the gopkg.in server's conventions.
  262. func CheckPath(path string) error {
  263. if err := checkPath(path, false); err != nil {
  264. return fmt.Errorf("malformed module path %q: %v", path, err)
  265. }
  266. i := strings.Index(path, "/")
  267. if i < 0 {
  268. i = len(path)
  269. }
  270. if i == 0 {
  271. return fmt.Errorf("malformed module path %q: leading slash", path)
  272. }
  273. if !strings.Contains(path[:i], ".") {
  274. return fmt.Errorf("malformed module path %q: missing dot in first path element", path)
  275. }
  276. if path[0] == '-' {
  277. return fmt.Errorf("malformed module path %q: leading dash in first path element", path)
  278. }
  279. for _, r := range path[:i] {
  280. if !firstPathOK(r) {
  281. return fmt.Errorf("malformed module path %q: invalid char %q in first path element", path, r)
  282. }
  283. }
  284. if _, _, ok := SplitPathVersion(path); !ok {
  285. return fmt.Errorf("malformed module path %q: invalid version", path)
  286. }
  287. return nil
  288. }
  289. // CheckImportPath checks that an import path is valid.
  290. //
  291. // A valid import path consists of one or more valid path elements
  292. // separated by slashes (U+002F). (It must not begin with nor end in a slash.)
  293. //
  294. // A valid path element is a non-empty string made up of
  295. // ASCII letters, ASCII digits, and limited ASCII punctuation: + - . _ and ~.
  296. // It must not begin or end with a dot (U+002E), nor contain two dots in a row.
  297. //
  298. // The element prefix up to the first dot must not be a reserved file name
  299. // on Windows, regardless of case (CON, com1, NuL, and so on).
  300. //
  301. // CheckImportPath may be less restrictive in the future, but see the
  302. // top-level package documentation for additional information about
  303. // subtleties of Unicode.
  304. func CheckImportPath(path string) error {
  305. if err := checkPath(path, false); err != nil {
  306. return fmt.Errorf("malformed import path %q: %v", path, err)
  307. }
  308. return nil
  309. }
  310. // checkPath checks that a general path is valid.
  311. // It returns an error describing why but not mentioning path.
  312. // Because these checks apply to both module paths and import paths,
  313. // the caller is expected to add the "malformed ___ path %q: " prefix.
  314. // fileName indicates whether the final element of the path is a file name
  315. // (as opposed to a directory name).
  316. func checkPath(path string, fileName bool) error {
  317. if !utf8.ValidString(path) {
  318. return fmt.Errorf("invalid UTF-8")
  319. }
  320. if path == "" {
  321. return fmt.Errorf("empty string")
  322. }
  323. if path[0] == '-' {
  324. return fmt.Errorf("leading dash")
  325. }
  326. if strings.Contains(path, "//") {
  327. return fmt.Errorf("double slash")
  328. }
  329. if path[len(path)-1] == '/' {
  330. return fmt.Errorf("trailing slash")
  331. }
  332. elemStart := 0
  333. for i, r := range path {
  334. if r == '/' {
  335. if err := checkElem(path[elemStart:i], fileName); err != nil {
  336. return err
  337. }
  338. elemStart = i + 1
  339. }
  340. }
  341. if err := checkElem(path[elemStart:], fileName); err != nil {
  342. return err
  343. }
  344. return nil
  345. }
  346. // checkElem checks whether an individual path element is valid.
  347. // fileName indicates whether the element is a file name (not a directory name).
  348. func checkElem(elem string, fileName bool) error {
  349. if elem == "" {
  350. return fmt.Errorf("empty path element")
  351. }
  352. if strings.Count(elem, ".") == len(elem) {
  353. return fmt.Errorf("invalid path element %q", elem)
  354. }
  355. if elem[0] == '.' && !fileName {
  356. return fmt.Errorf("leading dot in path element")
  357. }
  358. if elem[len(elem)-1] == '.' {
  359. return fmt.Errorf("trailing dot in path element")
  360. }
  361. charOK := pathOK
  362. if fileName {
  363. charOK = fileNameOK
  364. }
  365. for _, r := range elem {
  366. if !charOK(r) {
  367. return fmt.Errorf("invalid char %q", r)
  368. }
  369. }
  370. // Windows disallows a bunch of path elements, sadly.
  371. // See https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file
  372. short := elem
  373. if i := strings.Index(short, "."); i >= 0 {
  374. short = short[:i]
  375. }
  376. for _, bad := range badWindowsNames {
  377. if strings.EqualFold(bad, short) {
  378. return fmt.Errorf("%q disallowed as path element component on Windows", short)
  379. }
  380. }
  381. return nil
  382. }
  383. // CheckFilePath checks that a slash-separated file path is valid.
  384. // The definition of a valid file path is the same as the definition
  385. // of a valid import path except that the set of allowed characters is larger:
  386. // all Unicode letters, ASCII digits, the ASCII space character (U+0020),
  387. // and the ASCII punctuation characters
  388. // “!#$%&()+,-.=@[]^_{}~”.
  389. // (The excluded punctuation characters, " * < > ? ` ' | / \ and :,
  390. // have special meanings in certain shells or operating systems.)
  391. //
  392. // CheckFilePath may be less restrictive in the future, but see the
  393. // top-level package documentation for additional information about
  394. // subtleties of Unicode.
  395. func CheckFilePath(path string) error {
  396. if err := checkPath(path, true); err != nil {
  397. return fmt.Errorf("malformed file path %q: %v", path, err)
  398. }
  399. return nil
  400. }
  401. // badWindowsNames are the reserved file path elements on Windows.
  402. // See https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file
  403. var badWindowsNames = []string{
  404. "CON",
  405. "PRN",
  406. "AUX",
  407. "NUL",
  408. "COM1",
  409. "COM2",
  410. "COM3",
  411. "COM4",
  412. "COM5",
  413. "COM6",
  414. "COM7",
  415. "COM8",
  416. "COM9",
  417. "LPT1",
  418. "LPT2",
  419. "LPT3",
  420. "LPT4",
  421. "LPT5",
  422. "LPT6",
  423. "LPT7",
  424. "LPT8",
  425. "LPT9",
  426. }
  427. // SplitPathVersion returns prefix and major version such that prefix+pathMajor == path
  428. // and version is either empty or "/vN" for N >= 2.
  429. // As a special case, gopkg.in paths are recognized directly;
  430. // they require ".vN" instead of "/vN", and for all N, not just N >= 2.
  431. // SplitPathVersion returns with ok = false when presented with
  432. // a path whose last path element does not satisfy the constraints
  433. // applied by CheckPath, such as "example.com/pkg/v1" or "example.com/pkg/v1.2".
  434. func SplitPathVersion(path string) (prefix, pathMajor string, ok bool) {
  435. if strings.HasPrefix(path, "gopkg.in/") {
  436. return splitGopkgIn(path)
  437. }
  438. i := len(path)
  439. dot := false
  440. for i > 0 && ('0' <= path[i-1] && path[i-1] <= '9' || path[i-1] == '.') {
  441. if path[i-1] == '.' {
  442. dot = true
  443. }
  444. i--
  445. }
  446. if i <= 1 || i == len(path) || path[i-1] != 'v' || path[i-2] != '/' {
  447. return path, "", true
  448. }
  449. prefix, pathMajor = path[:i-2], path[i-2:]
  450. if dot || len(pathMajor) <= 2 || pathMajor[2] == '0' || pathMajor == "/v1" {
  451. return path, "", false
  452. }
  453. return prefix, pathMajor, true
  454. }
  455. // splitGopkgIn is like SplitPathVersion but only for gopkg.in paths.
  456. func splitGopkgIn(path string) (prefix, pathMajor string, ok bool) {
  457. if !strings.HasPrefix(path, "gopkg.in/") {
  458. return path, "", false
  459. }
  460. i := len(path)
  461. if strings.HasSuffix(path, "-unstable") {
  462. i -= len("-unstable")
  463. }
  464. for i > 0 && ('0' <= path[i-1] && path[i-1] <= '9') {
  465. i--
  466. }
  467. if i <= 1 || path[i-1] != 'v' || path[i-2] != '.' {
  468. // All gopkg.in paths must end in vN for some N.
  469. return path, "", false
  470. }
  471. prefix, pathMajor = path[:i-2], path[i-2:]
  472. if len(pathMajor) <= 2 || pathMajor[2] == '0' && pathMajor != ".v0" {
  473. return path, "", false
  474. }
  475. return prefix, pathMajor, true
  476. }
  477. // MatchPathMajor reports whether the semantic version v
  478. // matches the path major version pathMajor.
  479. //
  480. // MatchPathMajor returns true if and only if CheckPathMajor returns nil.
  481. func MatchPathMajor(v, pathMajor string) bool {
  482. return CheckPathMajor(v, pathMajor) == nil
  483. }
  484. // CheckPathMajor returns a non-nil error if the semantic version v
  485. // does not match the path major version pathMajor.
  486. func CheckPathMajor(v, pathMajor string) error {
  487. // TODO(jayconrod): return errors or panic for invalid inputs. This function
  488. // (and others) was covered by integration tests for cmd/go, and surrounding
  489. // code protected against invalid inputs like non-canonical versions.
  490. if strings.HasPrefix(pathMajor, ".v") && strings.HasSuffix(pathMajor, "-unstable") {
  491. pathMajor = strings.TrimSuffix(pathMajor, "-unstable")
  492. }
  493. if strings.HasPrefix(v, "v0.0.0-") && pathMajor == ".v1" {
  494. // Allow old bug in pseudo-versions that generated v0.0.0- pseudoversion for gopkg .v1.
  495. // For example, gopkg.in/yaml.v2@v2.2.1's go.mod requires gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405.
  496. return nil
  497. }
  498. m := semver.Major(v)
  499. if pathMajor == "" {
  500. if m == "v0" || m == "v1" || semver.Build(v) == "+incompatible" {
  501. return nil
  502. }
  503. pathMajor = "v0 or v1"
  504. } else if pathMajor[0] == '/' || pathMajor[0] == '.' {
  505. if m == pathMajor[1:] {
  506. return nil
  507. }
  508. pathMajor = pathMajor[1:]
  509. }
  510. return &InvalidVersionError{
  511. Version: v,
  512. Err: fmt.Errorf("should be %s, not %s", pathMajor, semver.Major(v)),
  513. }
  514. }
  515. // PathMajorPrefix returns the major-version tag prefix implied by pathMajor.
  516. // An empty PathMajorPrefix allows either v0 or v1.
  517. //
  518. // Note that MatchPathMajor may accept some versions that do not actually begin
  519. // with this prefix: namely, it accepts a 'v0.0.0-' prefix for a '.v1'
  520. // pathMajor, even though that pathMajor implies 'v1' tagging.
  521. func PathMajorPrefix(pathMajor string) string {
  522. if pathMajor == "" {
  523. return ""
  524. }
  525. if pathMajor[0] != '/' && pathMajor[0] != '.' {
  526. panic("pathMajor suffix " + pathMajor + " passed to PathMajorPrefix lacks separator")
  527. }
  528. if strings.HasPrefix(pathMajor, ".v") && strings.HasSuffix(pathMajor, "-unstable") {
  529. pathMajor = strings.TrimSuffix(pathMajor, "-unstable")
  530. }
  531. m := pathMajor[1:]
  532. if m != semver.Major(m) {
  533. panic("pathMajor suffix " + pathMajor + "passed to PathMajorPrefix is not a valid major version")
  534. }
  535. return m
  536. }
  537. // CanonicalVersion returns the canonical form of the version string v.
  538. // It is the same as semver.Canonical(v) except that it preserves the special build suffix "+incompatible".
  539. func CanonicalVersion(v string) string {
  540. cv := semver.Canonical(v)
  541. if semver.Build(v) == "+incompatible" {
  542. cv += "+incompatible"
  543. }
  544. return cv
  545. }
  546. // Sort sorts the list by Path, breaking ties by comparing Version fields.
  547. // The Version fields are interpreted as semantic versions (using semver.Compare)
  548. // optionally followed by a tie-breaking suffix introduced by a slash character,
  549. // like in "v0.0.1/go.mod".
  550. func Sort(list []Version) {
  551. sort.Slice(list, func(i, j int) bool {
  552. mi := list[i]
  553. mj := list[j]
  554. if mi.Path != mj.Path {
  555. return mi.Path < mj.Path
  556. }
  557. // To help go.sum formatting, allow version/file.
  558. // Compare semver prefix by semver rules,
  559. // file by string order.
  560. vi := mi.Version
  561. vj := mj.Version
  562. var fi, fj string
  563. if k := strings.Index(vi, "/"); k >= 0 {
  564. vi, fi = vi[:k], vi[k:]
  565. }
  566. if k := strings.Index(vj, "/"); k >= 0 {
  567. vj, fj = vj[:k], vj[k:]
  568. }
  569. if vi != vj {
  570. return semver.Compare(vi, vj) < 0
  571. }
  572. return fi < fj
  573. })
  574. }
  575. // EscapePath returns the escaped form of the given module path.
  576. // It fails if the module path is invalid.
  577. func EscapePath(path string) (escaped string, err error) {
  578. if err := CheckPath(path); err != nil {
  579. return "", err
  580. }
  581. return escapeString(path)
  582. }
  583. // EscapeVersion returns the escaped form of the given module version.
  584. // Versions are allowed to be in non-semver form but must be valid file names
  585. // and not contain exclamation marks.
  586. func EscapeVersion(v string) (escaped string, err error) {
  587. if err := checkElem(v, true); err != nil || strings.Contains(v, "!") {
  588. return "", &InvalidVersionError{
  589. Version: v,
  590. Err: fmt.Errorf("disallowed version string"),
  591. }
  592. }
  593. return escapeString(v)
  594. }
  595. func escapeString(s string) (escaped string, err error) {
  596. haveUpper := false
  597. for _, r := range s {
  598. if r == '!' || r >= utf8.RuneSelf {
  599. // This should be disallowed by CheckPath, but diagnose anyway.
  600. // The correctness of the escaping loop below depends on it.
  601. return "", fmt.Errorf("internal error: inconsistency in EscapePath")
  602. }
  603. if 'A' <= r && r <= 'Z' {
  604. haveUpper = true
  605. }
  606. }
  607. if !haveUpper {
  608. return s, nil
  609. }
  610. var buf []byte
  611. for _, r := range s {
  612. if 'A' <= r && r <= 'Z' {
  613. buf = append(buf, '!', byte(r+'a'-'A'))
  614. } else {
  615. buf = append(buf, byte(r))
  616. }
  617. }
  618. return string(buf), nil
  619. }
  620. // UnescapePath returns the module path for the given escaped path.
  621. // It fails if the escaped path is invalid or describes an invalid path.
  622. func UnescapePath(escaped string) (path string, err error) {
  623. path, ok := unescapeString(escaped)
  624. if !ok {
  625. return "", fmt.Errorf("invalid escaped module path %q", escaped)
  626. }
  627. if err := CheckPath(path); err != nil {
  628. return "", fmt.Errorf("invalid escaped module path %q: %v", escaped, err)
  629. }
  630. return path, nil
  631. }
  632. // UnescapeVersion returns the version string for the given escaped version.
  633. // It fails if the escaped form is invalid or describes an invalid version.
  634. // Versions are allowed to be in non-semver form but must be valid file names
  635. // and not contain exclamation marks.
  636. func UnescapeVersion(escaped string) (v string, err error) {
  637. v, ok := unescapeString(escaped)
  638. if !ok {
  639. return "", fmt.Errorf("invalid escaped version %q", escaped)
  640. }
  641. if err := checkElem(v, true); err != nil {
  642. return "", fmt.Errorf("invalid escaped version %q: %v", v, err)
  643. }
  644. return v, nil
  645. }
  646. func unescapeString(escaped string) (string, bool) {
  647. var buf []byte
  648. bang := false
  649. for _, r := range escaped {
  650. if r >= utf8.RuneSelf {
  651. return "", false
  652. }
  653. if bang {
  654. bang = false
  655. if r < 'a' || 'z' < r {
  656. return "", false
  657. }
  658. buf = append(buf, byte(r+'A'-'a'))
  659. continue
  660. }
  661. if r == '!' {
  662. bang = true
  663. continue
  664. }
  665. if 'A' <= r && r <= 'Z' {
  666. return "", false
  667. }
  668. buf = append(buf, byte(r))
  669. }
  670. if bang {
  671. return "", false
  672. }
  673. return string(buf), true
  674. }