-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
GitRepository.swift
1411 lines (1237 loc) · 49.3 KB
/
GitRepository.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basics
import Dispatch
import class Foundation.NSLock
import struct TSCBasic.ByteString
import protocol TSCBasic.DiagnosticLocation
import struct TSCBasic.FileInfo
import enum TSCBasic.FileMode
import struct TSCBasic.FileSystemError
import class TSCBasic.Process
import enum TSCBasic.ProcessEnv
import struct TSCBasic.ProcessResult
import struct TSCBasic.RegEx
import protocol TSCUtility.DiagnosticLocationProviding
import enum TSCUtility.Git
// MARK: - GitShellHelper
/// Helper for shelling out to `git`
private struct GitShellHelper {
private let cancellator: Cancellator
init(cancellator: Cancellator) {
self.cancellator = cancellator
}
/// Private function to invoke the Git tool with its default environment and given set of arguments. The specified
/// failure message is used only in case of error. This function waits for the invocation to finish and returns the
/// output as a string.
func run(
_ args: [String],
environment: EnvironmentVariables = Git.environment,
outputRedirection: TSCBasic.Process.OutputRedirection = .collect
) throws -> String {
let process = TSCBasic.Process(
arguments: [Git.tool] + args,
environment: environment,
outputRedirection: outputRedirection
)
let result: ProcessResult
do {
guard let terminationKey = self.cancellator.register(process) else {
throw CancellationError() // terminating
}
defer { self.cancellator.deregister(terminationKey) }
try process.launch()
result = try process.waitUntilExit()
guard result.exitStatus == .terminated(code: 0) else {
throw GitShellError(result: result)
}
return try result.utf8Output().spm_chomp()
} catch let error as GitShellError {
throw error
} catch {
// Handle a failure to even launch the Git tool by synthesizing a result that we can wrap an error around.
let result = ProcessResult(
arguments: process.arguments,
environment: process.environment,
exitStatus: .terminated(code: -1),
output: .failure(error),
stderrOutput: .failure(error)
)
throw GitShellError(result: result)
}
}
}
// MARK: - GitRepositoryProvider
/// A `git` repository provider.
public struct GitRepositoryProvider: RepositoryProvider, Cancellable {
private let cancellator: Cancellator
private let git: GitShellHelper
private var repositoryCache = ThreadSafeKeyValueStore<String, Repository>()
public init() {
// helper to cancel outstanding processes
self.cancellator = Cancellator(observabilityScope: .none)
// helper to abstract shelling out to git
self.git = GitShellHelper(cancellator: cancellator)
}
@discardableResult
private func callGit(
_ args: [String],
environment: EnvironmentVariables = Git.environment,
repository: RepositorySpecifier,
failureMessage: String = "",
progress: FetchProgress.Handler? = nil
) throws -> String {
if let progress {
var stdoutBytes: [UInt8] = [], stderrBytes: [UInt8] = []
do {
// Capture stdout and stderr from the Git subprocess invocation, but also pass along stderr to the
// handler. We count on it being line-buffered.
let outputHandler = Process.OutputRedirection.stream(stdout: { stdoutBytes += $0 }, stderr: {
stderrBytes += $0
gitFetchStatusFilter($0, progress: progress)
})
return try self.git.run(
args + ["--progress"],
environment: environment,
outputRedirection: outputHandler
)
} catch let error as GitShellError {
let result = ProcessResult(
arguments: error.result.arguments,
environment: error.result.environment,
exitStatus: error.result.exitStatus,
output: .success(stdoutBytes),
stderrOutput: .success(stderrBytes)
)
throw GitCloneError(repository: repository, message: failureMessage, result: result)
}
} else {
do {
return try self.git.run(args, environment: environment)
} catch let error as GitShellError {
throw GitCloneError(repository: repository, message: failureMessage, result: error.result)
}
}
}
@discardableResult
private func callGit(
_ args: String...,
environment: EnvironmentVariables = Git.environment,
repository: RepositorySpecifier,
failureMessage: String = "",
progress: FetchProgress.Handler? = nil
) throws -> String {
try callGit(
args.map { $0 },
environment: environment,
repository: repository,
failureMessage: failureMessage,
progress: progress
)
}
private func clone(
_ repository: RepositorySpecifier,
_ origin: String,
_ destination: String,
_ options: [String],
progress: FetchProgress.Handler? = nil
) throws {
let invocation: [String] = [
"clone",
// Enable symbolic links for Windows support.
"-c", "core.symlinks=true",
// Disable fsmonitor to avoid spawning a monitor process.
"-c", "core.fsmonitor=false",
// Enable long path support on Windows as otherwise we are limited
// to 261 characters in the complete path.
"-c", "core.longpaths=true",
] + options + [origin, destination]
try self.callGit(
invocation,
repository: repository,
failureMessage: "Failed to clone repository \(repository.location)",
progress: progress
)
}
public func fetch(
repository: RepositorySpecifier,
to path: Basics.AbsolutePath,
progressHandler: FetchProgress.Handler? = nil
) throws {
// Perform a bare clone.
//
// NOTE: We intentionally do not create a shallow clone here; the
// expected cost of iterative updates on a full clone is less than on a
// shallow clone.
guard !localFileSystem.exists(path) else {
throw InternalError("\(path) already exists")
}
try self.clone(
repository,
repository.location.gitURL,
path.pathString,
["--mirror"],
progress: progressHandler
)
}
public func repositoryExists(at directory: Basics.AbsolutePath) -> Bool {
return localFileSystem.isDirectory(directory)
}
public func isValidDirectory(_ directory: Basics.AbsolutePath) throws -> Bool {
let result = try self.git.run(["-C", directory.pathString, "rev-parse", "--git-dir"])
return result == ".git" || result == "." || result == directory.pathString
}
public func isValidDirectory(_ directory: Basics.AbsolutePath, for repository: RepositorySpecifier) throws -> Bool {
let remoteURL = try self.git.run(["-C", directory.pathString, "config", "--get", "remote.origin.url"])
return remoteURL == repository.url
}
public func copy(from sourcePath: Basics.AbsolutePath, to destinationPath: Basics.AbsolutePath) throws {
try localFileSystem.copy(from: sourcePath, to: destinationPath)
}
public func open(repository: RepositorySpecifier, at path: Basics.AbsolutePath) -> Repository {
let key = "\(repository)@\(path)"
return self.repositoryCache.memoize(key) {
GitRepository(git: self.git, path: path, isWorkingRepo: false)
}
}
public func createWorkingCopy(
repository: RepositorySpecifier,
sourcePath: Basics.AbsolutePath,
at destinationPath: Basics.AbsolutePath,
editable: Bool
) throws -> WorkingCheckout {
if editable {
// For editable clones, i.e. the user is expected to directly work on them, first we create
// a clone from our cache of repositories and then we replace the remote to the one originally
// present in the bare repository.
try self.clone(
repository,
sourcePath.pathString,
destinationPath.pathString,
["--no-checkout"]
)
// The default name of the remote.
let origin = "origin"
// In destination repo remove the remote which will be pointing to the source repo.
let clone = GitRepository(git: self.git, path: destinationPath)
// Set the original remote to the new clone.
try clone.setURL(remote: origin, url: repository.location.gitURL)
// FIXME: This is unfortunate that we have to fetch to update remote's data.
try clone.fetch()
} else {
// Clone using a shared object store with the canonical copy.
//
// We currently expect using shared storage here to be safe because we
// only ever expect to attempt to use the working copy to materialize a
// revision we selected in response to dependency resolution, and if we
// re-resolve such that the objects in this repository changed, we would
// only ever expect to get back a revision that remains present in the
// object storage.
try self.clone(
repository,
sourcePath.pathString,
destinationPath.pathString,
["--shared", "--no-checkout"]
)
}
return try self.openWorkingCopy(at: destinationPath)
}
public func workingCopyExists(at path: Basics.AbsolutePath) throws -> Bool {
guard localFileSystem.exists(path) else {
throw InternalError("\(path) does not exist")
}
let repo = GitRepository(git: self.git, path: path)
return try repo.checkoutExists()
}
public func openWorkingCopy(at path: Basics.AbsolutePath) throws -> WorkingCheckout {
GitRepository(git: self.git, path: path)
}
public func cancel(deadline: DispatchTime) throws {
try self.cancellator.cancel(deadline: deadline)
}
}
// MARK: - GitRepository
// FIXME: Currently, this class is serving two goals, it is the Repository
// interface used by `RepositoryProvider`, but is also a class which can be
// instantiated directly against non-RepositoryProvider controlled
// repositories. This may prove inconvenient if what is currently `Repository`
// becomes inconvenient or incompatible with the ideal interface for this
// class. It is possible we should rename `Repository` to something more
// abstract, and change the provider to just return an adaptor around this
// class.
//
/// A basic Git repository in the local file system (almost always a clone of a remote). This class is thread safe.
public final class GitRepository: Repository, WorkingCheckout {
/// A hash object.
public struct Hash: Hashable {
// FIXME: We should optimize this representation.
let bytes: ByteString
/// Create a hash from the given hexadecimal representation.
///
/// - Returns; The hash, or nil if the identifier is invalid.
public init?(_ identifier: String) {
self.init(asciiBytes: ByteString(encodingAsUTF8: identifier).contents)
}
/// Create a hash from the given ASCII bytes.
///
/// - Returns; The hash, or nil if the identifier is invalid.
init?<C: Collection>(asciiBytes bytes: C) where C.Iterator.Element == UInt8 {
if bytes.count != 40 {
return nil
}
for byte in bytes {
switch byte {
case UInt8(ascii: "0") ... UInt8(ascii: "9"),
UInt8(ascii: "a") ... UInt8(ascii: "z"):
continue
default:
return nil
}
}
self.bytes = ByteString(bytes)
}
}
/// A commit object.
public struct Commit: Equatable {
/// The object hash.
public let hash: Hash
/// The tree contained in the commit.
public let tree: Hash
}
/// A tree object.
public struct Tree {
public enum Location: Hashable {
case hash(Hash)
case tag(String)
}
public struct Entry {
public enum EntryType {
case blob
case commit
case executableBlob
case symlink
case tree
init?(mode: Int) {
// Although the mode is a full UNIX mode mask, there are
// only a limited set of allowed values.
switch mode {
case 0o040000:
self = .tree
case 0o100644:
self = .blob
case 0o100755:
self = .executableBlob
case 0o120000:
self = .symlink
case 0o160000:
self = .commit
default:
return nil
}
}
}
/// The object location.
public let location: Location
/// The type of object referenced.
public let type: EntryType
/// The name of the object.
public let name: String
}
/// The object location.
public let location: Location
/// The list of contents.
public let contents: [Entry]
}
/// The path of the repository in the local file system.
public let path: AbsolutePath
/// Concurrent queue to execute git cli on.
private let git: GitShellHelper
// lock top protect concurrent modifications to the repository
private let lock = NSLock()
/// If this repo is a work tree repo (checkout) as opposed to a bare repo.
private let isWorkingRepo: Bool
/// Dictionary for memoizing results of git calls that are not expected to change.
private var cachedHashes = ThreadSafeKeyValueStore<String, Hash>()
private var cachedBlobs = ThreadSafeKeyValueStore<Hash, ByteString>()
private var cachedTrees = ThreadSafeKeyValueStore<String, Tree>()
private var cachedTags = ThreadSafeBox<[String]>()
private var cachedBranches = ThreadSafeBox<[String]>()
private var cachedIsBareRepo = ThreadSafeBox<Bool>()
private var cachedHasSubmodules = ThreadSafeBox<Bool>()
public convenience init(path: AbsolutePath, isWorkingRepo: Bool = true, cancellator: Cancellator? = .none) {
// used in one-off operations on git repo, as such the terminator is not ver important
let cancellator = cancellator ?? Cancellator(observabilityScope: .none)
let git = GitShellHelper(cancellator: cancellator)
self.init(git: git, path: path, isWorkingRepo: isWorkingRepo)
}
fileprivate init(git: GitShellHelper, path: AbsolutePath, isWorkingRepo: Bool = true) {
self.git = git
self.path = path
self.isWorkingRepo = isWorkingRepo
assert({
// Ignore if we couldn't run popen for some reason.
(try? self.isBare() != isWorkingRepo) ?? true
}())
}
/// Private function to invoke the Git tool with its default environment and given set of arguments, specifying the
/// path of the repository as the one to operate on. The specified failure message is used only in case of error.
/// This function waits for the invocation to finish and returns the output as a string.
@discardableResult
private func callGit(
_ args: String...,
environment: EnvironmentVariables = Git.environment,
failureMessage: String = "",
progress: FetchProgress.Handler? = nil
) throws -> String {
if let progress {
var stdoutBytes: [UInt8] = [], stderrBytes: [UInt8] = []
do {
// Capture stdout and stderr from the Git subprocess invocation, but also pass along stderr to the
// handler. We count on it being line-buffered.
let outputHandler = Process.OutputRedirection.stream(stdout: { stdoutBytes += $0 }, stderr: {
stderrBytes += $0
gitFetchStatusFilter($0, progress: progress)
})
return try self.git.run(
["-C", self.path.pathString] + args,
environment: environment,
outputRedirection: outputHandler
)
} catch let error as GitShellError {
let result = ProcessResult(
arguments: error.result.arguments,
environment: error.result.environment,
exitStatus: error.result.exitStatus,
output: .success(stdoutBytes),
stderrOutput: .success(stderrBytes)
)
throw GitRepositoryError(path: self.path, message: failureMessage, result: result)
}
} else {
do {
return try self.git.run(["-C", self.path.pathString] + args, environment: environment)
} catch let error as GitShellError {
throw GitRepositoryError(path: self.path, message: failureMessage, result: error.result)
}
}
}
/// Changes URL for the remote.
///
/// - parameters:
/// - remote: The name of the remote to operate on. It should already be present.
/// - url: The new url of the remote.
public func setURL(remote: String, url: String) throws {
// use barrier for write operations
try self.lock.withLock {
try callGit(
"remote",
"set-url",
remote,
url,
failureMessage: "Couldn’t set the URL of the remote ‘\(remote)’ to ‘\(url)’"
)
}
}
/// Gets the current list of remotes of the repository.
///
/// - Returns: An array of tuple containing name and url of the remote.
public func remotes() throws -> [(name: String, url: String)] {
try self.lock.withLock {
// Get the remote names.
let remoteNamesOutput = try callGit(
"remote",
failureMessage: "Couldn’t get the list of remotes"
)
let remoteNames = remoteNamesOutput.split(separator: "\n").map(String.init)
return try remoteNames.map { name in
// For each remote get the url.
let url = try callGit(
"config",
"--get",
"remote.\(name).url",
failureMessage: "Couldn’t get the URL of the remote ‘\(name)’"
)
return (name, url)
}
}
}
// MARK: Helpers for package search functionality
public func getDefaultBranch() throws -> String {
try callGit("rev-parse", "--abbrev-ref", "HEAD", failureMessage: "Couldn’t get the default branch")
}
public func getBranches() throws -> [String] {
try self.cachedBranches.memoize {
try self.lock.withLock {
let branches = try callGit("branch", "-l", failureMessage: "Couldn’t get the list of branches")
return branches.split(separator: "\n").map { $0.dropFirst(2) }.map(String.init)
}
}
}
// MARK: Repository Interface
/// Returns the tags present in repository.
public func getTags() throws -> [String] {
// Get the contents using `ls-tree`.
try self.cachedTags.memoize {
try self.lock.withLock {
let tagList = try callGit(
"tag",
"-l",
failureMessage: "Couldn’t get the list of tags"
)
return tagList.split(separator: "\n").map(String.init)
}
}
}
public func resolveRevision(tag: String) throws -> Revision {
try Revision(identifier: self.resolveHash(treeish: tag, type: "commit").bytes.description)
}
public func resolveRevision(identifier: String) throws -> Revision {
try Revision(identifier: self.resolveHash(treeish: identifier, type: "commit").bytes.description)
}
public func fetch() throws {
try self.fetch(progress: nil)
}
public func fetch(progress: FetchProgress.Handler? = nil) throws {
// use barrier for write operations
try self.lock.withLock {
try callGit(
"remote",
"-v",
"update",
"-p",
failureMessage: "Couldn’t fetch updates from remote repositories",
progress: progress
)
self.cachedTags.clear()
}
}
public func hasUncommittedChanges() -> Bool {
// Only a working repository can have changes.
guard self.isWorkingRepo else { return false }
return self.lock.withLock {
guard let result = try? callGit("status", "-s") else {
return false
}
return !result.isEmpty
}
}
public func openFileView(revision: Revision) throws -> FileSystem {
try GitFileSystemView(repository: self, revision: revision)
}
public func openFileView(tag: String) throws -> FileSystem {
try GitFileSystemView(repository: self, tag: tag)
}
// MARK: Working Checkout Interface
public func hasUnpushedCommits() throws -> Bool {
try self.lock.withLock {
let hasOutput = try callGit(
"log",
"--branches",
"--not",
"--remotes",
failureMessage: "Couldn’t check for unpushed commits"
).isEmpty
return !hasOutput
}
}
public func getCurrentRevision() throws -> Revision {
try self.lock.withLock {
try Revision(identifier: callGit(
"rev-parse",
"--verify",
"HEAD",
failureMessage: "Couldn’t get current revision"
))
}
}
public func getCurrentTag() -> String? {
self.lock.withLock {
try? callGit(
"describe",
"--exact-match",
"--tags",
failureMessage: "Couldn’t get current tag"
)
}
}
public func checkout(tag: String) throws {
// FIXME: Audit behavior with off-branch tags in remote repositories, we
// may need to take a little more care here.
// use barrier for write operations
try self.lock.withLock {
try callGit(
"reset",
"--hard",
tag,
failureMessage: "Couldn’t check out tag ‘\(tag)’"
)
try self.updateSubmoduleAndCleanIfNecessary()
}
}
public func checkout(revision: Revision) throws {
// FIXME: Audit behavior with off-branch tags in remote repositories, we
// may need to take a little more care here.
// use barrier for write operations
try self.lock.withLock {
try callGit(
"checkout",
"-f",
revision.identifier,
failureMessage: "Couldn’t check out revision ‘\(revision.identifier)’"
)
try self.updateSubmoduleAndCleanIfNecessary()
}
}
internal func isBare() throws -> Bool {
return try self.cachedIsBareRepo.memoize(body: {
let output = try callGit(
"rev-parse",
"--is-bare-repository",
failureMessage: "Couldn’t test for bare repository"
)
return output == "true"
})
}
internal func checkoutExists() throws -> Bool {
return try !self.isBare()
}
private func updateSubmoduleAndCleanIfNecessary() throws {
if self.cachedHasSubmodules.get(default: false) || localFileSystem.exists(self.path.appending(".gitmodules")) {
self.cachedHasSubmodules.put(true)
try self.updateSubmoduleAndCleanNotOnQueue()
}
}
/// Initializes and updates the submodules, if any, and cleans left over the files and directories using git-clean.
private func updateSubmoduleAndCleanNotOnQueue() throws {
try self.callGit(
"submodule",
"update",
"--init",
"--recursive",
failureMessage: "Couldn’t update repository submodules"
)
try self.callGit(
"clean",
"-ffdx",
failureMessage: "Couldn’t clean repository submodules"
)
}
/// Returns true if a revision exists.
public func exists(revision: Revision) -> Bool {
let output = try? callGit("rev-parse", "--verify", "\(revision.identifier)^{commit}")
return output != nil
}
public func checkout(newBranch: String) throws {
guard self.isWorkingRepo else {
throw InternalError("This operation is only valid in a working repository")
}
// use barrier for write operations
try self.lock.withLock {
try callGit(
"checkout",
"-b",
newBranch,
failureMessage: "Couldn’t check out new branch ‘\(newBranch)’"
)
}
}
public func archive(to path: AbsolutePath) throws {
guard self.isWorkingRepo else {
throw InternalError("This operation is only valid in a working repository")
}
try self.lock.withLock {
try callGit(
"archive",
"--format",
"zip",
"--prefix",
"\(path.basenameWithoutExt)/",
"--output",
path.pathString,
"HEAD",
failureMessage: "Couldn’t create an archive"
)
}
}
/// Returns true if there is an alternative object store in the repository and it is valid.
public func isAlternateObjectStoreValid(expected: AbsolutePath) -> Bool {
let objectStoreFile = self.path.appending(components: ".git", "objects", "info", "alternates")
guard let bytes = try? localFileSystem.readFileContents(objectStoreFile) else {
return false
}
let split = bytes.contents.split(separator: UInt8(ascii: "\n"), maxSplits: 1, omittingEmptySubsequences: false)
guard let firstLine = ByteString(split[0]).validDescription else {
return false
}
guard let objectsPath = try? AbsolutePath(validating: firstLine), localFileSystem.isDirectory(objectsPath) else {
return false
}
let repositoryPath = objectsPath.parentDirectory
return expected == repositoryPath
}
/// Returns true if the file at `path` is ignored by `git`
public func areIgnored(_ paths: [Basics.AbsolutePath]) throws -> [Bool] {
try self.lock.withLock {
let stringPaths = paths.map(\.pathString)
let output: String
do {
output = try self.git.run(["-C", self.path.pathString, "check-ignore"] + stringPaths)
} catch let error as GitShellError {
guard error.result.exitStatus == .terminated(code: 1) else {
throw GitRepositoryError(
path: self.path,
message: "unable to check ignored files",
result: error.result
)
}
output = try error.result.utf8Output().spm_chomp()
}
return stringPaths.map(output.split(separator: "\n").map {
let string = String($0).replacingOccurrences(of: "\\\\", with: "\\")
if string.utf8.first == UInt8(ascii: "\"") {
return String(string.dropFirst(1).dropLast(1))
}
return string
}.contains)
}
}
// MARK: Git Operations
/// Resolve a "treeish" to a concrete hash.
///
/// Technically this method can accept much more than a "treeish", it maps
/// to the syntax accepted by `git rev-parse`.
public func resolveHash(treeish: String, type: String? = nil) throws -> Hash {
let specifier: String
if let type {
specifier = treeish + "^{\(type)}"
} else {
specifier = treeish
}
return try self.cachedHashes.memoize(specifier) {
try self.lock.withLock {
let output = try callGit(
"rev-parse",
"--verify",
specifier,
failureMessage: "Couldn’t get revision ‘\(specifier)’"
)
guard let hash = Hash(output) else {
throw GitInterfaceError.malformedResponse("expected an object hash in \(output)")
}
return hash
}
}
}
/// Read the commit referenced by `hash`.
public func readCommit(hash: Hash) throws -> Commit {
// Currently, we just load the tree, using the typed `rev-parse` syntax.
let treeHash = try resolveHash(treeish: hash.bytes.description, type: "tree")
return Commit(hash: hash, tree: treeHash)
}
/// Read a tree object.
public func readTree(location: Tree.Location) throws -> Tree {
switch location {
case .hash(let hash):
return try self.readTree(hash: hash)
case .tag(let tag):
return try self.readTree(tag: tag)
}
}
/// Read a tree object.
public func readTree(hash: Hash) throws -> Tree {
let hashString = hash.bytes.description
return try self.cachedTrees.memoize(hashString) {
try self.lock.withLock {
let output = try callGit(
"ls-tree",
hashString,
failureMessage: "Couldn’t read '\(hashString)'"
)
let entries = try self.parseTree(output)
return Tree(location: .hash(hash), contents: entries)
}
}
}
public func readTree(tag: String) throws -> Tree {
try self.cachedTrees.memoize(tag) {
try self.lock.withLock {
let output = try callGit(
"ls-tree",
tag,
failureMessage: "Couldn’t read '\(tag)'"
)
let entries = try self.parseTree(output)
return Tree(location: .tag(tag), contents: entries)
}
}
}
private func parseTree(_ text: String) throws -> [Tree.Entry] {
var entries = [Tree.Entry]()
for line in text.components(separatedBy: "\n") {
// Ignore empty lines.
if line == "" { continue }
// Each line in the response should match:
//
// `mode type hash\tname`
//
// where `mode` is the 6-byte octal file mode, `type` is a 4-byte or 6-byte
// type ("blob", "tree", "commit"), `hash` is the hash, and the remainder of
// the line is the file name.
let bytes = ByteString(encodingAsUTF8: line)
let expectedBytesCount = 6 + 1 + 4 + 1 + 40 + 1
guard bytes.count > expectedBytesCount,
bytes.contents[6] == UInt8(ascii: " "),
// Search for the second space since `type` is of variable length.
let secondSpace = bytes.contents[6 + 1 ..< bytes.contents.endIndex].firstIndex(of: UInt8(ascii: " ")),
bytes.contents[secondSpace] == UInt8(ascii: " "),
bytes.contents[secondSpace + 1 + 40] == UInt8(ascii: "\t")
else {
throw GitInterfaceError.malformedResponse("unexpected tree entry '\(line)' in '\(text)'")
}
// Compute the mode.
let mode = bytes.contents[0 ..< 6].reduce(0) { (acc: Int, char: UInt8) in
(acc << 3) | (Int(char) - Int(UInt8(ascii: "0")))
}
guard let type = Tree.Entry.EntryType(mode: mode),
let hash = Hash(asciiBytes: bytes.contents[(secondSpace + 1) ..< (secondSpace + 1 + 40)]),
let name = ByteString(bytes.contents[(secondSpace + 1 + 40 + 1) ..< bytes.count]).validDescription
else {
throw GitInterfaceError.malformedResponse("unexpected tree entry '\(line)' in '\(text)'")
}
// FIXME: We do not handle de-quoting of names, currently.
if name.hasPrefix("\"") {
throw GitInterfaceError.malformedResponse("unexpected tree entry '\(line)' in '\(text)'")
}
entries.append(Tree.Entry(location: .hash(hash), type: type, name: name))
}
return entries
}
/// Read a blob object.
func readBlob(hash: Hash) throws -> ByteString {
try self.cachedBlobs.memoize(hash) {
try self.lock.withLock {
// Get the contents using `cat-file`.
//
// FIXME: We need to get the raw bytes back, not a String.
let output = try callGit(
"cat-file",
"-p",
hash.bytes.description,
failureMessage: "Couldn’t read ‘\(hash.bytes.description)’"
)
return ByteString(encodingAsUTF8: output)
}
}
}
/// Read a symbolic link.
func readLink(hash: Hash) throws -> String {
return try callGit(
"cat-file", "-p", String(describing: hash.bytes),
failureMessage: "Couldn't read '\(String(describing: hash.bytes))'"
)
}
}
// MARK: - GitFileSystemView
/// A `git` file system view.
///
/// The current implementation is based on lazily caching data with no eviction
/// policy, and is very unoptimized.
private class GitFileSystemView: FileSystem {
typealias Hash = GitRepository.Hash
typealias Tree = GitRepository.Tree
// MARK: Git Object Model
// The map of loaded trees.
var trees = ThreadSafeKeyValueStore<Tree.Location, Tree>()
/// The underlying repository.
let repository: GitRepository
/// The root tree hash.
// let root: GitRepository.Hash
let root: Tree.Location
init(repository: GitRepository, revision: Revision) throws {
self.repository = repository
self.root = try .hash(repository.readCommit(hash: Hash(revision.identifier)!).tree)
}
init(repository: GitRepository, tag: String) throws {
self.repository = repository
self.root = .tag(tag)
}
// MARK: FileSystem Implementations
private func getEntry(_ path: TSCAbsolutePath) throws -> Tree.Entry? {
// Walk the components resolving the tree (starting with a synthetic
// root entry).
var current = Tree.Entry(location: self.root, type: .tree, name: AbsolutePath.root.pathString)
var currentPath = AbsolutePath.root
for component in path.components {
// Skip the root pseudo-component.
if component == AbsolutePath.root.pathString { continue }
currentPath = currentPath.appending(component: component)
// We have a component to resolve, so the current entry must be a tree.
guard current.type == .tree else {
throw FileSystemError(.notDirectory, .init(currentPath))
}
// Fetch the tree.
let tree = try self.getTree(current.location)
// Search the tree for the component.
//
// FIXME: This needs to be optimized, somewhere.
guard let index = tree.contents.firstIndex(where: { $0.name == component }) else {
return nil
}