Skip to content

Commit cce860c

Browse files
hartbitaciidgh
authored andcommitted
Remove TSCBasic.Dictionary.init(items:) (#2410)
* Remove TSCBasic.Dictionary.init(items:) as it can be implemented using the new Dictionary initializers * Improvements after review
1 parent e7bf021 commit cce860c

22 files changed

+40
-62
lines changed

Sources/PackageGraph/PinsStore.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ extension PinsStore: SimplePersistanceProtocol {
131131
}
132132

133133
public func restore(from json: JSON) throws {
134-
self.pinsMap = try Dictionary(items: json.get("pins").map({ ($0.packageRef.identity, $0) }))
134+
self.pinsMap = try Dictionary(uniqueKeysWithValues: json.get("pins").map({ ($0.packageRef.identity, $0) }))
135135
}
136136

137137
/// Saves the current state of pins.

Sources/PackageLoading/PackageBuilder.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -519,8 +519,8 @@ public final class PackageBuilder {
519519
}
520520

521521
let targetItems = manifest.targets.map({ ($0.name, $0 as TargetDescription) })
522-
let targetMap = Dictionary(items: targetItems)
523-
let potentialModuleMap = Dictionary(items: potentialModules.map({ ($0.name, $0) }))
522+
let targetMap = Dictionary(targetItems, uniquingKeysWith: { $1 })
523+
let potentialModuleMap = Dictionary(potentialModules.map({ ($0.name, $0) }), uniquingKeysWith: { $1 })
524524
let successors: (PotentialModule) -> [PotentialModule] = {
525525
// No reference of this target in manifest, i.e. it has no dependencies.
526526
guard let target = targetMap[$0.name] else { return [] }
@@ -984,7 +984,7 @@ public final class PackageBuilder {
984984
}
985985

986986
// Map containing targets mapped to their names.
987-
let modulesMap = Dictionary(items: targets.map({ ($0.name, $0) }))
987+
let modulesMap = Dictionary(targets.map({ ($0.name, $0) }), uniquingKeysWith: { $1 })
988988

989989
/// Helper method to get targets from target names.
990990
func modulesFrom(targetNames names: [String], product: String) throws -> [Target] {

Sources/PackageLoading/ToolsVersionLoader.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ extension Manifest {
5050
let regex = try! RegEx(pattern: "^Package@swift-(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?.swift$")
5151

5252
// Collect all version-specific manifests at the given package path.
53-
let versionSpecificManifests = Dictionary(items: contents.compactMap{ file -> (ToolsVersion, String)? in
53+
let versionSpecificManifests = Dictionary(contents.compactMap{ file -> (ToolsVersion, String)? in
5454
let parsedVersion = regex.matchGroups(in: file)
5555
guard parsedVersion.count == 1, parsedVersion[0].count == 3 else {
5656
return nil
@@ -61,7 +61,7 @@ extension Manifest {
6161
let patch = parsedVersion[0][2].isEmpty ? 0 : Int(parsedVersion[0][2])!
6262

6363
return (ToolsVersion(version: Version(major, minor, patch)), file)
64-
})
64+
}, uniquingKeysWith: { $1 })
6565

6666
let regularManifest = packagePath.appending(component: filename)
6767
let toolsVersionLoader = ToolsVersionLoader(currentToolsVersion: currentToolsVersion)

Sources/SPMTestSupport/MockDependencyGraph.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ public struct MockManifestGraph {
102102
repoProvider = inMemory?.provider
103103
// Create the test repositories, we don't need them to have actual
104104
// contents (the manifests are mocked).
105-
let repos = Dictionary(items: try packages.map({ package -> (String, RepositorySpecifier) in
105+
let repos = Dictionary(uniqueKeysWithValues: try packages.map({ package -> (String, RepositorySpecifier) in
106106
let repoPath = path.appending(component: package.name)
107107
let tag = package.version?.description ?? "initial"
108108
let specifier = RepositorySpecifier(url: repoPath.pathString)
@@ -150,7 +150,7 @@ public struct MockManifestGraph {
150150
)
151151

152152
// Create the manifests from mock packages.
153-
var manifests = Dictionary(items: packages.map({ package -> (MockManifestLoader.Key, Manifest) in
153+
var manifests = Dictionary(uniqueKeysWithValues: packages.map({ package -> (MockManifestLoader.Key, Manifest) in
154154
let url = repos[package.name]!.url
155155
let manifest = Manifest(
156156
name: package.name,

Sources/SPMTestSupport/MockDependencyResolver.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ public struct MockPackagesProvider: PackageContainerProvider {
203203

204204
public init(containers: [MockPackageContainer]) {
205205
self.containers = containers
206-
self.containersByIdentifier = Dictionary(items: containers.map({ ($0.identifier, $0) }))
206+
self.containersByIdentifier = Dictionary(uniqueKeysWithValues: containers.map({ ($0.identifier, $0) }))
207207
}
208208

209209
public func getContainer(
@@ -255,7 +255,7 @@ public struct MockGraph {
255255
guard case let .array(containers)? = dict["containers"] else { fatalError() }
256256
guard case let .dictionary(result)? = dict["result"] else { fatalError() }
257257

258-
self.result = Dictionary(items: result.map({ value in
258+
self.result = Dictionary(uniqueKeysWithValues: result.map({ value in
259259
let (container, version) = value
260260
guard case let .string(str) = version else { fatalError() }
261261
return (container.lowercased(), Version(string: str)!)

Sources/SourceControl/RepositoryManager.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -390,9 +390,9 @@ extension RepositoryManager: SimplePersistanceProtocol {
390390
// We will use this to save the state so we don't have to read the other
391391
// handles when saving the sate of a handle.
392392
self.serializedRepositories = try json.get("repositories")
393-
self.repositories = try Dictionary(items: serializedRepositories.map({
394-
try ($0.0, RepositoryHandle(manager: self, json: $0.1))
395-
}))
393+
self.repositories = try serializedRepositories.mapValues({
394+
try RepositoryHandle(manager: self, json: $0)
395+
})
396396
}
397397

398398
public func toJSON() -> JSON {

Sources/TSCBasic/DictionaryExtensions.swift

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -9,22 +9,6 @@
99
*/
1010

1111
extension Dictionary {
12-
/// Convenience initializer to create dictionary from tuples.
13-
public init<S: Sequence>(items: S) where S.Iterator.Element == (Key, Value) {
14-
self.init(minimumCapacity: items.underestimatedCount)
15-
for (key, value) in items {
16-
self[key] = value
17-
}
18-
}
19-
20-
/// Convenience initializer to create dictionary from tuples.
21-
public init<S: Sequence>(items: S) where S.Iterator.Element == (Key, Optional<Value>) {
22-
self.init(minimumCapacity: items.underestimatedCount)
23-
for (key, value) in items {
24-
self[key] = value
25-
}
26-
}
27-
2812
/// Returns a new dictionary containing the keys of this dictionary with the
2913
/// values transformed by the given closure, if transformed is not nil.
3014
public func spm_flatMapValues<T>(_ transform: (Value) throws -> T?) rethrows -> [Key: T] {

Sources/TSCBasic/JSON.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,7 @@ extension JSON {
278278

279279
extension JSON {
280280
public init(_ dict: [String: JSONSerializable]) {
281-
self = .dictionary(Dictionary(items: dict.map({ ($0.0, $0.1.toJSON()) })))
281+
self = .dictionary(dict.mapValues({ $0.toJSON() }))
282282
}
283283
}
284284

Sources/TSCBasic/JSONMapper.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ extension JSON {
6565
throw MapError.typeMismatch(
6666
key: key, expected: Dictionary<String, JSON>.self, json: object)
6767
}
68-
return try Dictionary(items: value.map({ ($0.0, try T.init(json: $0.1)) }))
68+
return try value.mapValues({ try T.init(json: $0) })
6969
}
7070

7171
/// Returns a JSON mappable dictionary from a given key.

Sources/TSCUtility/ArgumentParser.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -815,7 +815,7 @@ public final class ArgumentParser {
815815
}
816816
return result
817817
})
818-
let optionsMap = Dictionary(items: optionsTuple)
818+
let optionsMap = Dictionary(uniqueKeysWithValues: optionsTuple)
819819

820820
// Create iterators.
821821
var positionalArgumentIterator = positionalArguments.makeIterator()

Sources/Workspace/ManagedDependency.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ public final class ManagedDependencies: SimplePersistanceProtocol {
296296
}
297297

298298
public func restore(from json: JSON) throws {
299-
self.dependencyMap = try Dictionary(items:
299+
self.dependencyMap = try Dictionary(uniqueKeysWithValues:
300300
json.get("dependencies").map({ ($0.packageRef.path, $0) })
301301
)
302302
}

Sources/Workspace/Workspace.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ public class Workspace {
186186
}
187187

188188
func computePackageURLs() -> (required: Set<PackageReference>, missing: Set<PackageReference>) {
189-
let manifestsMap: [String: Manifest] = Dictionary(items:
189+
let manifestsMap: [String: Manifest] = Dictionary(uniqueKeysWithValues:
190190
root.manifests.map({ (PackageReference.computeIdentity(packageURL: $0.url), $0) }) +
191191
dependencies.map({ (PackageReference.computeIdentity(packageURL: $0.manifest.url), $0.manifest) }))
192192

Tests/BuildTests/BuildPlanTests.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1831,8 +1831,8 @@ private struct BuildPlanResult {
18311831

18321832
init(plan: BuildPlan) {
18331833
self.plan = plan
1834-
self.productMap = Dictionary(items: plan.buildProducts.map{ ($0.product.name, $0) })
1835-
self.targetMap = Dictionary(items: plan.targetMap.map{ ($0.0.name, $0.1) })
1834+
self.productMap = Dictionary(uniqueKeysWithValues: plan.buildProducts.map{ ($0.product.name, $0) })
1835+
self.targetMap = Dictionary(uniqueKeysWithValues: plan.targetMap.map{ ($0.0.name, $0.1) })
18361836
}
18371837

18381838
func checkTargetsCount(_ count: Int, file: StaticString = #file, line: UInt = #line) {

Tests/PackageGraphTests/DependencyResolverTests.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -986,7 +986,7 @@ private extension DependencyResolver {
986986
subjectTo allConstraints: [PackageReference: VersionSetSpecifier] = [:],
987987
excluding exclusions: [PackageReference: Set<Version>] = [:]
988988
) -> AnySequence<VersionAssignmentSet> {
989-
let constraints = Dictionary(items: allConstraints.map{ ($0.0, PackageRequirement.versionSet($0.1)) })
989+
let constraints = Dictionary(uniqueKeysWithValues: allConstraints.map{ ($0.0, PackageRequirement.versionSet($0.1)) })
990990
return resolveSubtree(container, subjectTo: PackageContainerConstraintSet(constraints), excluding: exclusions)
991991
}
992992
}

Tests/PackageGraphTests/PubgrubTests.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1923,7 +1923,7 @@ public struct MockProvider: PackageContainerProvider {
19231923

19241924
public init(containers: [MockContainer]) {
19251925
self.containers = containers
1926-
self.containersByIdentifier = Dictionary(items: containers.map({ ($0.identifier, $0) }))
1926+
self.containersByIdentifier = Dictionary(uniqueKeysWithValues: containers.map({ ($0.identifier, $0) }))
19271927
}
19281928

19291929
public func getContainer(

Tests/PackageLoadingTests/PD4LoadingTests.swift

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ class PackageDescription4LoadingTests: XCTestCase {
9494

9595
loadManifest(stream.bytes) { manifest in
9696
XCTAssertEqual(manifest.name, "Trivial")
97-
let targets = Dictionary(items:
97+
let targets = Dictionary(uniqueKeysWithValues:
9898
manifest.targets.map({ ($0.name, $0 as TargetDescription ) }))
9999
let foo = targets["foo"]!
100100
XCTAssertEqual(foo.name, "foo")
@@ -169,7 +169,7 @@ class PackageDescription4LoadingTests: XCTestCase {
169169
)
170170
"""
171171
loadManifest(stream.bytes) { manifest in
172-
let deps = Dictionary(items: manifest.dependencies.map{ ($0.url, $0) })
172+
let deps = Dictionary(uniqueKeysWithValues: manifest.dependencies.map{ ($0.url, $0) })
173173
XCTAssertEqual(deps["/foo1"], PackageDependencyDescription(url: "/foo1", requirement: .upToNextMajor(from: "1.0.0")))
174174
XCTAssertEqual(deps["/foo2"], PackageDependencyDescription(url: "/foo2", requirement: .upToNextMajor(from: "1.0.0")))
175175
XCTAssertEqual(deps["/foo3"], PackageDependencyDescription(url: "/foo3", requirement: .upToNextMinor(from: "1.0.0")))
@@ -193,7 +193,7 @@ class PackageDescription4LoadingTests: XCTestCase {
193193
)
194194
"""
195195
loadManifest(stream.bytes) { manifest in
196-
let products = Dictionary(items: manifest.products.map{ ($0.name, $0) })
196+
let products = Dictionary(uniqueKeysWithValues: manifest.products.map{ ($0.name, $0) })
197197
// Check tool.
198198
let tool = products["tool"]!
199199
XCTAssertEqual(tool.name, "tool")
@@ -251,7 +251,7 @@ class PackageDescription4LoadingTests: XCTestCase {
251251
)
252252
"""
253253
loadManifest(stream.bytes) { manifest in
254-
let targets = Dictionary(items:
254+
let targets = Dictionary(uniqueKeysWithValues:
255255
manifest.targets.map({ ($0.name, $0 as TargetDescription ) }))
256256

257257
let foo = targets["Foo"]!
@@ -281,7 +281,7 @@ class PackageDescription4LoadingTests: XCTestCase {
281281
)
282282
"""
283283
loadManifest(stream.bytes) { manifest in
284-
let targets = Dictionary(items:
284+
let targets = Dictionary(uniqueKeysWithValues:
285285
manifest.targets.map({ ($0.name, $0 as TargetDescription ) }))
286286

287287
let foo = targets["Foo"]!

Tests/PackageLoadingTests/PD4_2LoadingTests.swift

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ class PackageDescription4_2LoadingTests: XCTestCase {
8282
XCTAssertEqual(manifest.name, "Trivial")
8383

8484
// Check targets.
85-
let targets = Dictionary(items:
85+
let targets = Dictionary(uniqueKeysWithValues:
8686
manifest.targets.map({ ($0.name, $0 as TargetDescription ) }))
8787
let foo = targets["foo"]!
8888
XCTAssertEqual(foo.name, "foo")
@@ -95,11 +95,11 @@ class PackageDescription4_2LoadingTests: XCTestCase {
9595
XCTAssertEqual(bar.dependencies, ["foo"])
9696

9797
// Check dependencies.
98-
let deps = Dictionary(items: manifest.dependencies.map{ ($0.url, $0) })
98+
let deps = Dictionary(uniqueKeysWithValues: manifest.dependencies.map{ ($0.url, $0) })
9999
XCTAssertEqual(deps["/foo1"], PackageDependencyDescription(url: "/foo1", requirement: .upToNextMajor(from: "1.0.0")))
100100

101101
// Check products.
102-
let products = Dictionary(items: manifest.products.map{ ($0.name, $0) })
102+
let products = Dictionary(uniqueKeysWithValues: manifest.products.map{ ($0.name, $0) })
103103

104104
let tool = products["tool"]!
105105
XCTAssertEqual(tool.name, "tool")
@@ -285,7 +285,7 @@ class PackageDescription4_2LoadingTests: XCTestCase {
285285
)
286286
"""
287287
loadManifest(stream.bytes) { manifest in
288-
let deps = Dictionary(items: manifest.dependencies.map{ ($0.url, $0) })
288+
let deps = Dictionary(uniqueKeysWithValues: manifest.dependencies.map{ ($0.url, $0) })
289289
XCTAssertEqual(deps["/foo1"], PackageDependencyDescription(url: "/foo1", requirement: .upToNextMajor(from: "1.0.0")))
290290
XCTAssertEqual(deps["/foo2"], PackageDependencyDescription(url: "/foo2", requirement: .revision("58e9de4e7b79e67c72a46e164158e3542e570ab6")))
291291

@@ -337,7 +337,7 @@ class PackageDescription4_2LoadingTests: XCTestCase {
337337
)
338338
"""
339339
loadManifest(stream.bytes) { manifest in
340-
let targets = Dictionary(items:
340+
let targets = Dictionary(uniqueKeysWithValues:
341341
manifest.targets.map({ ($0.name, $0 as TargetDescription ) }))
342342
let foo = targets["foo"]!
343343
XCTAssertEqual(foo.name, "foo")

Tests/PackageLoadingTests/PD5LoadingTests.swift

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ class PackageDescription5LoadingTests: XCTestCase {
8484
XCTAssertEqual(manifest.name, "Trivial")
8585

8686
// Check targets.
87-
let targets = Dictionary(items:
87+
let targets = Dictionary(uniqueKeysWithValues:
8888
manifest.targets.map({ ($0.name, $0 as TargetDescription ) }))
8989
let foo = targets["foo"]!
9090
XCTAssertEqual(foo.name, "foo")
@@ -97,11 +97,11 @@ class PackageDescription5LoadingTests: XCTestCase {
9797
XCTAssertEqual(bar.dependencies, ["foo"])
9898

9999
// Check dependencies.
100-
let deps = Dictionary(items: manifest.dependencies.map{ ($0.url, $0) })
100+
let deps = Dictionary(uniqueKeysWithValues: manifest.dependencies.map{ ($0.url, $0) })
101101
XCTAssertEqual(deps["/foo1"], PackageDependencyDescription(url: "/foo1", requirement: .upToNextMajor(from: "1.0.0")))
102102

103103
// Check products.
104-
let products = Dictionary(items: manifest.products.map{ ($0.name, $0) })
104+
let products = Dictionary(uniqueKeysWithValues: manifest.products.map{ ($0.name, $0) })
105105

106106
let tool = products["tool"]!
107107
XCTAssertEqual(tool.name, "tool")
@@ -488,7 +488,7 @@ class PackageDescription5LoadingTests: XCTestCase {
488488
XCTAssertEqual(manifest.name, "Foo")
489489

490490
// Check targets.
491-
let targets = Dictionary(items:
491+
let targets = Dictionary(uniqueKeysWithValues:
492492
manifest.targets.map({ ($0.name, $0 as TargetDescription ) }))
493493
let foo = targets["foo"]!
494494
XCTAssertEqual(foo.name, "foo")

Tests/SourceControlTests/GitRepositoryTests.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -381,10 +381,10 @@ class GitRepositoryTests: XCTestCase {
381381
// Add a remote via git cli.
382382
try systemQuietly([Git.tool, "-C", testRepoPath.pathString, "remote", "add", "origin", "../foo"])
383383
// Test if it was added.
384-
XCTAssertEqual(Dictionary(items: try repo.remotes().map { ($0.0, $0.1) }), ["origin": "../foo"])
384+
XCTAssertEqual(Dictionary(uniqueKeysWithValues: try repo.remotes().map { ($0.0, $0.1) }), ["origin": "../foo"])
385385
// Change remote.
386386
try repo.setURL(remote: "origin", url: "../bar")
387-
XCTAssertEqual(Dictionary(items: try repo.remotes().map { ($0.0, $0.1) }), ["origin": "../bar"])
387+
XCTAssertEqual(Dictionary(uniqueKeysWithValues: try repo.remotes().map { ($0.0, $0.1) }), ["origin": "../bar"])
388388
// Try changing remote of non-existant remote.
389389
do {
390390
try repo.setURL(remote: "fake", url: "../bar")

Tests/TSCBasicTests/DictionaryExtensionsTests.swift

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,6 @@ import TSCBasic
1414
class DictionaryExtensionTests: XCTestCase {
1515

1616
func testBasics() {
17-
XCTAssertEqual(Dictionary(items: [("foo", 1), ("bar", 2)]), ["foo": 1, "bar": 2])
18-
XCTAssertEqual(Dictionary(items: [(1, 1), (1, 2)]), [1: 2])
19-
20-
XCTAssertEqual(Dictionary(items: [(1, 1), (1, nil)]), [:])
21-
XCTAssertEqual(Dictionary(items: [(1, 1), (2, nil), (3, 4)]), [1: 1, 3: 4])
22-
2317
XCTAssertEqual(["foo": "1", "bar": "2", "baz": "f"].spm_flatMapValues({ Int($0) }), ["foo": 1, "bar": 2])
2418
}
2519

Tests/TSCBasicTests/JSONMapperTests.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ fileprivate struct Foo: JSONMappable, JSONSerializable {
6464
"bar": bar.toJSON(),
6565
"barOp": barOp.flatMap{$0.toJSON()} ?? .null,
6666
"barArray": .array(barArray.map{$0.toJSON()}),
67-
"dict": .dictionary(Dictionary(items: dict.map{($0.0, .double($0.1))})),
67+
"dict": .dictionary(Dictionary(uniqueKeysWithValues: dict.map{($0.0, .double($0.1))})),
6868
])
6969
}
7070

Tests/XcodeprojTests/PackageGraphTests.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -423,7 +423,7 @@ private class XcodeProjectResult {
423423

424424
init(_ project: Xcode.Project) {
425425
self.project = project
426-
self.targetMap = Dictionary(items: project.targets.map { target -> (String, Xcode.Target) in (target.name, target) })
426+
self.targetMap = Dictionary(uniqueKeysWithValues: project.targets.map { target -> (String, Xcode.Target) in (target.name, target) })
427427
}
428428

429429
func check(projectDir: String, file: StaticString = #file, line: UInt = #line) {

0 commit comments

Comments
 (0)