-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
PackageCommandTests.swift
3666 lines (3255 loc) · 181 KB
/
PackageCommandTests.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-2024 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
@testable import CoreCommands
@testable import Commands
import Foundation
@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)
import PackageGraph
import PackageLoading
import PackageModel
import SourceControl
import _InternalTestSupport
import Workspace
import XCTest
import struct TSCBasic.ByteString
import class TSCBasic.BufferedOutputByteStream
import enum TSCBasic.JSON
import class Basics.AsyncProcess
final class PackageCommandTests: CommandsTestCase {
@discardableResult
private func execute(
_ args: [String] = [],
packagePath: AbsolutePath? = nil,
env: Environment? = nil
) async throws -> (stdout: String, stderr: String) {
var environment = env ?? [:]
// don't ignore local packages when caching
environment["SWIFTPM_TESTS_PACKAGECACHE"] = "1"
return try await SwiftPM.Package.execute(args, packagePath: packagePath, env: environment)
}
func testNoParameters() async throws {
let stdout = try await execute().stdout
XCTAssertMatch(stdout, .contains("USAGE: swift package"))
}
func testUsage() async throws {
throw XCTSkip("rdar://131126477")
do {
_ = try await execute(["-halp"])
XCTFail("expecting `execute` to fail")
} catch SwiftPMError.executionFailure(_, _, let stderr) {
XCTAssertMatch(stderr, .contains("Usage: swift package"))
} catch {
throw error
}
}
func testSeeAlso() async throws {
let stdout = try await execute(["--help"]).stdout
XCTAssertMatch(stdout, .contains("SEE ALSO: swift build, swift run, swift test"))
}
func testVersion() async throws {
let stdout = try await execute(["--version"]).stdout
XCTAssertMatch(stdout, .contains("Swift Package Manager"))
}
func testCompletionTool() async throws {
let stdout = try await execute(["completion-tool", "--help"]).stdout
XCTAssertMatch(stdout, .contains("OVERVIEW: Completion command (for shell completions)"))
}
func testInitOverview() async throws {
let stdout = try await execute(["init", "--help"]).stdout
XCTAssertMatch(stdout, .contains("OVERVIEW: Initialize a new package"))
}
func testInitUsage() async throws {
let stdout = try await execute(["init", "--help"]).stdout
XCTAssertMatch(stdout, .contains("USAGE: swift package init [--type <type>] "))
XCTAssertMatch(stdout, .contains(" [--name <name>]"))
}
func testInitOptionsHelp() async throws {
let stdout = try await execute(["init", "--help"]).stdout
XCTAssertMatch(stdout, .contains("OPTIONS:"))
}
func testPlugin() async throws {
await XCTAssertThrowsCommandExecutionError(try await execute(["plugin"])) { error in
XCTAssertMatch(error.stderr, .contains("error: Missing expected plugin command"))
}
}
func testUnknownOption() async throws {
await XCTAssertThrowsCommandExecutionError(try await execute(["--foo"])) { error in
XCTAssertMatch(error.stderr, .contains("error: Unknown option '--foo'"))
}
}
func testUnknownSubcommand() async throws {
try await fixture(name: "Miscellaneous/ExeTest") { fixturePath in
await XCTAssertThrowsCommandExecutionError(try await execute(["foo"], packagePath: fixturePath)) { error in
XCTAssertMatch(error.stderr, .contains("Unknown subcommand or plugin name ‘foo’"))
}
}
}
func testNetrc() async throws {
try await fixture(name: "DependencyResolution/External/XCFramework") { fixturePath in
// --enable-netrc flag
try await self.execute(["resolve", "--enable-netrc"], packagePath: fixturePath)
// --disable-netrc flag
try await self.execute(["resolve", "--disable-netrc"], packagePath: fixturePath)
// --enable-netrc and --disable-netrc flags
await XCTAssertAsyncThrowsError(
try await self.execute(["resolve", "--enable-netrc", "--disable-netrc"], packagePath: fixturePath)
) { error in
XCTAssertMatch(String(describing: error), .contains("Value to be set with flag '--disable-netrc' had already been set with flag '--enable-netrc'"))
}
}
}
func testNetrcFile() async throws {
try await fixture(name: "DependencyResolution/External/XCFramework") { fixturePath in
let fs = localFileSystem
let netrcPath = fixturePath.appending(".netrc")
try fs.writeFileContents(
netrcPath,
string: "machine mymachine.labkey.org login [email protected] password mypassword"
)
// valid .netrc file path
try await execute(["resolve", "--netrc-file", netrcPath.pathString], packagePath: fixturePath)
// valid .netrc file path with --disable-netrc option
await XCTAssertAsyncThrowsError(
try await execute(["resolve", "--netrc-file", netrcPath.pathString, "--disable-netrc"], packagePath: fixturePath)
) { error in
XCTAssertMatch(String(describing: error), .contains("'--disable-netrc' and '--netrc-file' are mutually exclusive"))
}
// invalid .netrc file path
await XCTAssertAsyncThrowsError(
try await execute(["resolve", "--netrc-file", "/foo"], packagePath: fixturePath)
) { error in
XCTAssertMatch(String(describing: error), .contains("Did not find netrc file at /foo."))
}
// invalid .netrc file path with --disable-netrc option
await XCTAssertAsyncThrowsError(
try await execute(["resolve", "--netrc-file", "/foo", "--disable-netrc"], packagePath: fixturePath)
) { error in
XCTAssertMatch(String(describing: error), .contains("'--disable-netrc' and '--netrc-file' are mutually exclusive"))
}
}
}
func testEnableDisableCache() async throws {
try await fixture(name: "DependencyResolution/External/Simple") { fixturePath in
let packageRoot = fixturePath.appending("Bar")
let repositoriesPath = packageRoot.appending(components: ".build", "repositories")
let cachePath = fixturePath.appending("cache")
let repositoriesCachePath = cachePath.appending("repositories")
do {
// Remove .build and cache folder
_ = try await execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
try await self.execute(["resolve", "--enable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
// we have to check for the prefix here since the hash value changes because spm sees the `prefix`
// directory `/var/...` as `/private/var/...`.
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesCachePath).contains { $0.hasPrefix("Foo-") })
// Remove .build folder
_ = try await execute(["reset"], packagePath: packageRoot)
// Perform another cache this time from the cache
_ = try await execute(["resolve", "--enable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
// Remove .build and cache folder
_ = try await execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
// Perform another fetch
_ = try await execute(["resolve", "--enable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesCachePath).contains { $0.hasPrefix("Foo-") })
}
do {
// Remove .build and cache folder
_ = try await execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
try await self.execute(["resolve", "--disable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
// we have to check for the prefix here since the hash value changes because spm sees the `prefix`
// directory `/var/...` as `/private/var/...`.
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssertFalse(localFileSystem.exists(repositoriesCachePath))
}
do {
// Remove .build and cache folder
_ = try await execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
let (_, _) = try await self.execute(["resolve", "--enable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
// we have to check for the prefix here since the hash value changes because spm sees the `prefix`
// directory `/var/...` as `/private/var/...`.
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesCachePath).contains { $0.hasPrefix("Foo-") })
// Remove .build folder
_ = try await execute(["reset"], packagePath: packageRoot)
// Perform another cache this time from the cache
_ = try await execute(["resolve", "--enable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
// Remove .build and cache folder
_ = try await execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
// Perform another fetch
_ = try await execute(["resolve", "--enable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesCachePath).contains { $0.hasPrefix("Foo-") })
}
do {
// Remove .build and cache folder
_ = try await execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
let (_, _) = try await self.execute(["resolve", "--disable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
// we have to check for the prefix here since the hash value changes because spm sees the `prefix`
// directory `/var/...` as `/private/var/...`.
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssertFalse(localFileSystem.exists(repositoriesCachePath))
}
}
}
func testResolve() async throws {
try await fixture(name: "DependencyResolution/External/Simple") { fixturePath in
let packageRoot = fixturePath.appending("Bar")
// Check that `resolve` works.
_ = try await execute(["resolve"], packagePath: packageRoot)
let path = try SwiftPM.packagePath(for: "Foo", packageRoot: packageRoot)
XCTAssertEqual(try GitRepository(path: path).getTags(), ["1.2.3"])
}
}
func testUpdate() async throws {
try await fixture(name: "DependencyResolution/External/Simple") { fixturePath in
let packageRoot = fixturePath.appending("Bar")
// Perform an initial fetch.
_ = try await execute(["resolve"], packagePath: packageRoot)
do {
let checkoutPath = try SwiftPM.packagePath(for: "Foo", packageRoot: packageRoot)
let checkoutRepo = GitRepository(path: checkoutPath)
XCTAssertEqual(try checkoutRepo.getTags(), ["1.2.3"])
_ = try checkoutRepo.revision(forTag: "1.2.3")
}
// update and retag the dependency, and update.
let repoPath = fixturePath.appending("Foo")
let repo = GitRepository(path: repoPath)
try localFileSystem.writeFileContents(repoPath.appending("test"), string: "test")
try repo.stageEverything()
try repo.commit()
try repo.tag(name: "1.2.4")
// we will validate it is there
let revision = try repo.revision(forTag: "1.2.4")
_ = try await execute(["update"], packagePath: packageRoot)
do {
// We shouldn't assume package path will be same after an update so ask again for it.
let checkoutPath = try SwiftPM.packagePath(for: "Foo", packageRoot: packageRoot)
let checkoutRepo = GitRepository(path: checkoutPath)
// tag may not be there, but revision should be after update
XCTAssertTrue(checkoutRepo.exists(revision: .init(identifier: revision)))
}
}
}
func testCache() async throws {
try await fixture(name: "DependencyResolution/External/Simple") { fixturePath in
let packageRoot = fixturePath.appending("Bar")
let repositoriesPath = packageRoot.appending(components: ".build", "repositories")
let cachePath = fixturePath.appending("cache")
let repositoriesCachePath = cachePath.appending("repositories")
// Perform an initial fetch and populate the cache
_ = try await execute(["resolve", "--cache-path", cachePath.pathString], packagePath: packageRoot)
// we have to check for the prefix here since the hash value changes because spm sees the `prefix`
// directory `/var/...` as `/private/var/...`.
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesCachePath).contains { $0.hasPrefix("Foo-") })
// Remove .build folder
_ = try await execute(["reset"], packagePath: packageRoot)
// Perform another cache this time from the cache
_ = try await execute(["resolve", "--cache-path", cachePath.pathString], packagePath: packageRoot)
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
// Remove .build and cache folder
_ = try await execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
// Perform another fetch
_ = try await execute(["resolve", "--cache-path", cachePath.pathString], packagePath: packageRoot)
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesCachePath).contains { $0.hasPrefix("Foo-") })
}
}
func testDescribe() async throws {
try await fixture(name: "Miscellaneous/ExeTest") { fixturePath in
// Generate the JSON description.
let (jsonOutput, _) = try await SwiftPM.Package.execute(["describe", "--type=json"], packagePath: fixturePath)
let json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))
// Check that tests don't appear in the product memberships.
XCTAssertEqual(json["name"]?.string, "ExeTest")
let jsonTarget0 = try XCTUnwrap(json["targets"]?.array?[0])
XCTAssertNil(jsonTarget0["product_memberships"])
let jsonTarget1 = try XCTUnwrap(json["targets"]?.array?[1])
XCTAssertEqual(jsonTarget1["product_memberships"]?.array?[0].stringValue, "Exe")
}
try await fixture(name: "CFamilyTargets/SwiftCMixed") { fixturePath in
// Generate the JSON description.
let (jsonOutput, _) = try await SwiftPM.Package.execute(["describe", "--type=json"], packagePath: fixturePath)
let json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))
// Check that the JSON description contains what we expect it to.
XCTAssertEqual(json["name"]?.string, "SwiftCMixed")
XCTAssertMatch(json["path"]?.string, .prefix("/"))
XCTAssertMatch(json["path"]?.string, .suffix("/" + fixturePath.basename))
XCTAssertEqual(json["targets"]?.array?.count, 3)
let jsonTarget0 = try XCTUnwrap(json["targets"]?.array?[0])
XCTAssertEqual(jsonTarget0["name"]?.stringValue, "SeaLib")
XCTAssertEqual(jsonTarget0["c99name"]?.stringValue, "SeaLib")
XCTAssertEqual(jsonTarget0["type"]?.stringValue, "library")
XCTAssertEqual(jsonTarget0["module_type"]?.stringValue, "ClangTarget")
let jsonTarget1 = try XCTUnwrap(json["targets"]?.array?[1])
XCTAssertEqual(jsonTarget1["name"]?.stringValue, "SeaExec")
XCTAssertEqual(jsonTarget1["c99name"]?.stringValue, "SeaExec")
XCTAssertEqual(jsonTarget1["type"]?.stringValue, "executable")
XCTAssertEqual(jsonTarget1["module_type"]?.stringValue, "SwiftTarget")
XCTAssertEqual(jsonTarget1["product_memberships"]?.array?[0].stringValue, "SeaExec")
let jsonTarget2 = try XCTUnwrap(json["targets"]?.array?[2])
XCTAssertEqual(jsonTarget2["name"]?.stringValue, "CExec")
XCTAssertEqual(jsonTarget2["c99name"]?.stringValue, "CExec")
XCTAssertEqual(jsonTarget2["type"]?.stringValue, "executable")
XCTAssertEqual(jsonTarget2["module_type"]?.stringValue, "ClangTarget")
XCTAssertEqual(jsonTarget2["product_memberships"]?.array?[0].stringValue, "CExec")
// Generate the text description.
let (textOutput, _) = try await SwiftPM.Package.execute(["describe", "--type=text"], packagePath: fixturePath)
let textChunks = textOutput.components(separatedBy: "\n").reduce(into: [""]) { chunks, line in
// Split the text into chunks based on presence or absence of leading whitespace.
if line.hasPrefix(" ") == chunks[chunks.count-1].hasPrefix(" ") {
chunks[chunks.count-1].append(line + "\n")
}
else {
chunks.append(line + "\n")
}
}.filter{ !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
// Check that the text description contains what we expect it to.
// FIXME: This is a bit inelegant, but any errors are easy to reason about.
let textChunk0 = try XCTUnwrap(textChunks[0])
XCTAssertMatch(textChunk0, .contains("Name: SwiftCMixed"))
XCTAssertMatch(textChunk0, .contains("Path: /"))
XCTAssertMatch(textChunk0, .contains("/" + fixturePath.basename + "\n"))
XCTAssertMatch(textChunk0, .contains("Tools version: 4.2"))
XCTAssertMatch(textChunk0, .contains("Products:"))
let textChunk1 = try XCTUnwrap(textChunks[1])
XCTAssertMatch(textChunk1, .contains("Name: SeaExec"))
XCTAssertMatch(textChunk1, .contains("Type:\n Executable"))
XCTAssertMatch(textChunk1, .contains("Targets:\n SeaExec"))
let textChunk2 = try XCTUnwrap(textChunks[2])
XCTAssertMatch(textChunk2, .contains("Name: CExec"))
XCTAssertMatch(textChunk2, .contains("Type:\n Executable"))
XCTAssertMatch(textChunk2, .contains("Targets:\n CExec"))
let textChunk3 = try XCTUnwrap(textChunks[3])
XCTAssertMatch(textChunk3, .contains("Targets:"))
let textChunk4 = try XCTUnwrap(textChunks[4])
XCTAssertMatch(textChunk4, .contains("Name: SeaLib"))
XCTAssertMatch(textChunk4, .contains("C99name: SeaLib"))
XCTAssertMatch(textChunk4, .contains("Type: library"))
XCTAssertMatch(textChunk4, .contains("Module type: ClangTarget"))
XCTAssertMatch(textChunk4, .contains("Path: Sources/SeaLib"))
XCTAssertMatch(textChunk4, .contains("Sources:\n Foo.c"))
let textChunk5 = try XCTUnwrap(textChunks[5])
XCTAssertMatch(textChunk5, .contains("Name: SeaExec"))
XCTAssertMatch(textChunk5, .contains("C99name: SeaExec"))
XCTAssertMatch(textChunk5, .contains("Type: executable"))
XCTAssertMatch(textChunk5, .contains("Module type: SwiftTarget"))
XCTAssertMatch(textChunk5, .contains("Path: Sources/SeaExec"))
XCTAssertMatch(textChunk5, .contains("Sources:\n main.swift"))
let textChunk6 = try XCTUnwrap(textChunks[6])
XCTAssertMatch(textChunk6, .contains("Name: CExec"))
XCTAssertMatch(textChunk6, .contains("C99name: CExec"))
XCTAssertMatch(textChunk6, .contains("Type: executable"))
XCTAssertMatch(textChunk6, .contains("Module type: ClangTarget"))
XCTAssertMatch(textChunk6, .contains("Path: Sources/CExec"))
XCTAssertMatch(textChunk6, .contains("Sources:\n main.c"))
}
try await fixture(name: "DependencyResolution/External/Simple/Bar") { fixturePath in
// Generate the JSON description.
let (jsonOutput, _) = try await SwiftPM.Package.execute(["describe", "--type=json"], packagePath: fixturePath)
let json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))
// Check that product dependencies and memberships are as expected.
XCTAssertEqual(json["name"]?.string, "Bar")
let jsonTarget = try XCTUnwrap(json["targets"]?.array?[0])
XCTAssertEqual(jsonTarget["product_memberships"]?.array?[0].stringValue, "Bar")
XCTAssertEqual(jsonTarget["product_dependencies"]?.array?[0].stringValue, "Foo")
XCTAssertNil(jsonTarget["target_dependencies"])
}
}
func testDescribePackageUsingPlugins() async throws {
try await fixture(name: "Miscellaneous/Plugins/MySourceGenPlugin") { fixturePath in
// Generate the JSON description.
let (stdout, _) = try await SwiftPM.Package.execute(["describe", "--type=json"], packagePath: fixturePath)
let json = try JSON(bytes: ByteString(encodingAsUTF8: stdout))
// Check the contents of the JSON.
XCTAssertEqual(try XCTUnwrap(json["name"]).string, "MySourceGenPlugin")
let targetsArray = try XCTUnwrap(json["targets"]?.array)
let buildToolPluginTarget = try XCTUnwrap(targetsArray.first{ $0["name"]?.string == "MySourceGenBuildToolPlugin" }?.dictionary)
XCTAssertEqual(buildToolPluginTarget["module_type"]?.string, "PluginTarget")
XCTAssertEqual(buildToolPluginTarget["plugin_capability"]?.dictionary?["type"]?.string, "buildTool")
let prebuildPluginTarget = try XCTUnwrap(targetsArray.first{ $0["name"]?.string == "MySourceGenPrebuildPlugin" }?.dictionary)
XCTAssertEqual(prebuildPluginTarget["module_type"]?.string, "PluginTarget")
XCTAssertEqual(prebuildPluginTarget["plugin_capability"]?.dictionary?["type"]?.string, "buildTool")
}
}
func testDumpPackage() async throws {
try await fixture(name: "DependencyResolution/External/Complex") { fixturePath in
let packageRoot = fixturePath.appending("app")
let (dumpOutput, _) = try await execute(["dump-package"], packagePath: packageRoot)
let json = try JSON(bytes: ByteString(encodingAsUTF8: dumpOutput))
guard case let .dictionary(contents) = json else { XCTFail("unexpected result"); return }
guard case let .string(name)? = contents["name"] else { XCTFail("unexpected result"); return }
guard case let .array(platforms)? = contents["platforms"] else { XCTFail("unexpected result"); return }
XCTAssertEqual(name, "Dealer")
XCTAssertEqual(platforms, [
.dictionary([
"platformName": .string("macos"),
"version": .string("10.12"),
"options": .array([])
]),
.dictionary([
"platformName": .string("ios"),
"version": .string("10.0"),
"options": .array([])
]),
.dictionary([
"platformName": .string("tvos"),
"version": .string("11.0"),
"options": .array([])
]),
.dictionary([
"platformName": .string("watchos"),
"version": .string("5.0"),
"options": .array([])
]),
])
}
}
// Returns symbol graph with or without pretty printing.
private func symbolGraph(atPath path: AbsolutePath, withPrettyPrinting: Bool, file: StaticString = #file, line: UInt = #line) async throws -> Data? {
let tool = try SwiftCommandState.makeMockState(options: GlobalOptions.parse(["--package-path", path.pathString]))
let symbolGraphExtractorPath = try tool.getTargetToolchain().getSymbolGraphExtract()
let arguments = withPrettyPrinting ? ["dump-symbol-graph", "--pretty-print"] : ["dump-symbol-graph"]
let result = try await SwiftPM.Package.execute(arguments, packagePath: path, env: ["SWIFT_SYMBOLGRAPH_EXTRACT": symbolGraphExtractorPath.pathString])
let enumerator = try XCTUnwrap(FileManager.default.enumerator(at: URL(fileURLWithPath: path.pathString), includingPropertiesForKeys: nil), file: file, line: line)
var symbolGraphURL: URL?
for case let url as URL in enumerator where url.lastPathComponent == "Bar.symbols.json" {
symbolGraphURL = url
break
}
let symbolGraphData: Data
if let symbolGraphURL {
symbolGraphData = try Data(contentsOf: symbolGraphURL)
} else {
XCTFail("Failed to extract symbol graph: \(result.stdout)\n\(result.stderr)")
return nil
}
// Double check that it's a valid JSON
XCTAssertNoThrow(try JSONSerialization.jsonObject(with: symbolGraphData), file: file, line: line)
return symbolGraphData
}
func testDumpSymbolGraphCompactFormatting() async throws {
// Depending on how the test is running, the `swift-symbolgraph-extract` tool might be unavailable.
try XCTSkipIf((try? UserToolchain.default.getSymbolGraphExtract()) == nil, "skipping test because the `swift-symbolgraph-extract` tools isn't available")
try await fixture(name: "DependencyResolution/Internal/Simple") { fixturePath in
let compactGraphData = try await XCTAsyncUnwrap(await symbolGraph(atPath: fixturePath, withPrettyPrinting: false))
let compactJSONText = String(decoding: compactGraphData, as: UTF8.self)
XCTAssertEqual(compactJSONText.components(separatedBy: .newlines).count, 1)
}
}
func testDumpSymbolGraphPrettyFormatting() async throws {
// Depending on how the test is running, the `swift-symbolgraph-extract` tool might be unavailable.
try XCTSkipIf((try? UserToolchain.default.getSymbolGraphExtract()) == nil, "skipping test because the `swift-symbolgraph-extract` tools isn't available")
try await fixture(name: "DependencyResolution/Internal/Simple") { fixturePath in
let prettyGraphData = try await XCTAsyncUnwrap(await symbolGraph(atPath: fixturePath, withPrettyPrinting: true))
let prettyJSONText = String(decoding: prettyGraphData, as: UTF8.self)
XCTAssertGreaterThan(prettyJSONText.components(separatedBy: .newlines).count, 1)
}
}
func testShowExecutables() async throws {
try await fixture(name: "Miscellaneous/ShowExecutables") { fixturePath in
let packageRoot = fixturePath.appending("app")
let (textOutput, _) = try await SwiftPM.Package.execute(["show-executables", "--format=flatlist"], packagePath: packageRoot)
XCTAssert(textOutput.contains("dealer\n"))
XCTAssert(textOutput.contains("deck (deck-of-playing-cards)\n"))
let (jsonOutput, _) = try await SwiftPM.Package.execute(["show-executables", "--format=json"], packagePath: packageRoot)
let json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))
guard case let .array(contents) = json else { XCTFail("unexpected result"); return }
XCTAssertEqual(2, contents.count)
guard case let first = contents.first else { XCTFail("unexpected result"); return }
guard case let .dictionary(dealer) = first else { XCTFail("unexpected result"); return }
guard case let .string(dealerName)? = dealer["name"] else { XCTFail("unexpected result"); return }
XCTAssertEqual(dealerName, "dealer")
if case let .string(package)? = dealer["package"] {
XCTFail("unexpected package for dealer (should be unset): \(package)")
return
}
guard case let last = contents.last else { XCTFail("unexpected result"); return }
guard case let .dictionary(deck) = last else { XCTFail("unexpected result"); return }
guard case let .string(deckName)? = deck["name"] else { XCTFail("unexpected result"); return }
XCTAssertEqual(deckName, "deck")
if case let .string(package)? = deck["package"] {
XCTAssertEqual("deck-of-playing-cards", package)
} else {
XCTFail("missing package for deck")
return
}
}
}
func testShowDependencies() async throws {
try await fixture(name: "DependencyResolution/External/Complex") { fixturePath in
let packageRoot = fixturePath.appending("app")
let (textOutput, _) = try await SwiftPM.Package.execute(["show-dependencies", "--format=text"], packagePath: packageRoot)
XCTAssert(textOutput.contains("[email protected]"))
let (jsonOutput, _) = try await SwiftPM.Package.execute(["show-dependencies", "--format=json"], packagePath: packageRoot)
let json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))
guard case let .dictionary(contents) = json else { XCTFail("unexpected result"); return }
guard case let .string(name)? = contents["name"] else { XCTFail("unexpected result"); return }
XCTAssertEqual(name, "Dealer")
guard case let .string(path)? = contents["path"] else { XCTFail("unexpected result"); return }
XCTAssertEqual(try resolveSymlinks(try AbsolutePath(validating: path)), try resolveSymlinks(packageRoot))
}
}
func testShowDependencies_dotFormat_sr12016() throws {
// Confirm that SR-12016 is resolved.
// See https://bugs.swift.org/browse/SR-12016
let fileSystem = InMemoryFileSystem(emptyFiles: [
"/PackageA/Sources/TargetA/main.swift",
"/PackageB/Sources/TargetB/B.swift",
"/PackageC/Sources/TargetC/C.swift",
"/PackageD/Sources/TargetD/D.swift",
])
let manifestA = Manifest.createRootManifest(
displayName: "PackageA",
path: "/PackageA",
toolsVersion: .v5_3,
dependencies: [
.fileSystem(path: "/PackageB"),
.fileSystem(path: "/PackageC"),
],
products: [
try .init(name: "exe", type: .executable, targets: ["TargetA"])
],
targets: [
try .init(name: "TargetA", dependencies: ["PackageB", "PackageC"])
]
)
let manifestB = Manifest.createFileSystemManifest(
displayName: "PackageB",
path: "/PackageB",
toolsVersion: .v5_3,
dependencies: [
.fileSystem(path: "/PackageC"),
.fileSystem(path: "/PackageD"),
],
products: [
try .init(name: "PackageB", type: .library(.dynamic), targets: ["TargetB"])
],
targets: [
try .init(name: "TargetB", dependencies: ["PackageC", "PackageD"])
]
)
let manifestC = Manifest.createFileSystemManifest(
displayName: "PackageC",
path: "/PackageC",
toolsVersion: .v5_3,
dependencies: [
.fileSystem(path: "/PackageD"),
],
products: [
try .init(name: "PackageC", type: .library(.dynamic), targets: ["TargetC"])
],
targets: [
try .init(name: "TargetC", dependencies: ["PackageD"])
]
)
let manifestD = Manifest.createFileSystemManifest(
displayName: "PackageD",
path: "/PackageD",
toolsVersion: .v5_3,
products: [
try .init(name: "PackageD", type: .library(.dynamic), targets: ["TargetD"])
],
targets: [
try .init(name: "TargetD")
]
)
let observability = ObservabilitySystem.makeForTesting()
let graph = try loadModulesGraph(
fileSystem: fileSystem,
manifests: [manifestA, manifestB, manifestC, manifestD],
observabilityScope: observability.topScope
)
XCTAssertNoDiagnostics(observability.diagnostics)
let output = BufferedOutputByteStream()
SwiftPackageCommand.ShowDependencies.dumpDependenciesOf(
graph: graph,
rootPackage: graph.rootPackages[graph.rootPackages.startIndex],
mode: .dot,
on: output
)
let dotFormat = output.bytes.description
var alreadyPutOut: Set<Substring> = []
for line in dotFormat.split(whereSeparator: { $0.isNewline }) {
if alreadyPutOut.contains(line) {
XCTFail("Same line was already put out: \(line)")
}
alreadyPutOut.insert(line)
}
let expectedLines: [Substring] = [
#""/PackageA" [label="packagea\n/PackageA\nunspecified"]"#,
#""/PackageB" [label="packageb\n/PackageB\nunspecified"]"#,
#""/PackageC" [label="packagec\n/PackageC\nunspecified"]"#,
#""/PackageD" [label="packaged\n/PackageD\nunspecified"]"#,
#""/PackageA" -> "/PackageB""#,
#""/PackageA" -> "/PackageC""#,
#""/PackageB" -> "/PackageC""#,
#""/PackageB" -> "/PackageD""#,
#""/PackageC" -> "/PackageD""#,
]
for expectedLine in expectedLines {
XCTAssertTrue(alreadyPutOut.contains(expectedLine),
"Expected line is not found: \(expectedLine)")
}
}
func testShowDependencies_redirectJsonOutput() async throws {
try await testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let root = tmpPath.appending(components: "root")
let dep = tmpPath.appending(components: "dep")
// Create root package.
let mainFilePath = root.appending(components: "Sources", "root", "main.swift")
try fs.writeFileContents(mainFilePath, string: "")
try fs.writeFileContents(root.appending("Package.swift"), string:
"""
// swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "root",
dependencies: [.package(url: "../dep", from: "1.0.0")],
targets: [.target(name: "root", dependencies: ["dep"])]
)
"""
)
// Create dependency.
try fs.writeFileContents(dep.appending(components: "Sources", "dep", "lib.swift"), string: "")
try fs.writeFileContents(dep.appending("Package.swift"), string:
"""
// swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "dep",
products: [.library(name: "dep", targets: ["dep"])],
targets: [.target(name: "dep")]
)
"""
)
do {
let depGit = GitRepository(path: dep)
try depGit.create()
try depGit.stageEverything()
try depGit.commit()
try depGit.tag(name: "1.0.0")
}
let resultPath = root.appending("result.json")
_ = try await execute(["show-dependencies", "--format", "json", "--output-path", resultPath.pathString ], packagePath: root)
XCTAssertFileExists(resultPath)
let jsonOutput: Data = try fs.readFileContents(resultPath)
let json = try JSON(data: jsonOutput)
XCTAssertEqual(json["name"]?.string, "root")
XCTAssertEqual(json["dependencies"]?[0]?["name"]?.string, "dep")
}
}
func testInitEmpty() async throws {
try await testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending("Foo")
try fs.createDirectory(path)
_ = try await execute(["init", "--type", "empty"], packagePath: path)
XCTAssertFileExists(path.appending("Package.swift"))
}
}
func testInitExecutable() async throws {
try await testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending("Foo")
try fs.createDirectory(path)
_ = try await execute(["init", "--type", "executable"], packagePath: path)
let manifest = path.appending("Package.swift")
let contents: String = try localFileSystem.readFileContents(manifest)
let version = InitPackage.newPackageToolsVersion
let versionSpecifier = "\(version.major).\(version.minor)"
XCTAssertMatch(contents, .prefix("// swift-tools-version:\(version < .v5_4 ? "" : " ")\(versionSpecifier)\n"))
XCTAssertFileExists(manifest)
XCTAssertEqual(try fs.getDirectoryContents(path.appending("Sources")), ["main.swift"])
}
}
func testInitLibrary() async throws {
try await testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending("Foo")
try fs.createDirectory(path)
_ = try await execute(["init"], packagePath: path)
XCTAssertFileExists(path.appending("Package.swift"))
XCTAssertEqual(try fs.getDirectoryContents(path.appending("Sources").appending("Foo")), ["Foo.swift"])
XCTAssertEqual(try fs.getDirectoryContents(path.appending("Tests")).sorted(), ["FooTests"])
}
}
func testInitCustomNameExecutable() async throws {
try await testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending("Foo")
try fs.createDirectory(path)
_ = try await execute(["init", "--name", "CustomName", "--type", "executable"], packagePath: path)
let manifest = path.appending("Package.swift")
let contents: String = try localFileSystem.readFileContents(manifest)
let version = InitPackage.newPackageToolsVersion
let versionSpecifier = "\(version.major).\(version.minor)"
XCTAssertMatch(contents, .prefix("// swift-tools-version:\(version < .v5_4 ? "" : " ")\(versionSpecifier)\n"))
XCTAssertFileExists(manifest)
XCTAssertEqual(try fs.getDirectoryContents(path.appending("Sources")), ["main.swift"])
}
}
func testPackageAddURLDependency() async throws {
try await testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending("PackageB")
try fs.createDirectory(path)
try fs.writeFileContents(path.appending("Package.swift"), string:
"""
// swift-tools-version: 5.9
import PackageDescription
let package = Package(
name: "client",
targets: [ .target(name: "client", dependencies: [ "library" ]) ]
)
"""
)
_ = try await execute(
[
"add-dependency",
"https://github.com/swiftlang/swift-syntax.git",
"--exact",
"1.0.0",
],
packagePath: path
)
_ = try await execute(
[
"add-dependency",
"https://github.com/swiftlang/swift-syntax.git",
"--branch",
"main",
],
packagePath: path
)
_ = try await execute(
[
"add-dependency",
"https://github.com/swiftlang/swift-syntax.git",
"--revision",
"58e9de4e7b79e67c72a46e164158e3542e570ab6",
],
packagePath: path
)
_ = try await execute(
[
"add-dependency",
"https://github.com/swiftlang/swift-syntax.git",
"--from",
"1.0.0",
],
packagePath: path
)
_ = try await execute(
[
"add-dependency",
"https://github.com/swiftlang/swift-syntax.git",
"--up-to-next-minor-from",
"1.0.0",
],
packagePath: path
)
let manifest = path.appending("Package.swift")
XCTAssertFileExists(manifest)
let contents: String = try fs.readFileContents(manifest)
XCTAssertMatch(contents, .contains(#".package(url: "https://github.com/swiftlang/swift-syntax.git", exact: "1.0.0"),"#))
XCTAssertMatch(contents, .contains(#".package(url: "https://github.com/swiftlang/swift-syntax.git", branch: "main"),"#))
XCTAssertMatch(contents, .contains(#".package(url: "https://github.com/swiftlang/swift-syntax.git", revision: "58e9de4e7b79e67c72a46e164158e3542e570ab6"),"#))
XCTAssertMatch(contents, .contains(#".package(url: "https://github.com/swiftlang/swift-syntax.git", from: "1.0.0"),"#))
XCTAssertMatch(contents, .contains(#".package(url: "https://github.com/swiftlang/swift-syntax.git", "1.0.0" ..< "1.1.0"),"#))
}
}
func testPackageAddPathDependency() async throws {
try await testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending("PackageB")
try fs.createDirectory(path)
try fs.writeFileContents(path.appending("Package.swift"), string:
"""
// swift-tools-version: 5.9
import PackageDescription
let package = Package(
name: "client",
targets: [ .target(name: "client", dependencies: [ "library" ]) ]
)
"""
)
_ = try await execute(
[
"add-dependency",
"/directory",
"--type",
"path"
],
packagePath: path
)
let manifest = path.appending("Package.swift")
XCTAssertFileExists(manifest)
let contents: String = try fs.readFileContents(manifest)
XCTAssertMatch(contents, .contains(#".package(path: "/directory"),"#))
}
}
func testPackageAddRegistryDependency() async throws {
try await testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending("PackageB")
try fs.createDirectory(path)
try fs.writeFileContents(path.appending("Package.swift"), string:
"""
// swift-tools-version: 5.9
import PackageDescription
let package = Package(
name: "client",
targets: [ .target(name: "client", dependencies: [ "library" ]) ]
)
"""
)
_ = try await execute(
[
"add-dependency",
"scope.name",
"--type",
"registry",
"--exact",
"1.0.0",
],
packagePath: path
)
_ = try await execute(
[
"add-dependency",
"scope.name",
"--type",
"registry",
"--from",
"1.0.0",
],
packagePath: path
)
_ = try await execute(
[
"add-dependency",
"scope.name",
"--type",
"registry",
"--up-to-next-minor-from",
"1.0.0",
],
packagePath: path
)