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

104 lines
1.9 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package git
  5. import (
  6. "errors"
  7. "fmt"
  8. "strings"
  9. "github.com/Unknwon/com"
  10. )
  11. var (
  12. // Cached Git version.
  13. gitVer *Version
  14. )
  15. // Version represents version of Git.
  16. type Version struct {
  17. Major, Minor, Patch int
  18. }
  19. func ParseVersion(verStr string) (*Version, error) {
  20. infos := strings.Split(verStr, ".")
  21. if len(infos) < 3 {
  22. return nil, errors.New("incorrect version input")
  23. }
  24. v := &Version{}
  25. for i, s := range infos {
  26. switch i {
  27. case 0:
  28. v.Major, _ = com.StrTo(s).Int()
  29. case 1:
  30. v.Minor, _ = com.StrTo(s).Int()
  31. case 2:
  32. v.Patch, _ = com.StrTo(strings.TrimSpace(s)).Int()
  33. }
  34. }
  35. return v, nil
  36. }
  37. func MustParseVersion(verStr string) *Version {
  38. v, _ := ParseVersion(verStr)
  39. return v
  40. }
  41. // Compare compares two versions,
  42. // it returns 1 if original is greater, -1 if original is smaller, 0 if equal.
  43. func (v *Version) Compare(that *Version) int {
  44. if v.Major > that.Major {
  45. return 1
  46. } else if v.Major < that.Major {
  47. return -1
  48. }
  49. if v.Minor > that.Minor {
  50. return 1
  51. } else if v.Minor < that.Minor {
  52. return -1
  53. }
  54. if v.Patch > that.Patch {
  55. return 1
  56. } else if v.Patch < that.Patch {
  57. return -1
  58. }
  59. return 0
  60. }
  61. func (v *Version) LessThan(that *Version) bool {
  62. return v.Compare(that) < 0
  63. }
  64. func (v *Version) AtLeast(that *Version) bool {
  65. return v.Compare(that) >= 0
  66. }
  67. func (v *Version) String() string {
  68. return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
  69. }
  70. // GetVersion returns current Git version installed.
  71. func GetVersion() (*Version, error) {
  72. if gitVer != nil {
  73. return gitVer, nil
  74. }
  75. stdout, stderr, err := com.ExecCmd("git", "version")
  76. if err != nil {
  77. return nil, errors.New(stderr)
  78. }
  79. infos := strings.Split(stdout, " ")
  80. if len(infos) < 3 {
  81. return nil, errors.New("not enough output")
  82. }
  83. gitVer, err = ParseVersion(infos[2])
  84. return gitVer, err
  85. }