version.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. // GetVersion returns current Git version installed.
  64. func GetVersion() (*Version, error) {
  65. if gitVer != nil {
  66. return gitVer, nil
  67. }
  68. stdout, stderr, err := com.ExecCmd("git", "version")
  69. if err != nil {
  70. return nil, errors.New(stderr)
  71. }
  72. infos := strings.Split(stdout, " ")
  73. if len(infos) < 3 {
  74. return nil, errors.New("not enough output")
  75. }
  76. gitVer, err = ParseVersion(infos[2])
  77. return gitVer, err
  78. }