File: PackageIdentity.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (608 lines) | stat: -rw-r--r-- 21,989 bytes parent folder | download
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import Basics
import Foundation

/// The canonical identifier for a package, based on its source location.
public struct PackageIdentity: CustomStringConvertible, Sendable {
    /// A textual representation of this instance.
    public let description: String

    /// Creates a package identity from a string.
    /// - Parameter value: A string used to identify a package.
    init(_ value: String) {
        self.description = value
    }

    /// Creates a package identity from a URL.
    /// - Parameter url: The package's URL.
    public init(url: SourceControlURL) {
        self.init(urlString: url.absoluteString)
    }

    /// Creates a package identity from a URL.
    /// - Parameter urlString: The package's URL.
    // FIXME: deprecate this
    public init(urlString: String) {
        self.description = PackageIdentityParser(urlString).description
    }

    /// Creates a package identity from a file path.
    /// - Parameter path: An absolute path to the package.
    public init(path: AbsolutePath) {
        self.description = PackageIdentityParser(path.pathString).description
    }

    /// Creates a plain package identity for a root package
    /// - Parameter value: A string used to identify a package, will be used unmodified
    public static func plain(_ value: String) -> PackageIdentity {
        PackageIdentity(value)
    }

    @available(*, deprecated, message: "use .registry instead")
    public var scopeAndName: (scope: Scope, name: Name)? {
        self.registry.flatMap { (scope: $0.scope, name: $0.name) }
    }

    public var registry: RegistryIdentity? {
        let components = self.description.split(separator: ".", maxSplits: 1, omittingEmptySubsequences: true)
        guard components.count == 2,
              let scope = Scope(components.first),
              let name = Name(components.last)
        else {
            return .none
        }

        return RegistryIdentity(
            scope: scope,
            name: name,
            underlying: self
        )
    }

    public var isRegistry: Bool {
        self.registry != nil
    }

    public struct RegistryIdentity: Hashable, CustomStringConvertible, Sendable {
        public let scope: PackageIdentity.Scope
        public let name: PackageIdentity.Name
        public let underlying: PackageIdentity

        public var description: String {
            self.underlying.description
        }
    }
}

extension PackageIdentity: Equatable, Comparable {
    private func compare(to other: PackageIdentity) -> ComparisonResult {
        self.description.caseInsensitiveCompare(other.description)
    }

    public static func == (lhs: PackageIdentity, rhs: PackageIdentity) -> Bool {
        lhs.compare(to: rhs) == .orderedSame
    }

    public static func < (lhs: PackageIdentity, rhs: PackageIdentity) -> Bool {
        lhs.compare(to: rhs) == .orderedAscending
    }

    public static func > (lhs: PackageIdentity, rhs: PackageIdentity) -> Bool {
        lhs.compare(to: rhs) == .orderedDescending
    }
}

extension PackageIdentity: Hashable {
    public func hash(into hasher: inout Hasher) {
        hasher.combine(self.description.lowercased())
    }
}

extension PackageIdentity: Codable {
    public init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        let description = try container.decode(String.self)
        self.init(description)
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(self.description)
    }
}

// MARK: -

extension PackageIdentity {
    /// Provides a namespace for related packages within a package registry.
    public struct Scope: LosslessStringConvertible, Hashable, Equatable, Comparable, ExpressibleByStringLiteral,
        Sendable
    {
        public let description: String

        public init(validating description: String) throws {
            guard !description.isEmpty else {
                throw StringError("The minimum length of a package scope is 1 character.")
            }

            guard description.count <= 39 else {
                throw StringError("The maximum length of a package scope is 39 characters.")
            }

            for (index, character) in zip(description.indices, description) {
                guard character.isASCII,
                      character.isLetter ||
                      character.isNumber ||
                      character == "-"
                else {
                    throw StringError("A package scope consists of alphanumeric characters and hyphens.")
                }

                if character.isPunctuation {
                    switch (index, description.index(after: index)) {
                    case (description.startIndex, _):
                        throw StringError("Hyphens may not occur at the beginning of a scope.")
                    case (_, description.endIndex):
                        throw StringError("Hyphens may not occur at the end of a scope.")
                    case (_, let nextIndex) where description[nextIndex].isPunctuation:
                        throw StringError("Hyphens may not occur consecutively within a scope.")
                    default:
                        continue
                    }
                }
            }

            self.description = description
        }

        public init?(_ description: String) {
            guard let scope = try? Scope(validating: description) else { return nil }
            self = scope
        }

        fileprivate init?(_ substring: String.SubSequence?) {
            guard let substring else { return nil }
            self.init(String(substring))
        }

        // MARK: - Equatable & Comparable

        private func compare(to other: Scope) -> ComparisonResult {
            // Package scopes are case-insensitive (for example, `mona` ≍ `MONA`).
            self.description.caseInsensitiveCompare(other.description)
        }

        public static func == (lhs: Scope, rhs: Scope) -> Bool {
            lhs.compare(to: rhs) == .orderedSame
        }

        public static func < (lhs: Scope, rhs: Scope) -> Bool {
            lhs.compare(to: rhs) == .orderedAscending
        }

        public static func > (lhs: Scope, rhs: Scope) -> Bool {
            lhs.compare(to: rhs) == .orderedDescending
        }

        // MARK: - Hashable

        public func hash(into hasher: inout Hasher) {
            hasher.combine(self.description.lowercased())
        }

        // MARK: - ExpressibleByStringLiteral

        public init(stringLiteral value: StringLiteralType) {
            try! self.init(validating: value)
        }
    }

    /// Uniquely identifies a package in a scope
    public struct Name: LosslessStringConvertible, Hashable, Equatable, Comparable, ExpressibleByStringLiteral,
        Sendable
    {
        public let description: String

        public init(validating description: String) throws {
            guard !description.isEmpty else {
                throw StringError("The minimum length of a package name is 1 character.")
            }

            guard description.count <= 100 else {
                throw StringError("The maximum length of a package name is 100 characters.")
            }

            for (index, character) in zip(description.indices, description) {
                guard character.isASCII,
                      character.isLetter ||
                      character.isNumber ||
                      character == "-" ||
                      character == "_"
                else {
                    throw StringError("A package name consists of alphanumeric characters, underscores, and hyphens.")
                }

                if character.isPunctuation {
                    switch (index, description.index(after: index)) {
                    case (description.startIndex, _):
                        throw StringError("Hyphens and underscores may not occur at the beginning of a name.")
                    case (_, description.endIndex):
                        throw StringError("Hyphens and underscores may not occur at the end of a name.")
                    case (_, let nextIndex) where description[nextIndex].isPunctuation:
                        throw StringError("Hyphens and underscores may not occur consecutively within a name.")
                    default:
                        continue
                    }
                }
            }

            self.description = description
        }

        public init?(_ description: String) {
            guard let name = try? Name(validating: description) else { return nil }
            self = name
        }

        fileprivate init?(_ substring: String.SubSequence?) {
            guard let substring else { return nil }
            self.init(String(substring))
        }

        // MARK: - Equatable & Comparable

        private func compare(to other: Name) -> ComparisonResult {
            // Package scopes are case-insensitive (for example, `LinkedList` ≍ `LINKEDLIST`).
            self.description.caseInsensitiveCompare(other.description)
        }

        public static func == (lhs: Name, rhs: Name) -> Bool {
            lhs.compare(to: rhs) == .orderedSame
        }

        public static func < (lhs: Name, rhs: Name) -> Bool {
            lhs.compare(to: rhs) == .orderedAscending
        }

        public static func > (lhs: Name, rhs: Name) -> Bool {
            lhs.compare(to: rhs) == .orderedDescending
        }

        // MARK: - Hashable

        public func hash(into hasher: inout Hasher) {
            hasher.combine(self.description.lowercased())
        }

        // MARK: - ExpressibleByStringLiteral

        public init(stringLiteral value: StringLiteralType) {
            try! self.init(validating: value)
        }
    }
}

// MARK: -

struct PackageIdentityParser {
    /// A textual representation of this instance.
    public let description: String

    /// Instantiates an instance of the conforming type from a string representation.
    public init(_ string: String) {
        self.description = Self.computeDefaultName(fromLocation: string).lowercased()
    }

    /// Compute the default name of a package given its URL.
    public static func computeDefaultName(fromURL url: SourceControlURL) -> String {
        Self.computeDefaultName(fromLocation: url.absoluteString)
    }

    /// Compute the default name of a package given its path.
    public static func computeDefaultName(fromPath path: AbsolutePath) -> String {
        Self.computeDefaultName(fromLocation: path.pathString)
    }

    /// Compute the default name of a package given its location.
    public static func computeDefaultName(fromLocation url: String) -> String {
        #if os(Windows)
        let isSeparator: (Character) -> Bool = { $0 == "/" || $0 == "\\" }
        #else
        let isSeparator: (Character) -> Bool = { $0 == "/" }
        #endif

        // Get the last path component of the URL.
        // Drop the last character in case it's a trailing slash.
        var endIndex = url.endIndex
        if let lastCharacter = url.last, isSeparator(lastCharacter) {
            endIndex = url.index(before: endIndex)
        }

        let separatorIndex = url[..<endIndex].lastIndex(where: isSeparator)
        let startIndex = separatorIndex.map { url.index(after: $0) } ?? url.startIndex
        var lastComponent = url[startIndex ..< endIndex]

        // Strip `.git` suffix if present.
        if lastComponent.hasSuffix(".git") {
            lastComponent = lastComponent.dropLast(4)
        }

        return String(lastComponent)
    }
}

/// A canonicalized package location.
///
/// A package may declare external packages as dependencies in its manifest.
/// Each external package is uniquely identified by the location of its source code.
///
/// An external package dependency may itself have one or more external package dependencies,
/// known as _transitive dependencies_.
/// When multiple packages have dependencies in common,
/// Swift Package Manager determines which version of that package should be used
/// (if any exist that satisfy all specified requirements)
/// in a process called package resolution.
///
/// External package dependencies are located by a URL
/// (which may be an implicit `file://` URL in the form of a file path).
/// For the purposes of package resolution,
/// package URLs are case-insensitive (mona ≍ MONA)
/// and normalization-insensitive (n + ◌̃ ≍ ñ).
/// Swift Package Manager takes additional steps to canonicalize URLs
/// to resolve insignificant differences between URLs.
/// For example,
/// the URLs `https://example.com/Mona/LinkedList` and `git@example.com:mona/linkedlist`
/// are equivalent, in that they both resolve to the same source code repository,
/// despite having different scheme, authority, and path components.
///
/// The `PackageIdentity` type canonicalizes package locations by
/// performing the following operations:
///
/// * Removing the scheme component, if present
///   ```
///   https://example.com/mona/LinkedList → example.com/mona/LinkedList
///   ```
/// * Removing the userinfo component (preceded by `@`), if present:
///   ```
///   git@example.com/mona/LinkedList → example.com/mona/LinkedList
///   ```
/// * Removing the port subcomponent, if present:
///   ```
///   example.com:443/mona/LinkedList → example.com/mona/LinkedList
///   ```
/// * Replacing the colon (`:`) preceding the path component in "`scp`-style" URLs:
///   ```
///   git@example.com:mona/LinkedList.git → example.com/mona/LinkedList
///   ```
/// * Expanding the tilde (`~`) to the provided user, if applicable:
///   ```
///   ssh://mona@example.com/~/LinkedList.git → example.com/~mona/LinkedList
///   ```
/// * Removing percent-encoding from the path component, if applicable:
///   ```
///   example.com/mona/%F0%9F%94%97List → example.com/mona/🔗List
///   ```
/// * Removing the `.git` file extension from the path component, if present:
///   ```
///   example.com/mona/LinkedList.git → example.com/mona/LinkedList
///   ```
/// * Removing the trailing slash (`/`) in the path component, if present:
///   ```
///   example.com/mona/LinkedList/ → example.com/mona/LinkedList
///   ```
/// * Removing the fragment component (preceded by `#`), if present:
///   ```
///   example.com/mona/LinkedList#installation → example.com/mona/LinkedList
///   ```
/// * Removing the query component (preceded by `?`), if present:
///   ```
///   example.com/mona/LinkedList?utm_source=forums.swift.org → example.com/mona/LinkedList
///   ```
/// * Adding a leading slash (`/`) for `file://` URLs and absolute file paths:
///   ```
///   file:///Users/mona/LinkedList → /Users/mona/LinkedList
///   ```
public struct CanonicalPackageLocation: Equatable, CustomStringConvertible {
    /// A textual representation of this instance.
    public let description: String

    /// Instantiates an instance of the conforming type from a string representation.
    public init(_ string: String) {
        self.description = computeCanonicalLocation(string).description
    }
}

/// Similar to `CanonicalPackageLocation` but differentiates based on the scheme.
public struct CanonicalPackageURL: Equatable, CustomStringConvertible {
    public let description: String
    public let scheme: String?

    public init(_ string: String) {
        let location = computeCanonicalLocation(string)
        self.description = location.description
        self.scheme = location.scheme
    }
}

private func computeCanonicalLocation(_ string: String) -> (description: String, scheme: String?) {
    var description = string.precomposedStringWithCanonicalMapping.lowercased()

    // Remove the scheme component, if present.
    let detectedScheme = description.dropSchemeComponentPrefixIfPresent()
    var scheme = detectedScheme

    // Remove the userinfo subcomponent (user / password), if present.
    if case (let user, _)? = description.dropUserinfoSubcomponentPrefixIfPresent() {
        // If a user was provided, perform tilde expansion, if applicable.
        description.replaceFirstOccurrenceIfPresent(of: "/~/", with: "/~\(user)/")

        if user == "git", scheme == nil {
            scheme = "ssh"
        }
    }

    // Remove the port subcomponent, if present.
    description.removePortComponentIfPresent()

    // Remove the fragment component, if present.
    description.removeFragmentComponentIfPresent()

    // Remove the query component, if present.
    description.removeQueryComponentIfPresent()

    // Accommodate "`scp`-style" SSH URLs
    if detectedScheme == nil || detectedScheme == "ssh" {
        description.replaceFirstOccurrenceIfPresent(of: ":", before: description.firstIndex(of: "/"), with: "/")
    }

    // Split the remaining string into path components,
    // filtering out empty path components and removing valid percent encodings.
    var components = description.split(omittingEmptySubsequences: true, whereSeparator: isSeparator)
        .compactMap { $0.removingPercentEncoding ?? String($0) }

    // Remove the `.git` suffix from the last path component.
    var lastPathComponent = components.popLast() ?? ""
    lastPathComponent.removeSuffixIfPresent(".git")
    components.append(lastPathComponent)

    description = components.joined(separator: "/")

    // Prepend a leading slash for file URLs and paths
    if detectedScheme == "file" || string.first.flatMap(isSeparator) ?? false {
        scheme = "file"
        description.insert("/", at: description.startIndex)
    }

    return (description, scheme)
}

#if os(Windows)
fileprivate let isSeparator: (Character) -> Bool = { $0 == "/" || $0 == "\\" }
#else
fileprivate let isSeparator: (Character) -> Bool = { $0 == "/" }
#endif

extension Character {
    fileprivate var isDigit: Bool {
        switch self {
        case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
            return true
        default:
            return false
        }
    }

    fileprivate var isAllowedInURLScheme: Bool {
        isLetter || self.isDigit || self == "+" || self == "-" || self == "."
    }
}

extension String {
    @discardableResult
    private mutating func removePrefixIfPresent<T: StringProtocol>(_ prefix: T) -> Bool {
        guard hasPrefix(prefix) else { return false }
        removeFirst(prefix.count)
        return true
    }

    @discardableResult
    fileprivate mutating func removeSuffixIfPresent<T: StringProtocol>(_ suffix: T) -> Bool {
        guard hasSuffix(suffix) else { return false }
        removeLast(suffix.count)
        return true
    }

    @discardableResult
    fileprivate mutating func dropSchemeComponentPrefixIfPresent() -> String? {
        if let rangeOfDelimiter = range(of: "://"),
           self[startIndex].isLetter,
           self[..<rangeOfDelimiter.lowerBound].allSatisfy(\.isAllowedInURLScheme)
        {
            defer { self.removeSubrange(..<rangeOfDelimiter.upperBound) }

            return String(self[..<rangeOfDelimiter.lowerBound])
        }

        return nil
    }

    @discardableResult
    fileprivate mutating func dropUserinfoSubcomponentPrefixIfPresent() -> (user: String, password: String?)? {
        if let indexOfAtSign = firstIndex(of: "@"),
           let indexOfFirstPathComponent = firstIndex(where: isSeparator),
           indexOfAtSign < indexOfFirstPathComponent
        {
            defer { self.removeSubrange(...indexOfAtSign) }

            let userinfo = self[..<indexOfAtSign]
            var components = userinfo.split(separator: ":", maxSplits: 2, omittingEmptySubsequences: false)
            guard components.count > 0 else { return nil }
            let user = String(components.removeFirst())
            let password = components.last.map(String.init)

            return (user, password)
        }

        return nil
    }

    @discardableResult
    fileprivate mutating func removePortComponentIfPresent() -> Bool {
        if let indexOfFirstPathComponent = firstIndex(where: isSeparator),
           let startIndexOfPort = firstIndex(of: ":"),
           startIndexOfPort < endIndex,
           let endIndexOfPort = self[index(after: startIndexOfPort)...].lastIndex(where: { $0.isDigit }),
           endIndexOfPort <= indexOfFirstPathComponent
        {
            self.removeSubrange(startIndexOfPort ... endIndexOfPort)
            return true
        }

        return false
    }

    @discardableResult
    fileprivate mutating func removeFragmentComponentIfPresent() -> Bool {
        if let index = firstIndex(of: "#") {
            self.removeSubrange(index...)
        }

        return false
    }

    @discardableResult
    fileprivate mutating func removeQueryComponentIfPresent() -> Bool {
        if let index = firstIndex(of: "?") {
            self.removeSubrange(index...)
        }

        return false
    }

    @discardableResult
    fileprivate mutating func replaceFirstOccurrenceIfPresent<T: StringProtocol, U: StringProtocol>(
        of string: T,
        before index: Index? = nil,
        with replacement: U
    ) -> Bool {
        guard let range = range(of: string) else { return false }

        if let index, range.lowerBound >= index {
            return false
        }

        self.replaceSubrange(range, with: replacement)
        return true
    }
}