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.

99 lines
1.8 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. "strings"
  8. "github.com/Unknwon/com"
  9. )
  10. var (
  11. // Cached Git version.
  12. gitVer *Version
  13. )
  14. // Version represents version of Git.
  15. type Version struct {
  16. Major, Minor, Patch int
  17. }
  18. func ParseVersion(verStr string) (*Version, error) {
  19. infos := strings.Split(verStr, ".")
  20. if len(infos) < 3 {
  21. return nil, errors.New("incorrect version input")
  22. }
  23. v := &Version{}
  24. for i, s := range infos {
  25. switch i {
  26. case 0:
  27. v.Major, _ = com.StrTo(s).Int()
  28. case 1:
  29. v.Minor, _ = com.StrTo(s).Int()
  30. case 2:
  31. v.Patch, _ = com.StrTo(strings.TrimSpace(s)).Int()
  32. }
  33. }
  34. return v, nil
  35. }
  36. func MustParseVersion(verStr string) *Version {
  37. v, _ := ParseVersion(verStr)
  38. return v
  39. }
  40. // Compare compares two versions,
  41. // it returns 1 if original is greater, -1 if original is smaller, 0 if equal.
  42. func (v *Version) Compare(that *Version) int {
  43. if v.Major > that.Major {
  44. return 1
  45. } else if v.Major < that.Major {
  46. return -1
  47. }
  48. if v.Minor > that.Minor {
  49. return 1
  50. } else if v.Minor < that.Minor {
  51. return -1
  52. }
  53. if v.Patch > that.Patch {
  54. return 1
  55. } else if v.Patch < that.Patch {
  56. return -1
  57. }
  58. return 0
  59. }
  60. func (v *Version) LessThan(that *Version) bool {
  61. return v.Compare(that) < 0
  62. }
  63. func (v *Version) AtLeast(that *Version) bool {
  64. return v.Compare(that) >= 0
  65. }
  66. // GetVersion returns current Git version installed.
  67. func GetVersion() (*Version, error) {
  68. if gitVer != nil {
  69. return gitVer, nil
  70. }
  71. stdout, stderr, err := com.ExecCmd("git", "version")
  72. if err != nil {
  73. return nil, errors.New(stderr)
  74. }
  75. infos := strings.Split(stdout, " ")
  76. if len(infos) < 3 {
  77. return nil, errors.New("not enough output")
  78. }
  79. gitVer, err = ParseVersion(infos[2])
  80. return gitVer, err
  81. }