1010
1111import func POSIX. realpath
1212import func POSIX. getenv
13+ import libc
1314
1415public class Git {
1516 public class Repo {
@@ -23,7 +24,7 @@ public class Git {
2324
2425 public lazy var origin : String ? = { repo in
2526 do {
26- guard let url = try popen ( [ Git . tool, " -C " , repo. path, " config " , " --get " , " remote.origin.url " ] ) . chuzzle ( ) else {
27+ guard let url = try Git . runPopen ( [ Git . tool, " -C " , repo. path, " config " , " --get " , " remote.origin.url " ] ) . chuzzle ( ) else {
2728 return nil
2829 }
2930 if URL . scheme ( url) == nil {
@@ -40,15 +41,54 @@ public class Git {
4041 } ( self )
4142
4243 public var branch : String ! {
43- return try ? popen ( [ Git . tool, " -C " , path, " rev-parse " , " --abbrev-ref " , " HEAD " ] ) . chomp ( )
44+ return try ? Git . runPopen ( [ Git . tool, " -C " , path, " rev-parse " , " --abbrev-ref " , " HEAD " ] ) . chomp ( )
4445 }
4546
4647 public func fetch( ) throws {
47- try system ( Git . tool, " -C " , path, " fetch " , " --tags " , " origin " , message: nil )
48+ do {
49+ try system ( Git . tool, " -C " , path, " fetch " , " --tags " , " origin " , message: nil )
50+ } catch let errror {
51+ Git . handle ( errror)
52+ }
4853 }
4954 }
5055
5156 public class var tool : String {
5257 return getenv ( " SWIFT_GIT " ) ?? " git "
5358 }
59+
60+ public class var version : String ! {
61+ return try ? Git . runPopen ( [ Git . tool, " version " ] )
62+ }
63+
64+ public class var majorVersionNumber : Int ? {
65+ let prefix = " git version "
66+ var version = self . version
67+ if version. hasPrefix ( prefix) {
68+ let prefixRange = version. startIndex... version. startIndex. advanced ( by: prefix. characters. count)
69+ version. removeSubrange ( prefixRange)
70+ }
71+ guard let first = version. characters. first else {
72+ return nil
73+ }
74+ return Int ( String ( first) )
75+ }
76+
77+ @noreturn public class func handle( error: ErrorProtocol ) {
78+ // Git 2.0 or higher is required
79+ if Git . majorVersionNumber < 2 {
80+ print ( " error: " , Error . ObsoleteGitVersion)
81+ } else {
82+ print ( " error: " , Error . UnknownGitError)
83+ }
84+ exit ( 1 )
85+ }
86+
87+ public class func runPopen( arguments: [ String ] ) throws -> String {
88+ do {
89+ return try popen ( arguments)
90+ } catch let error {
91+ handle ( error)
92+ }
93+ }
5494}
0 commit comments