forked from apple/swift-package-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SwiftTool.swift
1208 lines (1035 loc) · 50.5 KB
/
SwiftTool.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-2021 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 ArgumentParser
import Basics
import Build
import Dispatch
import class Foundation.ProcessInfo
import OrderedCollections
import PackageGraph
import PackageLoading
import PackageModel
import SourceControl
import SPMBuildCore
import TSCBasic
import class TSCUtility.MultiLineNinjaProgressAnimation
import class TSCUtility.NinjaProgressAnimation
import protocol TSCUtility.ProgressAnimationProtocol
import Workspace
import XCBuildSupport
#if canImport(WinSDK)
import WinSDK
#elseif canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#endif
import protocol TSCUtility.ProgressAnimationProtocol
import class TSCUtility.NinjaProgressAnimation
import class TSCUtility.PercentProgressAnimation
import var TSCUtility.verbosity
typealias Diagnostic = Basics.Diagnostic
private class ToolWorkspaceDelegate: WorkspaceDelegate {
private struct DownloadProgress {
let bytesDownloaded: Int64
let totalBytesToDownload: Int64
}
private struct FetchProgress {
let progress: Int64
let total: Int64
}
/// The progress of binary downloads.
private var binaryDownloadProgress = OrderedCollections.OrderedDictionary<String, DownloadProgress>()
private let binaryDownloadProgressLock = Lock()
/// The progress of package fetch operations.
private var fetchProgress = OrderedCollections.OrderedDictionary<PackageIdentity, FetchProgress>()
private let fetchProgressLock = Lock()
private let observabilityScope: ObservabilityScope
private let outputHandler: (String, Bool) -> Void
private let progressHandler: (Int64, Int64, String?) -> Void
init(
observabilityScope: ObservabilityScope,
outputHandler: @escaping (String, Bool) -> Void,
progressHandler: @escaping (Int64, Int64, String?) -> Void
) {
self.observabilityScope = observabilityScope
self.outputHandler = outputHandler
self.progressHandler = progressHandler
}
func willFetchPackage(package: PackageIdentity, packageLocation: String?, fetchDetails: PackageFetchDetails) {
self.outputHandler("Fetching \(packageLocation ?? package.description)\(fetchDetails.fromCache ? " from cache" : "")", false)
}
func didFetchPackage(package: PackageIdentity, packageLocation: String?, result: Result<PackageFetchDetails, Error>, duration: DispatchTimeInterval) {
guard case .success = result, !self.observabilityScope.errorsReported else {
return
}
self.fetchProgressLock.withLock {
let progress = self.fetchProgress.values.reduce(0) { $0 + $1.progress }
let total = self.fetchProgress.values.reduce(0) { $0 + $1.total }
if progress == total && !self.fetchProgress.isEmpty {
self.fetchProgress.removeAll()
} else {
self.fetchProgress[package] = nil
}
}
self.outputHandler("Fetched \(packageLocation ?? package.description) (\(duration.descriptionInSeconds))", false)
}
func fetchingPackage(package: PackageIdentity, packageLocation: String?, progress: Int64, total: Int64?) {
let (step, total, packages) = self.fetchProgressLock.withLock { () -> (Int64, Int64, String) in
self.fetchProgress[package] = FetchProgress(
progress: progress,
total: total ?? progress
)
let progress = self.fetchProgress.values.reduce(0) { $0 + $1.progress }
let total = self.fetchProgress.values.reduce(0) { $0 + $1.total }
let packages = self.fetchProgress.keys.map { $0.description }.joined(separator: ", ")
return (progress, total, packages)
}
self.progressHandler(step, total, "Fetching \(packages)")
}
func willUpdateRepository(package: PackageIdentity, repository url: String) {
self.outputHandler("Updating \(url)", false)
}
func didUpdateRepository(package: PackageIdentity, repository url: String, duration: DispatchTimeInterval) {
self.outputHandler("Updated \(url) (\(duration.descriptionInSeconds))", false)
}
func dependenciesUpToDate() {
self.outputHandler("Everything is already up-to-date", false)
}
func willCreateWorkingCopy(package: PackageIdentity, repository url: String, at path: AbsolutePath) {
self.outputHandler("Creating working copy for \(url)", false)
}
func didCheckOut(package: PackageIdentity, repository url: String, revision: String, at path: AbsolutePath) {
self.outputHandler("Working copy of \(url) resolved at \(revision)", false)
}
func removing(package: PackageIdentity, packageLocation: String?) {
self.outputHandler("Removing \(packageLocation ?? package.description)", false)
}
func willResolveDependencies(reason: WorkspaceResolveReason) {
self.outputHandler(Workspace.format(workspaceResolveReason: reason), true)
}
func willComputeVersion(package: PackageIdentity, location: String) {
self.outputHandler("Computing version for \(location)", false)
}
func didComputeVersion(package: PackageIdentity, location: String, version: String, duration: DispatchTimeInterval) {
self.outputHandler("Computed \(location) at \(version) (\(duration.descriptionInSeconds))", false)
}
func willDownloadBinaryArtifact(from url: String) {
self.outputHandler("Downloading binary artifact \(url)", false)
}
func didDownloadBinaryArtifact(from url: String, result: Result<AbsolutePath, Error>, duration: DispatchTimeInterval) {
guard case .success = result, !self.observabilityScope.errorsReported else {
return
}
self.binaryDownloadProgressLock.withLock {
let progress = self.binaryDownloadProgress.values.reduce(0) { $0 + $1.bytesDownloaded }
let total = self.binaryDownloadProgress.values.reduce(0) { $0 + $1.totalBytesToDownload }
if progress == total && !self.binaryDownloadProgress.isEmpty {
self.binaryDownloadProgress.removeAll()
} else {
self.binaryDownloadProgress[url] = nil
}
}
self.outputHandler("Downloaded \(url) (\(duration.descriptionInSeconds))", false)
}
func downloadingBinaryArtifact(from url: String, bytesDownloaded: Int64, totalBytesToDownload: Int64?) {
let (step, total, artifacts) = self.binaryDownloadProgressLock.withLock { () -> (Int64, Int64, String) in
self.binaryDownloadProgress[url] = DownloadProgress(
bytesDownloaded: bytesDownloaded,
totalBytesToDownload: totalBytesToDownload ?? bytesDownloaded
)
let step = self.binaryDownloadProgress.values.reduce(0, { $0 + $1.bytesDownloaded })
let total = self.binaryDownloadProgress.values.reduce(0, { $0 + $1.totalBytesToDownload })
let artifacts = self.binaryDownloadProgress.keys.joined(separator: ", ")
return (step, total, artifacts)
}
self.progressHandler(step, total, "Downloading \(artifacts)")
}
// noop
func willLoadManifest(packagePath: AbsolutePath, url: String, version: Version?, packageKind: PackageReference.Kind) {}
func didLoadManifest(packagePath: AbsolutePath, url: String, version: Version?, packageKind: PackageReference.Kind, manifest: Manifest?, diagnostics: [Basics.Diagnostic]) {}
func willCheckOut(package: PackageIdentity, repository url: String, revision: String, at path: AbsolutePath) {}
func didCreateWorkingCopy(package: PackageIdentity, repository url: String, at path: AbsolutePath) {}
func resolvedFileChanged() {}
func didDownloadAllBinaryArtifacts() {}
}
protocol SwiftCommand: ParsableCommand {
var globalOptions: GlobalOptions { get }
func run(_ swiftTool: SwiftTool) throws
}
extension SwiftCommand {
public func run() throws {
let swiftTool = try SwiftTool(options: globalOptions)
var toolError: Error? = .none
do {
try self.run(swiftTool)
if swiftTool.observabilityScope.errorsReported || swiftTool.executionStatus == .failure {
throw ExitCode.failure
}
} catch {
toolError = error
}
// wait for all observability items to process
swiftTool.waitForObservabilityEvents(timeout: .now() + 5)
if let error = toolError {
throw error
}
}
public static var _errorLabel: String { "error" }
}
/// A safe wrapper of TSCBasic.exec.
func exec(path: String, args: [String]) throws -> Never {
#if !os(Windows)
// On platforms other than Windows, signal(SIGINT, SIG_IGN) is used for handling SIGINT by DispatchSourceSignal,
// but this process is about to be replaced by exec, so SIG_IGN must be returned to default.
signal(SIGINT, SIG_DFL)
#endif
try TSCBasic.exec(path: path, args: args)
}
public class SwiftTool {
#if os(Windows)
// unfortunately this is needed for C callback handlers used by Windows shutdown handler
static var cancellator: Cancellator?
#endif
/// The original working directory.
let originalWorkingDirectory: AbsolutePath
/// The options of this tool.
let options: GlobalOptions
/// Path to the root package directory, nil if manifest is not found.
let packageRoot: AbsolutePath?
/// Helper function to get package root or throw error if it is not found.
func getPackageRoot() throws -> AbsolutePath {
guard let packageRoot = packageRoot else {
throw StringError("Could not find \(Manifest.filename) in this directory or any of its parent directories.")
}
return packageRoot
}
/// Get the current workspace root object.
func getWorkspaceRoot() throws -> PackageGraphRootInput {
let packages: [AbsolutePath]
if let workspace = options.locations.multirootPackageDataFile {
packages = try XcodeWorkspaceLoader(fileSystem: self.fileSystem, observabilityScope: self.observabilityScope).load(workspace: workspace)
} else {
packages = [try getPackageRoot()]
}
return PackageGraphRootInput(packages: packages)
}
/// Scratch space (.build) directory.
let scratchDirectory: AbsolutePath
/// Path to the shared security directory
let sharedSecurityDirectory: AbsolutePath?
/// Path to the shared cache directory
let sharedCacheDirectory: AbsolutePath?
/// Path to the shared configuration directory
let sharedConfigurationDirectory: AbsolutePath?
/// Cancellator to handle cancellation of outstanding work when handling SIGINT
let cancellator: Cancellator
/// The execution status of the tool.
var executionStatus: ExecutionStatus = .success
/// Holds the currently active workspace.
///
/// It is not initialized in init() because for some of the commands like package init , usage etc,
/// workspace is not needed, in-fact it would be an error to ask for the workspace object
/// for package init because the Manifest file should *not* present.
private var _workspace: Workspace?
private var _workspaceDelegate: ToolWorkspaceDelegate?
private let observabilityHandler: SwiftToolObservabilityHandler
/// The observability scope to emit diagnostics event on
let observabilityScope: ObservabilityScope
/// The min severity at which to log diagnostics
let logLevel: Diagnostic.Severity
/// The file system in use
let fileSystem: FileSystem
/// Create an instance of this tool.
///
/// - parameter options: The command line options to be passed to this tool.
convenience init(options: GlobalOptions) throws {
// output from background activities goes to stderr, this includes diagnostics and output from build operations,
// package resolution that take place as part of another action
// CLI commands that have user facing output, use stdout directly to emit the final result
// this means that the build output from "swift build" goes to stdout
// but the build output from "swift test" goes to stderr, while the tests output go to stdout
try self.init(outputStream: TSCBasic.stderrStream, options: options)
}
// marked internal for testing
internal init(outputStream: OutputByteStream, options: GlobalOptions) throws {
self.fileSystem = localFileSystem
// first, bootstrap the observability system
self.logLevel = options.logging.logLevel
self.observabilityHandler = SwiftToolObservabilityHandler(outputStream: outputStream, logLevel: self.logLevel)
let observabilitySystem = ObservabilitySystem(self.observabilityHandler)
self.observabilityScope = observabilitySystem.topScope
let cancellator = Cancellator(observabilityScope: self.observabilityScope)
// Capture the original working directory ASAP.
guard let cwd = self.fileSystem.currentWorkingDirectory else {
self.observabilityScope.emit(error: "couldn't determine the current working directory")
throw ExitCode.failure
}
self.originalWorkingDirectory = cwd
do {
try Self.postprocessArgParserResult(options: options, observabilityScope: self.observabilityScope)
self.options = options
// Honor package-path option is provided.
if let packagePath = options.locations.packageDirectory {
try ProcessEnv.chdir(packagePath)
}
#if os(Windows)
// set shutdown handler to terminate sub-processes, etc
SwiftTool.cancellator = cancellator
_ = SetConsoleCtrlHandler({ _ in
// Terminate all processes on receiving an interrupt signal.
try? SwiftTool.cancellator?.cancel(deadline: .now() + .seconds(30))
// Reset the handler.
_ = SetConsoleCtrlHandler(nil, false)
// Exit as if by signal()
TerminateProcess(GetCurrentProcess(), 3)
return true
}, true)
#else
// trap SIGINT to terminate sub-processes, etc
signal(SIGINT, SIG_IGN)
let interruptSignalSource = DispatchSource.makeSignalSource(signal: SIGINT)
interruptSignalSource.setEventHandler {
// cancel the trap?
interruptSignalSource.cancel()
// Terminate all processes on receiving an interrupt signal.
try? cancellator.cancel(deadline: .now() + .seconds(30))
#if os(macOS) || os(OpenBSD)
// Install the default signal handler.
var action = sigaction()
action.__sigaction_u.__sa_handler = SIG_DFL
sigaction(SIGINT, &action, nil)
kill(getpid(), SIGINT)
#elseif os(Android)
// Install the default signal handler.
var action = sigaction()
action.sa_handler = SIG_DFL
sigaction(SIGINT, &action, nil)
kill(getpid(), SIGINT)
#else
var action = sigaction()
action.__sigaction_handler = unsafeBitCast(
SIG_DFL,
to: sigaction.__Unnamed_union___sigaction_handler.self)
sigaction(SIGINT, &action, nil)
kill(getpid(), SIGINT)
#endif
}
interruptSignalSource.resume()
#endif
self.cancellator = cancellator
} catch {
self.observabilityScope.emit(error)
throw ExitCode.failure
}
// Create local variables to use while finding build path to avoid capture self before init error.
let packageRoot = findPackageRoot(fileSystem: fileSystem)
self.packageRoot = packageRoot
self.scratchDirectory =
getEnvBuildPath(workingDir: cwd) ??
options.locations.scratchDirectory ??
(packageRoot ?? cwd).appending(component: ".build")
// make sure common directories are created
self.sharedSecurityDirectory = try getSharedSecurityDirectory(options: self.options, fileSystem: fileSystem, observabilityScope: self.observabilityScope)
self.sharedConfigurationDirectory = try getSharedConfigurationDirectory(options: self.options, fileSystem: fileSystem, observabilityScope: self.observabilityScope)
self.sharedCacheDirectory = try getSharedCacheDirectory(options: self.options, fileSystem: fileSystem, observabilityScope: self.observabilityScope)
// set global process logging handler
Process.loggingHandler = { self.observabilityScope.emit(debug: $0) }
}
static func postprocessArgParserResult(options: GlobalOptions, observabilityScope: ObservabilityScope) throws {
if options.locations._deprecated_buildPath != nil {
observabilityScope.emit(warning: "'--build-path' option is deprecated; use '--scratch-path' instead")
}
if options.locations._deprecated_chdir != nil {
observabilityScope.emit(warning: "'--chdir/-C' option is deprecated; use '--package-path' instead")
}
if options.locations.multirootPackageDataFile != nil {
observabilityScope.emit(.unsupportedFlag("--multiroot-data-file"))
}
if options.build.useExplicitModuleBuild && !options.build.useIntegratedSwiftDriver {
observabilityScope.emit(error: "'--experimental-explicit-module-build' option requires '--use-integrated-swift-driver'")
}
if !options.build.archs.isEmpty && options.build.customCompileTriple != nil {
observabilityScope.emit(.mutuallyExclusiveArgumentsError(arguments: ["--arch", "--triple"]))
}
// --enable-test-discovery should never be called on darwin based platforms
#if canImport(Darwin)
if options.build.enableTestDiscovery {
observabilityScope.emit(warning: "'--enable-test-discovery' option is deprecated; tests are automatically discovered on all platforms")
}
#endif
if options.caching.shouldDisableManifestCaching {
observabilityScope.emit(warning: "'--disable-package-manifest-caching' option is deprecated; use '--manifest-caching' instead")
}
if let _ = options.security.netrcFilePath, options.security.netrc == false {
observabilityScope.emit(.mutuallyExclusiveArgumentsError(arguments: ["--disable-netrc", "--netrc-file"]))
}
if options.security._deprecated_netrc {
observabilityScope.emit(warning: "'--netrc' option is deprecated; .netrc files are located by default")
}
if options.security._deprecated_netrcOptional {
observabilityScope.emit(warning: "'--netrc-optional' option is deprecated; .netrc files are located by default")
}
if options.resolver._deprecated_enableResolverTrace {
observabilityScope.emit(warning: "'--enableResolverTrace' flag is deprecated; use '--verbose' option to log resolver output")
}
if options.caching._deprecated_useRepositoriesCache != nil {
observabilityScope.emit(warning: "'--disable-repository-cache'/'--enable-repository-cache' flags are deprecated; use '--disable-dependency-cache'/'--enable-dependency-cache' instead")
}
}
func waitForObservabilityEvents(timeout: DispatchTime) {
self.observabilityHandler.wait(timeout: timeout)
}
/// Returns the currently active workspace.
func getActiveWorkspace() throws -> Workspace {
if let workspace = _workspace {
return workspace
}
let delegate = ToolWorkspaceDelegate(
observabilityScope: self.observabilityScope,
outputHandler: self.observabilityHandler.print,
progressHandler: self.observabilityHandler.progress
)
let isXcodeBuildSystemEnabled = self.options.build.buildSystem == .xcode
let workspace = try Workspace(
fileSystem: self.fileSystem,
location: .init(
scratchDirectory: self.scratchDirectory,
editsDirectory: self.getEditsDirectory(),
resolvedVersionsFile: self.getResolvedVersionsFile(),
localConfigurationDirectory: try self.getLocalConfigurationDirectory(),
sharedConfigurationDirectory: self.sharedConfigurationDirectory,
sharedSecurityDirectory: self.sharedSecurityDirectory,
sharedCacheDirectory: self.sharedCacheDirectory
),
authorizationProvider: self.getAuthorizationProvider(),
configuration: .init(
skipDependenciesUpdates: options.resolver.skipDependencyUpdate,
prefetchBasedOnResolvedFile: options.resolver.shouldEnableResolverPrefetching,
additionalFileRules: isXcodeBuildSystemEnabled ? FileRuleDescription.xcbuildFileTypes : FileRuleDescription.swiftpmFileTypes,
sharedDependenciesCacheEnabled: self.options.caching.useDependenciesCache,
fingerprintCheckingMode: self.options.security.fingerprintCheckingMode,
sourceControlToRegistryDependencyTransformation: self.options.resolver.sourceControlToRegistryDependencyTransformation.workspaceConfiguration
),
cancellator: self.cancellator,
initializationWarningHandler: { self.observabilityScope.emit(warning: $0) },
customHostToolchain: self.getHostToolchain(),
customManifestLoader: self.getManifestLoader(),
delegate: delegate
)
_workspace = workspace
_workspaceDelegate = delegate
return workspace
}
private func getEditsDirectory() throws -> AbsolutePath {
// TODO: replace multiroot-data-file with explicit overrides
if let multiRootPackageDataFile = options.locations.multirootPackageDataFile {
return multiRootPackageDataFile.appending(component: "Packages")
}
return try Workspace.DefaultLocations.editsDirectory(forRootPackage: self.getPackageRoot())
}
private func getResolvedVersionsFile() throws -> AbsolutePath {
// TODO: replace multiroot-data-file with explicit overrides
if let multiRootPackageDataFile = options.locations.multirootPackageDataFile {
return multiRootPackageDataFile.appending(components: "xcshareddata", "swiftpm", "Package.resolved")
}
return try Workspace.DefaultLocations.resolvedVersionsFile(forRootPackage: self.getPackageRoot())
}
internal func getLocalConfigurationDirectory() throws -> AbsolutePath {
// Otherwise, use the default path.
// TODO: replace multiroot-data-file with explicit overrides
if let multiRootPackageDataFile = options.locations.multirootPackageDataFile {
// migrate from legacy location
let legacyPath = multiRootPackageDataFile.appending(components: "xcshareddata", "swiftpm", "config")
let newPath = Workspace.DefaultLocations.mirrorsConfigurationFile(at: multiRootPackageDataFile.appending(components: "xcshareddata", "swiftpm", "configuration"))
return try Workspace.migrateMirrorsConfiguration(from: legacyPath, to: newPath, observabilityScope: observabilityScope)
} else {
// migrate from legacy location
let legacyPath = try self.getPackageRoot().appending(components: ".swiftpm", "config")
let newPath = try Workspace.DefaultLocations.mirrorsConfigurationFile(forRootPackage: self.getPackageRoot())
return try Workspace.migrateMirrorsConfiguration(from: legacyPath, to: newPath, observabilityScope: observabilityScope)
}
}
func getAuthorizationProvider() throws -> AuthorizationProvider? {
var authorization = Workspace.Configuration.Authorization.default
if !options.security.netrc {
authorization.netrc = .disabled
} else if let configuredPath = options.security.netrcFilePath {
authorization.netrc = .custom(configuredPath)
} else {
let rootPath = try options.locations.multirootPackageDataFile ?? self.getPackageRoot()
authorization.netrc = .workspaceAndUser(rootPath: rootPath)
}
#if canImport(Security)
authorization.keychain = self.options.security.keychain ? .enabled : .disabled
#endif
return try authorization.makeAuthorizationProvider(fileSystem: self.fileSystem, observabilityScope: self.observabilityScope)
}
/// Resolve the dependencies.
func resolve() throws {
let workspace = try getActiveWorkspace()
let root = try getWorkspaceRoot()
if options.resolver.forceResolvedVersions {
try workspace.resolveBasedOnResolvedVersionsFile(root: root, observabilityScope: self.observabilityScope)
} else {
try workspace.resolve(root: root, observabilityScope: self.observabilityScope)
}
// Throw if there were errors when loading the graph.
// The actual errors will be printed before exiting.
guard !self.observabilityScope.errorsReported else {
throw ExitCode.failure
}
}
/// Fetch and load the complete package graph.
///
/// - Parameters:
/// - explicitProduct: The product specified on the command line to a “swift run” or “swift build” command. This allows executables from dependencies to be run directly without having to hook them up to any particular target.
@discardableResult
func loadPackageGraph(
explicitProduct: String? = nil,
createMultipleTestProducts: Bool = false,
createREPLProduct: Bool = false
) throws -> PackageGraph {
do {
let workspace = try getActiveWorkspace()
// Fetch and load the package graph.
let graph = try workspace.loadPackageGraph(
rootInput: getWorkspaceRoot(),
explicitProduct: explicitProduct,
createMultipleTestProducts: createMultipleTestProducts,
createREPLProduct: createREPLProduct,
forceResolvedVersions: options.resolver.forceResolvedVersions,
observabilityScope: self.observabilityScope
)
// Throw if there were errors when loading the graph.
// The actual errors will be printed before exiting.
guard !self.observabilityScope.errorsReported else {
throw ExitCode.failure
}
return graph
} catch {
throw error
}
}
func getPluginScriptRunner(customPluginsDir: AbsolutePath? = .none) throws -> PluginScriptRunner {
let pluginsDir = try customPluginsDir ?? self.getActiveWorkspace().location.pluginWorkingDirectory
let cacheDir = pluginsDir.appending(component: "cache")
let pluginScriptRunner = try DefaultPluginScriptRunner(
fileSystem: self.fileSystem,
cacheDir: cacheDir,
toolchain: self.getHostToolchain(),
enableSandbox: !self.options.security.shouldDisableSandbox,
verboseOutput: self.logLevel <= .info
)
// register the plugin runner system with the cancellation handler
self.cancellator.register(name: "plugin runner", handler: pluginScriptRunner)
return pluginScriptRunner
}
/// Returns the user toolchain to compile the actual product.
func getToolchain() throws -> UserToolchain {
return try _destinationToolchain.get()
}
func getHostToolchain() throws -> UserToolchain {
return try _hostToolchain.get()
}
func getManifestLoader() throws -> ManifestLoader {
return try _manifestLoader.get()
}
private func canUseCachedBuildManifest() throws -> Bool {
if !self.options.caching.cacheBuildManifest {
return false
}
let buildParameters = try self.buildParameters()
let haveBuildManifestAndDescription =
self.fileSystem.exists(buildParameters.llbuildManifest) &&
self.fileSystem.exists(buildParameters.buildDescriptionPath)
if !haveBuildManifestAndDescription {
return false
}
// Perform steps for build manifest caching if we can enabled it.
//
// FIXME: We don't add edited packages in the package structure command yet (SR-11254).
let hasEditedPackages = try self.getActiveWorkspace().state.dependencies.contains(where: { $0.isEdited })
if hasEditedPackages {
return false
}
return true
}
// note: do not customize the OutputStream unless absolutely necessary
// "customOutputStream" is designed to support build output redirection
// but it is only expected to be used when invoking builds from "swift build" command.
// in all other cases, the build output should go to the default which is stderr
func createBuildOperation(
explicitProduct: String? = .none,
cacheBuildManifest: Bool = true,
customBuildParameters: BuildParameters? = .none,
customPackageGraphLoader: (() throws -> PackageGraph)? = .none,
customOutputStream: OutputByteStream? = .none,
customLogLevel: Diagnostic.Severity? = .none,
customObservabilityScope: ObservabilityScope? = .none
) throws -> BuildOperation {
let graphLoader = { try self.loadPackageGraph(explicitProduct: explicitProduct) }
// Construct the build operation.
// FIXME: We need to implement the build tool invocation closure here so that build tool plugins work with dumping the symbol graph (the only case that currently goes through this path, as far as I can tell). rdar://86112934
let buildOp = try BuildOperation(
buildParameters: customBuildParameters ?? self.buildParameters(),
cacheBuildManifest: cacheBuildManifest && self.canUseCachedBuildManifest(),
packageGraphLoader: customPackageGraphLoader ?? graphLoader,
additionalFileRules: FileRuleDescription.swiftpmFileTypes,
pluginScriptRunner: self.getPluginScriptRunner(),
pluginWorkDirectory: try self.getActiveWorkspace().location.pluginWorkingDirectory,
disableSandboxForPluginCommands: self.options.security.shouldDisableSandbox,
outputStream: customOutputStream ?? self.outputStream,
logLevel: customLogLevel ?? self.logLevel,
fileSystem: self.fileSystem,
observabilityScope: customObservabilityScope ?? self.observabilityScope
)
// register the build system with the cancellation handler
self.cancellator.register(name: "build system", handler: buildOp.cancel)
return buildOp
}
// note: do not customize the OutputStream unless absolutely necessary
// "customOutputStream" is designed to support build output redirection
// but it is only expected to be used when invoking builds from "swift build" command.
// in all other cases, the build output should go to the default which is stderr
func createBuildSystem(
explicitProduct: String? = .none,
customBuildParameters: BuildParameters? = .none,
customPackageGraphLoader: (() throws -> PackageGraph)? = .none,
customOutputStream: OutputByteStream? = .none,
customObservabilityScope: ObservabilityScope? = .none
) throws -> BuildSystem {
let buildSystem: BuildSystem
switch options.build.buildSystem {
case .native:
buildSystem = try self.createBuildOperation(
explicitProduct: explicitProduct,
cacheBuildManifest: true,
customBuildParameters: customBuildParameters,
customPackageGraphLoader: customPackageGraphLoader,
customOutputStream: customOutputStream,
customObservabilityScope: customObservabilityScope
)
case .xcode:
let graphLoader = { try self.loadPackageGraph(explicitProduct: explicitProduct, createMultipleTestProducts: true) }
// FIXME: Implement the custom build command provider also.
buildSystem = try XcodeBuildSystem(
buildParameters: customBuildParameters ?? self.buildParameters(),
packageGraphLoader: customPackageGraphLoader ?? graphLoader,
outputStream: customOutputStream ?? self.outputStream,
logLevel: self.logLevel,
fileSystem: self.fileSystem,
observabilityScope: customObservabilityScope ?? self.observabilityScope
)
}
// register the build system with the cancellation handler
self.cancellator.register(name: "build system", handler: buildSystem.cancel)
return buildSystem
}
/// Return the build parameters.
func buildParameters() throws -> BuildParameters {
return try _buildParameters.get()
}
private lazy var _buildParameters: Result<BuildParameters, Swift.Error> = {
return Result(catching: {
let toolchain = try self.getToolchain()
let triple = toolchain.triple
// Use "apple" as the subdirectory because in theory Xcode build system
// can be used to build for any Apple platform and it has it's own
// conventions for build subpaths based on platforms.
let dataPath = self.scratchDirectory.appending(
component: options.build.buildSystem == .xcode ? "apple" : triple.platformBuildPathComponent())
return BuildParameters(
dataPath: dataPath,
configuration: options.build.configuration,
toolchain: toolchain,
destinationTriple: triple,
archs: options.build.archs,
flags: options.build.buildFlags,
xcbuildFlags: options.build.xcbuildFlags,
jobs: options.build.jobs ?? UInt32(ProcessInfo.processInfo.activeProcessorCount),
shouldLinkStaticSwiftStdlib: options.linker.shouldLinkStaticSwiftStdlib,
canRenameEntrypointFunctionName: SwiftTargetBuildDescription.checkSupportedFrontendFlags(
flags: ["entry-point-function-name"], fileSystem: self.fileSystem
),
sanitizers: options.build.enabledSanitizers,
enableCodeCoverage: false, // set by test commands when appropriate
indexStoreMode: options.build.indexStoreMode.buildParameter,
enableParseableModuleInterfaces: options.build.shouldEnableParseableModuleInterfaces,
emitSwiftModuleSeparately: options.build.emitSwiftModuleSeparately,
useIntegratedSwiftDriver: options.build.useIntegratedSwiftDriver,
useExplicitModuleBuild: options.build.useExplicitModuleBuild,
isXcodeBuildSystemEnabled: options.build.buildSystem == .xcode,
forceTestDiscovery: options.build.enableTestDiscovery, // backwards compatibility, remove with --enable-test-discovery
explicitTargetDependencyImportCheckingMode: options.build.explicitTargetDependencyImportCheck.modeParameter,
linkerDeadStrip: options.linker.linkerDeadStrip,
verboseOutput: self.logLevel <= .info
)
})
}()
/// Lazily compute the destination toolchain.
private lazy var _destinationToolchain: Result<UserToolchain, Swift.Error> = {
var destination: Destination
let hostDestination: Destination
do {
hostDestination = try self._hostToolchain.get().destination
// Create custom toolchain if present.
if let customDestination = self.options.locations.customCompileDestination {
destination = try Destination(fromFile: customDestination, fileSystem: self.fileSystem)
} else if let target = self.options.build.customCompileTriple,
let targetDestination = Destination.defaultDestination(for: target, host: hostDestination) {
destination = targetDestination
} else {
// Otherwise use the host toolchain.
destination = hostDestination
}
} catch {
return .failure(error)
}
// Apply any manual overrides.
if let triple = self.options.build.customCompileTriple {
destination.target = triple
}
if let binDir = self.options.build.customCompileToolchain {
destination.binDir = binDir.appending(components: "usr", "bin")
}
if let sdk = self.options.build.customCompileSDK {
destination.sdk = sdk
}
destination.archs = options.build.archs
// Check if we ended up with the host toolchain.
if hostDestination == destination {
return self._hostToolchain
}
return Result(catching: { try UserToolchain(destination: destination) })
}()
/// Lazily compute the host toolchain used to compile the package description.
private lazy var _hostToolchain: Result<UserToolchain, Swift.Error> = {
return Result(catching: {
try UserToolchain(destination: Destination.hostDestination(
originalWorkingDirectory: self.originalWorkingDirectory))
})
}()
private lazy var _manifestLoader: Result<ManifestLoader, Swift.Error> = {
return Result(catching: {
let cachePath: AbsolutePath?
switch (self.options.caching.shouldDisableManifestCaching, self.options.caching.manifestCachingMode) {
case (true, _):
// backwards compatibility
cachePath = .none
case (false, .none):
cachePath = .none
case (false, .local):
cachePath = self.scratchDirectory
case (false, .shared):
cachePath = self.sharedCacheDirectory.map{ Workspace.DefaultLocations.manifestsDirectory(at: $0) }
}
var extraManifestFlags = self.options.build.manifestFlags
// Disable the implicit concurrency import if the compiler in use supports it to avoid warnings if we are building against an older SDK that does not contain a Concurrency module.
if SwiftTargetBuildDescription.checkSupportedFrontendFlags(flags: ["disable-implicit-concurrency-module-import"], fileSystem: self.fileSystem) {
extraManifestFlags += ["-Xfrontend", "-disable-implicit-concurrency-module-import"]
}
// Disable the implicit string processing import if the compiler in use supports it to avoid warnings if we are building against an older SDK that does not contain a StringProcessing module.
if SwiftTargetBuildDescription.checkSupportedFrontendFlags(flags: ["disable-implicit-string-processing-module-import"], fileSystem: self.fileSystem) {
extraManifestFlags += ["-Xfrontend", "-disable-implicit-string-processing-module-import"]
}
if self.logLevel <= .info {
extraManifestFlags.append("-v")
}
return try ManifestLoader(
// Always use the host toolchain's resources for parsing manifest.
toolchain: self.getHostToolchain(),
isManifestSandboxEnabled: !self.options.security.shouldDisableSandbox,
cacheDir: cachePath,
extraManifestFlags: extraManifestFlags
)
})
}()
/// An enum indicating the execution status of run commands.
enum ExecutionStatus {
case success
case failure
}
}
/// Returns path of the nearest directory containing the manifest file w.r.t
/// current working directory.
private func findPackageRoot(fileSystem: FileSystem) -> AbsolutePath? {
guard var root = fileSystem.currentWorkingDirectory else {
return nil
}
// FIXME: It would be nice to move this to a generalized method which takes path and predicate and
// finds the lowest path for which the predicate is true.
while !fileSystem.isFile(root.appending(component: Manifest.filename)) {
root = root.parentDirectory
guard !root.isRoot else {
return nil
}
}
return root
}
/// Returns the build path from the environment, if present.
private func getEnvBuildPath(workingDir: AbsolutePath) -> AbsolutePath? {
// Don't rely on build path from env for SwiftPM's own tests.
guard ProcessEnv.vars["SWIFTPM_TESTS_MODULECACHE"] == nil else { return nil }
guard let env = ProcessEnv.vars["SWIFTPM_BUILD_DIR"] else { return nil }
return AbsolutePath(env, relativeTo: workingDir)
}
private func getSharedSecurityDirectory(options: GlobalOptions, fileSystem: FileSystem, observabilityScope: ObservabilityScope) throws -> AbsolutePath? {
if let explicitSecurityDirectory = options.locations.securityDirectory {
// Create the explicit security path if necessary
if !fileSystem.exists(explicitSecurityDirectory) {
try fileSystem.createDirectory(explicitSecurityDirectory, recursive: true)
}
return explicitSecurityDirectory
} else {
// further validation is done in workspace
return fileSystem.swiftPMSecurityDirectory
}
}
private func getSharedConfigurationDirectory(options: GlobalOptions, fileSystem: FileSystem, observabilityScope: ObservabilityScope) throws -> AbsolutePath? {
if let explicitConfigurationDirectory = options.locations.configurationDirectory {
// Create the explicit config path if necessary
if !fileSystem.exists(explicitConfigurationDirectory) {
try fileSystem.createDirectory(explicitConfigurationDirectory, recursive: true)
}
return explicitConfigurationDirectory
} else {
// further validation is done in workspace
return fileSystem.swiftPMConfigurationDirectory
}
}
private func getSharedCacheDirectory(options: GlobalOptions, fileSystem: FileSystem, observabilityScope: ObservabilityScope) throws -> AbsolutePath? {
if let explicitCacheDirectory = options.locations.cacheDirectory {
// Create the explicit cache path if necessary
if !fileSystem.exists(explicitCacheDirectory) {
try fileSystem.createDirectory(explicitCacheDirectory, recursive: true)
}
return explicitCacheDirectory
} else {
// further validation is done in workspace
return fileSystem.swiftPMCacheDirectory
}
}
extension Basics.Diagnostic {
static func unsupportedFlag(_ flag: String) -> Self {
.warning("\(flag) is an *unsupported* option which can be removed at any time; do not rely on it")
}
}
// MARK: - Diagnostics
private struct SwiftToolObservabilityHandler: ObservabilityHandlerProvider {
private let outputHandler: OutputHandler
var diagnosticsHandler: DiagnosticsHandler {
self.outputHandler
}
init(outputStream: OutputByteStream, logLevel: Diagnostic.Severity) {
let threadSafeOutputByteStream = outputStream as? ThreadSafeOutputByteStream ?? ThreadSafeOutputByteStream(outputStream)
self.outputHandler = OutputHandler(logLevel: logLevel, outputStream: threadSafeOutputByteStream)
}
// for raw output reporting
func print(_ output: String, verbose: Bool) {
self.outputHandler.print(output, verbose: verbose)
}
// for raw progress reporting
func progress(step: Int64, total: Int64, description: String?) {
self.outputHandler.progress(step: step, total: total, description: description)
}
// FIXME: deprecate this one we are further along refactoring the call sites that use it
var outputStream: OutputByteStream {
self.outputHandler.outputStream
}
func wait(timeout: DispatchTime) {
self.outputHandler.wait(timeout: timeout)
}