version.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. }