git-version.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. export class GitVersion {
  2. private readonly major: number = NaN
  3. private readonly minor: number = NaN
  4. private readonly patch: number = NaN
  5. /**
  6. * Used for comparing the version of git and git-lfs against the minimum required version
  7. * @param version the version string, e.g. 1.2 or 1.2.3
  8. */
  9. constructor(version?: string) {
  10. if (version) {
  11. const match = version.match(/^(\d+)\.(\d+)(\.(\d+))?$/)
  12. if (match) {
  13. this.major = Number(match[1])
  14. this.minor = Number(match[2])
  15. if (match[4]) {
  16. this.patch = Number(match[4])
  17. }
  18. }
  19. }
  20. }
  21. /**
  22. * Compares the instance against a minimum required version
  23. * @param minimum Minimum version
  24. */
  25. checkMinimum(minimum: GitVersion): boolean {
  26. if (!minimum.isValid()) {
  27. throw new Error('Arg minimum is not a valid version')
  28. }
  29. // Major is insufficient
  30. if (this.major < minimum.major) {
  31. return false
  32. }
  33. // Major is equal
  34. if (this.major === minimum.major) {
  35. // Minor is insufficient
  36. if (this.minor < minimum.minor) {
  37. return false
  38. }
  39. // Minor is equal
  40. if (this.minor === minimum.minor) {
  41. // Patch is insufficient
  42. if (this.patch && this.patch < (minimum.patch || 0)) {
  43. return false
  44. }
  45. }
  46. }
  47. return true
  48. }
  49. /**
  50. * Indicates whether the instance was constructed from a valid version string
  51. */
  52. isValid(): boolean {
  53. return !isNaN(this.major)
  54. }
  55. /**
  56. * Returns the version as a string, e.g. 1.2 or 1.2.3
  57. */
  58. toString(): string {
  59. let result = ''
  60. if (this.isValid()) {
  61. result = `${this.major}.${this.minor}`
  62. if (!isNaN(this.patch)) {
  63. result += `.${this.patch}`
  64. }
  65. }
  66. return result
  67. }
  68. }