-
Notifications
You must be signed in to change notification settings - Fork 233
Expand file tree
/
Copy pathURL_Swift.swift
More file actions
1327 lines (1178 loc) · 50.9 KB
/
URL_Swift.swift
File metadata and controls
1327 lines (1178 loc) · 50.9 KB
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.org open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if FOUNDATION_FRAMEWORK
#if canImport(os)
internal import os
#endif
internal import _ForSwiftFoundation
internal import Synchronization
/// `_SwiftURL` provides the new Swift implementation for `URL`, using the same parser
/// and `URLParseInfo` as `URLComponents`, but with a few compatibility behaviors.
///
/// Outside of `FOUNDATION_FRAMEWORK`, `_SwiftURL` provides the sole implementation
/// for `URL`. In `FOUNDATION_FRAMEWORK`, there are additional classes to handle `NSURL`
/// subclassing and bridging from ObjC.
///
/// - Note: For functions returning `URL?`, a `nil` return value allows `struct URL` to return `self` without creating a new struct.
internal final class _SwiftURL: Sendable, Hashable, Equatable {
typealias Parser = RFC3986Parser
internal let _parseInfo: URLParseInfo
internal let _baseURL: URL?
internal let _encoding: String.Encoding
// URL was created from a file path initializer and is absolute
private let _isCanonicalFileURL: Bool
#if FOUNDATION_FRAMEWORK
// Used frequently for NS/CFURL behaviors
private var isDecomposable: Bool {
return _parseInfo.scheme == nil || hasAuthority || _parseInfo.path.utf8.first == ._slash
}
// Note: We use a lock instead of a lazy var to ensure that we always
// bridge to the same NSURL even if the URL was copied across threads.
private let _nsurlLock = Mutex<NSURL?>(nil)
private var _nsurl: NSURL {
return _nsurlLock.withLock {
if let nsurl = $0 { return nsurl }
let nsurl = if _foundation_swift_nsurl_feature_enabled() {
_swiftCFURL() as NSURL
} else {
Self._makeNSURL(from: _parseInfo, baseURL: _baseURL)
}
$0 = nsurl
return nsurl
}
}
#endif
internal var url: URL {
URL(self)
}
private static func parse(string: String, encodingInvalidCharacters: Bool = true) -> URLParseInfo? {
return Parser.parse(urlString: string, encodingInvalidCharacters: encodingInvalidCharacters, allowEmptyScheme: true)
}
private static func compatibilityParse(string: String, encodingInvalidCharacters: Bool = false) -> URLParseInfo? {
return Parser.compatibilityParse(urlString: string, encodingInvalidCharacters: encodingInvalidCharacters)
}
init?(stringOrEmpty: String, relativeTo base: URL? = nil, encodingInvalidCharacters: Bool = true, encoding: String.Encoding = .utf8, compatibility: Bool = false, forceBaseURL: Bool = false) {
let parseInfo = if compatibility {
Self.compatibilityParse(string: stringOrEmpty, encodingInvalidCharacters: encodingInvalidCharacters)
} else {
Self.parse(string: stringOrEmpty, encodingInvalidCharacters: encodingInvalidCharacters)
}
guard let parseInfo else { return nil }
_parseInfo = parseInfo
_baseURL = (forceBaseURL || parseInfo.scheme == nil) ? base?.absoluteURL : nil
_encoding = encoding
_isCanonicalFileURL = false
}
convenience init?(string: String) {
guard !string.isEmpty else { return nil }
self.init(stringOrEmpty: string)
}
convenience init?(string: String, relativeTo base: URL?) {
guard !string.isEmpty else { return nil }
self.init(stringOrEmpty: string, relativeTo: base)
}
convenience init?(string: String, encodingInvalidCharacters: Bool) {
guard !string.isEmpty else { return nil }
self.init(stringOrEmpty: string, encodingInvalidCharacters: encodingInvalidCharacters)
}
convenience init?(stringOrEmpty: String, relativeTo base: URL?) {
self.init(stringOrEmpty: stringOrEmpty, relativeTo: base, encoding: .utf8)
}
convenience init(fileURLWithPath path: String, isDirectory: Bool, relativeTo base: URL?) {
let directoryHint: URL.DirectoryHint = isDirectory ? .isDirectory : .notDirectory
self.init(filePath: path.isEmpty ? "." : path, directoryHint: directoryHint, relativeTo: base)
}
convenience init(fileURLWithPath path: String, relativeTo base: URL?) {
let directoryHint: URL.DirectoryHint = path.utf8.last == ._slash ? .isDirectory : .checkFileSystem
self.init(filePath: path.isEmpty ? "." : path, directoryHint: directoryHint, relativeTo: base)
}
convenience init(fileURLWithPath path: String, isDirectory: Bool) {
let directoryHint: URL.DirectoryHint = isDirectory ? .isDirectory : .notDirectory
self.init(filePath: path.isEmpty ? "." : path, directoryHint: directoryHint)
}
convenience init(fileURLWithPath path: String) {
let directoryHint: URL.DirectoryHint = path.utf8.last == ._slash ? .isDirectory : .checkFileSystem
self.init(filePath: path.isEmpty ? "." : path, directoryHint: directoryHint)
}
convenience init(filePath path: String, directoryHint: URL.DirectoryHint = .inferFromPath, relativeTo base: URL? = nil) {
// .init(fileURLWithPath:) inits call through here, convert path to FSR now
self.init(filePath: path.fileSystemRepresentation, pathStyle: URL.defaultPathStyle, directoryHint: directoryHint, relativeTo: base)
}
internal init(filePath path: String, pathStyle: URL.PathStyle, directoryHint: URL.DirectoryHint = .inferFromPath, relativeTo base: URL? = nil) {
// Note: don't convert to file system representation in this init since
// .init(fileURLWithFileSystemRepresentation:) calls into it, too.
var baseURL = base
guard !path.isEmpty else {
#if !NO_FILESYSTEM
baseURL = baseURL ?? Self.currentDirectoryOrNil()
#endif
_parseInfo = Parser.parse(filePath: "./", isAbsolute: false)
_baseURL = baseURL?.absoluteURL
_encoding = .utf8
_isCanonicalFileURL = false
return
}
var filePath = if pathStyle == .windows {
// Convert any "\" to "/" before storing the URL parse info
path.replacing(._backslash, with: ._slash)
} else {
path
}
#if FOUNDATION_FRAMEWORK
// Linked-on-or-after check for apps which incorrectly pass a full URL
// string with a scheme. In the old implementation, this could work
// rarely if the app immediately called .appendingPathComponent(_:),
// which used to accidentally interpret a relative path starting with
// "scheme:" as an absolute "scheme:" URL string.
if URL.compatibility1 {
if filePath.utf8.starts(with: "file:".utf8) {
#if canImport(os)
URL.logger.fault("API MISUSE: URL(filePath:) called with a \"file:\" scheme. Input must only contain a path. Dropping \"file:\" scheme.")
#endif
filePath = String(filePath.dropFirst(5))._compressingSlashes()
} else if filePath.utf8.starts(with: "http:".utf8) || filePath.utf8.starts(with: "https:".utf8) {
#if canImport(os)
URL.logger.fault("API MISUSE: URL(filePath:) called with an HTTP URL string. Using URL(string:) instead.")
#endif
guard let parseInfo = Self.parse(string: filePath, encodingInvalidCharacters: true) else {
fatalError("API MISUSE: URL(filePath:) called with an HTTP URL string. URL(string:) returned nil.")
}
_parseInfo = parseInfo
_baseURL = nil // Drop the base URL since we have an HTTP scheme
_encoding = .utf8
_isCanonicalFileURL = false
return
}
}
#endif
let isAbsolute = URL.isAbsolute(standardizing: &filePath, pathStyle: pathStyle)
#if !NO_FILESYSTEM
if !isAbsolute {
baseURL = baseURL ?? Self.currentDirectoryOrNil()
}
#endif
let isDirectory: Bool
switch directoryHint {
case .isDirectory:
isDirectory = true
case .notDirectory:
filePath = filePath._droppingTrailingSlashes
isDirectory = false
case .checkFileSystem:
#if !NO_FILESYSTEM
func absoluteFilePath() -> String {
guard !isAbsolute, let baseURL else {
return filePath
}
let absolutePath = baseURL.absolutePath(percentEncoded: true).merging(relativePath: filePath)
return Self.fileSystemPath(for: absolutePath)
}
isDirectory = Self.isDirectory(absoluteFilePath())
#else
isDirectory = filePath.utf8.last == ._slash
#endif
case .inferFromPath:
isDirectory = filePath.utf8.last == ._slash
}
if isDirectory && !filePath.isEmpty && filePath.utf8.last != ._slash {
filePath += "/"
}
if isAbsolute {
let encodedPath = Parser.percentEncode(filePath, component: .path) ?? "/"
_parseInfo = Parser.parse(filePath: encodedPath, isAbsolute: true)
_baseURL = nil // Drop the baseURL if the URL is absolute
_isCanonicalFileURL = true
} else {
let encodedPath = Parser.percentEncode(filePath, component: .path) ?? ""
_parseInfo = Parser.parse(filePath: encodedPath, isAbsolute: false)
_baseURL = baseURL?.absoluteURL
_isCanonicalFileURL = false
}
_encoding = .utf8
}
init(url: _SwiftURL) {
_parseInfo = url._parseInfo
_baseURL = url._baseURL?.absoluteURL
_encoding = url._encoding
_isCanonicalFileURL = url._isCanonicalFileURL
}
convenience init?(dataRepresentation: Data, relativeTo base: URL?, isAbsolute: Bool) {
guard !dataRepresentation.isEmpty else { return nil }
var url: _SwiftURL?
if let string = String(data: dataRepresentation, encoding: .utf8) {
url = _SwiftURL(stringOrEmpty: string, relativeTo: base, encoding: .utf8, compatibility: true)
}
if url == nil, let string = String(data: dataRepresentation, encoding: .isoLatin1) {
url = _SwiftURL(stringOrEmpty: string, relativeTo: base, encoding: .isoLatin1, compatibility: true)
}
guard let url else {
return nil
}
if isAbsolute {
self.init(url: url.absoluteSwiftURL)
} else {
self.init(url: url)
}
}
convenience init(fileURLWithFileSystemRepresentation path: UnsafePointer<Int8>, isDirectory: Bool, relativeTo base: URL?) {
let pathString = String(cString: path)
let directoryHint: URL.DirectoryHint = isDirectory ? .isDirectory : .notDirectory
// Call the internal init so we don't automatically convert path to its decomposed form
self.init(filePath: pathString, pathStyle: URL.defaultPathStyle, directoryHint: directoryHint, relativeTo: base)
}
internal var encodedComponents: URLParseInfo.EncodedComponentSet {
return _parseInfo.encodedComponents
}
// MARK: - Strings, Data, and URLs
internal var originalString: String {
guard !encodedComponents.isEmpty else {
return relativeString
}
return URLComponents(parseInfo: _parseInfo)._uncheckedString(original: true)
}
var dataRepresentation: Data {
guard let result = originalString.data(using: _encoding) else {
fatalError("Could not convert URL.relativeString to data using encoding: \(_encoding)")
}
return result
}
var relativeString: String {
return _parseInfo.urlString
}
var absoluteString: String {
guard let baseURL else {
return relativeString
}
var builder = URLStringBuilder(parseInfo: _parseInfo)
if builder.scheme != nil {
builder.path = builder.path.removingDotSegments
return builder.string
}
if let baseScheme = baseURL.scheme {
builder.scheme = baseScheme
}
if hasAuthority {
return builder.string
}
let baseParseInfo = baseURL._swiftURL?._parseInfo
if let baseUser = baseURL.user(percentEncoded: true) {
builder.user = baseUser
}
if let basePassword = baseURL.password(percentEncoded: true) {
builder.password = basePassword
}
if let baseHost = baseParseInfo?.host {
builder.host = String(baseHost)
} else if let baseHost = baseURL.host(percentEncoded: true) {
builder.host = baseHost
}
if let basePort = baseParseInfo?.portString {
builder.portString = String(basePort)
} else if let basePort = baseURL.port {
builder.portString = String(basePort)
}
if builder.path.isEmpty {
builder.path = baseURL.path(percentEncoded: true)
if builder.query == nil, let baseQuery = baseURL.query(percentEncoded: true) {
builder.query = baseQuery
}
} else {
let newPath = if builder.path.utf8.first == ._slash {
builder.path
} else if baseURL.hasAuthority && baseURL.path().isEmpty {
"/" + builder.path
} else {
baseURL.path(percentEncoded: true).merging(relativePath: builder.path)
}
builder.path = newPath.removingDotSegments
}
return builder.string
}
var baseURL: URL? {
return _baseURL
}
private var absoluteSwiftURL: _SwiftURL {
guard baseURL != nil else { return self }
return _SwiftURL(stringOrEmpty: absoluteString, encoding: _encoding, compatibility: true) ?? self
}
var absoluteURL: URL? {
guard baseURL != nil else { return nil }
return absoluteSwiftURL.url
}
// MARK: - Components
var scheme: String? {
guard let scheme = _parseInfo.scheme else { return baseURL?.scheme }
return String(scheme)
}
private static let fileSchemeUTF8 = Array("file".utf8)
var isFileURL: Bool {
if _isCanonicalFileURL { return true }
guard let scheme else { return false }
return scheme.lowercased().utf8.elementsEqual(Self.fileSchemeUTF8)
}
var hasAuthority: Bool {
return _parseInfo.hasAuthority
}
var user: String? {
return user(percentEncoded: false)
}
func user(percentEncoded: Bool) -> String? {
if !hasAuthority { return baseURL?.user(percentEncoded: percentEncoded) }
guard let user = _parseInfo.user else { return nil }
if percentEncoded {
return String(user)
} else if encodedComponents.contains(.user) {
// If we encoded it using UTF-8, decode it using UTF-8
return Parser.percentDecode(user)
} else {
// Otherwise, use the encoding we were given
return Parser.percentDecode(user, encoding: _encoding)
}
}
var password: String? {
return password(percentEncoded: true)
}
func password(percentEncoded: Bool) -> String? {
if !hasAuthority { return baseURL?.password(percentEncoded: percentEncoded) }
guard let password = _parseInfo.password else { return nil }
if percentEncoded {
return String(password)
} else if encodedComponents.contains(.password) {
return Parser.percentDecode(password)
} else {
return Parser.percentDecode(password, encoding: _encoding)
}
}
var host: String? {
return host(percentEncoded: false)
}
func host(percentEncoded: Bool) -> String? {
if !hasAuthority { return baseURL?.host(percentEncoded: percentEncoded) }
guard let encodedHost = _parseInfo.host.map(String.init) else { return nil }
// According to RFC 3986, a host always exists if there is an authority
// component, it just might be empty. However, the old implementation
// of URL.host() returned nil for URLs like "https:///", and apps rely
// on this behavior, so keep it for bincompat.
if encodedHost.isEmpty && _parseInfo.user == nil && _parseInfo.password == nil && _parseInfo.portRange == nil {
return nil
}
func requestedHost() -> String? {
if percentEncoded {
if !encodedComponents.contains(.host) || _parseInfo.didPercentEncodeHost {
return encodedHost
}
// Now we need to IDNA-decode, then percent-encode
guard let decoded = Parser.IDNADecodeHost(encodedHost) else {
return encodedHost
}
return Parser.percentEncode(decoded, component: .host)
} else if encodedComponents.contains(.host) {
if _parseInfo.didPercentEncodeHost {
return Parser.percentDecode(encodedHost)
}
// Return IDNA-encoded host, which is technically not percent-encoded
return encodedHost
} else {
return Parser.percentDecode(encodedHost, encoding: _encoding)
}
}
guard let requestedHost = requestedHost() else {
return nil
}
if _parseInfo.isIPLiteral {
// Strip square brackets to be compatible with old URL.host behavior
return String(requestedHost.utf8.dropFirst().dropLast())
} else {
return requestedHost
}
}
var port: Int? {
return hasAuthority ? _parseInfo.port : baseURL?.port
}
var relativePath: String {
return Self.fileSystemPath(for: relativePath(percentEncoded: true))
}
func relativePath(percentEncoded: Bool) -> String {
if percentEncoded {
return String(_parseInfo.path)
} else if encodedComponents.contains(.path) {
return Parser.percentDecode(_parseInfo.path) ?? ""
} else {
return Parser.percentDecode(_parseInfo.path, encoding: _encoding) ?? ""
}
}
func absolutePath(percentEncoded: Bool) -> String {
if baseURL != nil {
return absoluteURL?.relativePath(percentEncoded: percentEncoded) ?? relativePath(percentEncoded: percentEncoded)
}
if percentEncoded {
return String(_parseInfo.path)
} else if encodedComponents.contains(.path) {
return Parser.percentDecode(_parseInfo.path) ?? ""
} else {
return Parser.percentDecode(_parseInfo.path, encoding: _encoding) ?? ""
}
}
var path: String {
if isFileURL { return fileSystemPath() }
let path = absolutePath(percentEncoded: true)
if encodedComponents.contains(.path) {
return Parser.percentDecode(path)?._droppingTrailingSlashes ?? ""
} else {
return Parser.percentDecode(path, encoding: _encoding)?._droppingTrailingSlashes ?? ""
}
}
func path(percentEncoded: Bool) -> String {
return absolutePath(percentEncoded: percentEncoded)
}
var query: String? {
return query(percentEncoded: true)
}
func query(percentEncoded: Bool) -> String? {
let query = _parseInfo.query
if query == nil && !hasAuthority && _parseInfo.path.isEmpty {
return baseURL?.query(percentEncoded: percentEncoded)
}
guard let query else { return nil }
if percentEncoded {
return String(query)
} else if encodedComponents.contains(.query) {
return Parser.percentDecode(query)
} else {
return Parser.percentDecode(query, encoding: _encoding)
}
}
var fragment: String? {
return fragment(percentEncoded: true)
}
func fragment(percentEncoded: Bool) -> String? {
guard let fragment = _parseInfo.fragment else { return nil }
if percentEncoded {
return String(fragment)
} else if encodedComponents.contains(.fragment) {
return Parser.percentDecode(fragment)
} else {
return Parser.percentDecode(fragment, encoding: _encoding)
}
}
// MARK: - File Paths
private static func decodeFilePath(_ path: some StringProtocol) -> String {
// Don't decode "%2F" or "%00"
let charsToLeaveEncoded: Set<UInt8> = [._slash, 0]
return Parser.percentDecode(path, excluding: charsToLeaveEncoded) ?? ""
}
private static func windowsPath(for urlPath: String, slashDropper: (String) -> String) -> String {
var iter = urlPath.utf8.makeIterator()
guard iter.next() == ._slash else {
return decodeFilePath(slashDropper(urlPath))
}
// "C:\" is standardized to "/C:/" on initialization.
if let driveLetter = iter.next(), driveLetter.isAlpha,
iter.next() == ._colon,
iter.next() == ._slash {
// Strip trailing slashes from the path, which preserves a root "/".
let path = slashDropper(String(Substring(urlPath.utf8.dropFirst(3))))
// Don't include a leading slash before the drive letter
return "\(Unicode.Scalar(driveLetter)):\(decodeFilePath(path))"
}
// There are many flavors of UNC paths, so use PathIsRootW to ensure
// we don't strip a trailing slash that represents a root.
let path = decodeFilePath(urlPath)
#if os(Windows)
return path.replacing(._slash, with: ._backslash).withCString(encodedAs: UTF16.self) { pwszPath in
guard !PathIsRootW(pwszPath) else {
return path
}
return slashDropper(path)
}
#else
return slashDropper(path)
#endif
}
internal static func fileSystemPath(for urlPath: String, style: URL.PathStyle = URL.defaultPathStyle) -> String {
let slashDropper: (String) -> String = { $0._droppingTrailingSlashes }
switch style {
case .posix: return decodeFilePath(slashDropper(urlPath))
case .windows: return windowsPath(for: urlPath, slashDropper: slashDropper)
}
}
internal func fileSystemPath(style: URL.PathStyle = URL.defaultPathStyle) -> String {
let urlPath = absolutePath(percentEncoded: true)
return Self.fileSystemPath(for: urlPath, style: style)
}
func withUnsafeFileSystemRepresentation<ResultType>(_ block: (UnsafePointer<Int8>?) throws -> ResultType) rethrows -> ResultType {
#if !os(Windows)
if _isCanonicalFileURL {
return try fileSystemPath().withCString { try block($0) }
}
#endif
return try fileSystemPath().withFileSystemRepresentation { try block($0) }
}
var hasDirectoryPath: Bool {
let path = String(_parseInfo.path)
if path.utf8.last == ._slash {
return true
}
if path.isEmpty {
return _parseInfo.scheme == nil && !hasAuthority && baseURL?.hasDirectoryPath == true
}
return path.lastPathComponent == "." || path.lastPathComponent == ".."
}
var pathComponents: [String] {
var result = absolutePath(percentEncoded: true).pathComponents.map { Parser.percentDecode($0) ?? "" }
if result.count > 1 && result.last == "/" {
_ = result.popLast()
}
return result
}
var lastPathComponent: String {
let component = absolutePath(percentEncoded: true).lastPathComponent
if isFileURL {
return Self.fileSystemPath(for: component)
} else {
return Parser.percentDecode(component, encoding: _encoding) ?? ""
}
}
var pathExtension: String {
return path.pathExtension
}
func appendingPathComponent(_ pathComponent: String, isDirectory: Bool) -> URL? {
let directoryHint: URL.DirectoryHint = isDirectory ? .isDirectory : .notDirectory
return appending(path: pathComponent, directoryHint: directoryHint)
}
func appendingPathComponent(_ pathComponent: String) -> URL? {
return appending(path: pathComponent, directoryHint: .checkFileSystem)
}
func appending<S>(path: S, directoryHint: URL.DirectoryHint) -> URL? where S : StringProtocol {
return appending(path: path, directoryHint: directoryHint, encodingSlashes: false)
}
func appending<S>(component: S, directoryHint: URL.DirectoryHint) -> URL? where S : StringProtocol {
// The old .appending(component:) implementation did not actually percent-encode
// "/" for file URLs as the documentation suggests. Many apps accidentally use
// .appending(component: "path/with/slashes") instead of using .appending(path:),
// so changing this behavior would cause breakage.
if isFileURL {
return appending(path: component, directoryHint: directoryHint, encodingSlashes: false)
}
return appending(path: component, directoryHint: directoryHint, encodingSlashes: true)
}
internal func appending<S: StringProtocol>(path: S, directoryHint: URL.DirectoryHint, encodingSlashes: Bool) -> URL? {
guard !path.isEmpty || !_parseInfo.path.isEmpty || _parseInfo.netLocationRange?.isEmpty == false else {
return nil
}
#if os(Windows)
var pathToAppend = path.replacing(._backslash, with: ._slash)
#else
var pathToAppend = String(path)
#endif
#if FOUNDATION_FRAMEWORK
if isFileURL {
// Use the file system (decomposed) representation
pathToAppend = pathToAppend.fileSystemRepresentation
}
#endif
if encodingSlashes {
pathToAppend = Parser.percentEncode(pathComponent: pathToAppend, including: [._slash])
} else {
pathToAppend = Parser.percentEncode(pathComponent: pathToAppend)
}
func appendedPath() -> String {
var currentPath = relativePath(percentEncoded: true)
if currentPath.isEmpty && !hasAuthority {
guard _parseInfo.scheme == nil else {
// Scheme only, append directly to the empty path, e.g.
// URL("scheme:").appending(path: "path") == scheme:path
return pathToAppend
}
// No scheme or authority, treat the empty path as "."
currentPath = "."
}
// If currentPath is empty, pathToAppend is relative, and we have an authority,
// we must append a slash to separate the path from authority, which happens below.
if currentPath.utf8.last != ._slash && pathToAppend.utf8.first != ._slash {
currentPath += "/"
} else if currentPath.utf8.last == ._slash && pathToAppend.utf8.first == ._slash {
_ = currentPath.popLast()
}
return currentPath + pathToAppend
}
func mergedPath(for relativePath: String) -> String {
precondition(relativePath.utf8.first != UInt8(ascii: "/"))
guard let baseURL else {
return relativePath
}
let basePath = baseURL.relativePath(percentEncoded: true)
if baseURL.hasAuthority && basePath.isEmpty {
return "/" + relativePath
}
return basePath.merging(relativePath: relativePath)
}
var newPath = appendedPath()
let hasTrailingSlash = newPath.utf8.last == ._slash
let isDirectory: Bool
switch directoryHint {
case .isDirectory:
isDirectory = true
case .notDirectory:
isDirectory = false
case .checkFileSystem:
#if !NO_FILESYSTEM
// We can only check file system if the URL is a file URL
if isFileURL {
let filePath: String
if newPath.utf8.first == ._slash {
filePath = Self.fileSystemPath(for: newPath)
} else {
filePath = Self.fileSystemPath(for: mergedPath(for: newPath))
}
isDirectory = Self.isDirectory(filePath)
} else {
// For web addresses, trust the trailing slash
isDirectory = hasTrailingSlash
}
#else // !NO_FILESYSTEM
isDirectory = hasTrailingSlash
#endif // !NO_FILESYSTEM
case .inferFromPath:
isDirectory = hasTrailingSlash
}
if isDirectory && newPath.utf8.last != ._slash {
newPath += "/"
}
var components = URLComponents(parseInfo: _parseInfo)
components.percentEncodedPath = newPath
let string = components._uncheckedString(original: false)
return _SwiftURL(stringOrEmpty: string, relativeTo: baseURL)?.url
}
#if !NO_FILESYSTEM
private static func isDirectory(_ path: String) -> Bool {
guard !path.isEmpty else { return false }
#if os(Windows)
let path = path.replacing(._slash, with: ._backslash)
return (try? path.withNTPathRepresentation { pwszPath in
// If path points to a symlink (reparse point), get a handle to
// the symlink itself using FILE_FLAG_OPEN_REPARSE_POINT.
let handle = CreateFileW(pwszPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nil)
guard handle != INVALID_HANDLE_VALUE else { return false }
defer { CloseHandle(handle) }
var info: BY_HANDLE_FILE_INFORMATION = BY_HANDLE_FILE_INFORMATION()
guard GetFileInformationByHandle(handle, &info) else { return false }
if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == FILE_ATTRIBUTE_REPARSE_POINT { return false }
return (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY
}) ?? false
#else
// FileManager uses stat() to check if the file exists.
// URL historically won't follow a symlink at the end
// of the path, so use lstat() here instead.
return path.withFileSystemRepresentation { fsRep in
guard let fsRep else { return false }
var fileInfo = stat()
guard lstat(fsRep, &fileInfo) == 0 else { return false }
return (mode_t(fileInfo.st_mode) & S_IFMT) == S_IFDIR
}
#endif
}
private static func currentDirectoryOrNil() -> URL? {
let path: String? = FileManager.default.currentDirectoryPath
guard var filePath = path else {
return nil
}
#if os(Windows)
filePath = filePath.replacing(._backslash, with: ._slash)
#endif
guard URL.isAbsolute(standardizing: &filePath) else {
return nil
}
return URL(filePath: filePath, directoryHint: .isDirectory)
}
#endif
/// True if the URL's relative path would resolve against a base URL path
private var pathResolvesAgainstBase: Bool {
return _parseInfo.scheme == nil && !hasAuthority && _parseInfo.path.utf8.first != ._slash
}
func deletingLastPathComponent() -> URL? {
let path = relativePath(percentEncoded: true)
let shouldAppendDotDot = (
pathResolvesAgainstBase && (
path.isEmpty
|| path.lastPathComponent == "."
|| path.lastPathComponent == ".."
)
)
var newPath = path
if newPath.lastPathComponent != ".." {
newPath = newPath.deletingLastPathComponent()
}
if shouldAppendDotDot {
newPath = newPath.appendingPathComponent("..")
}
if newPath.isEmpty && pathResolvesAgainstBase {
newPath = "."
}
// .deletingLastPathComponent() removes the trailing "/", but we know it's a directory
if !newPath.isEmpty && newPath.utf8.last != ._slash {
newPath += "/"
}
var components = URLComponents(parseInfo: _parseInfo)
/// Compatibility path for apps that loop on:
/// `url = url.deletingPathComponent().standardized` until `url.path.isEmpty`.
///
/// This used to work due to a combination of bugs where:
/// `URL("/").deletingLastPathComponent == URL("/../")`
/// `URL("/../").standardized == URL("")`
#if FOUNDATION_FRAMEWORK
if URL.compatibility1 && path == "/" {
components.percentEncodedPath = "/../"
} else {
components.percentEncodedPath = newPath
}
#else
components.percentEncodedPath = newPath
#endif
let string = components._uncheckedString(original: false)
return _SwiftURL(stringOrEmpty: string, relativeTo: baseURL)?.url
}
func appendingPathExtension(_ pathExtension: String) -> URL? {
guard !pathExtension.isEmpty, !_parseInfo.path.isEmpty else {
return nil
}
#if FOUNDATION_FRAMEWORK
var pathExtension = pathExtension
if isFileURL {
// Use the file system (decomposed) representation
pathExtension = pathExtension.fileSystemRepresentation
}
#endif
var components = URLComponents(parseInfo: _parseInfo)
// pathExtension might need to be percent-encoded
let encodedExtension = Parser.percentEncode(pathComponent: pathExtension)
let newPath = components.percentEncodedPath.appendingPathExtension(encodedExtension)
components.percentEncodedPath = newPath
let string = components._uncheckedString(original: false)
return _SwiftURL(string: string, relativeTo: baseURL)?.url
}
func deletingPathExtension() -> URL? {
guard !_parseInfo.path.isEmpty else { return nil }
var components = URLComponents(parseInfo: _parseInfo)
let newPath = components.percentEncodedPath.deletingPathExtension()
components.percentEncodedPath = newPath
let string = components._uncheckedString(original: false)
return _SwiftURL(stringOrEmpty: string, relativeTo: baseURL)?.url
}
var standardized: URL? {
/// Compatibility path for apps that loop on:
/// `url = url.deletingPathComponent().standardized` until `url.path.isEmpty`.
///
/// This used to work due to a combination of bugs where:
/// `URL("/").deletingLastPathComponent == URL("/../")`
/// `URL("/../").standardized == URL("")`
#if FOUNDATION_FRAMEWORK
guard isDecomposable else { return nil }
let newPath = if URL.compatibility1 && _parseInfo.path == "/../" {
""
} else {
String(_parseInfo.path).removingDotSegments
}
#else
let newPath = String(_parseInfo.path).removingDotSegments
#endif
var components = URLComponents(parseInfo: _parseInfo)
components.percentEncodedPath = newPath.removingDotSegments
if components.scheme != nil {
// Standardize scheme:// to scheme:///
if newPath.isEmpty && _parseInfo.netLocationRange?.isEmpty ?? false {
components.percentEncodedPath = "/"
}
// Standardize scheme:/path to scheme:///path
if components.encodedHost == nil {
components.encodedHost = ""
}
}
let string = components._uncheckedString(original: false)
return _SwiftURL(stringOrEmpty: string, relativeTo: baseURL)?.url
}
#if !NO_FILESYSTEM
var standardizedFileURL: URL? {
guard isFileURL, !fileSystemPath().isEmpty else { return nil }
return URL(filePath: fileSystemPath().standardizingPath, directoryHint: hasDirectoryPath ? .isDirectory : .notDirectory)
}
func resolvingSymlinksInPath() -> URL? {
guard isFileURL, !fileSystemPath().isEmpty else { return nil }
return URL(filePath: fileSystemPath().resolvingSymlinksInPath, directoryHint: hasDirectoryPath ? .isDirectory : .notDirectory)
}
#endif
private static let dataSchemeUTF8 = Array("data".utf8)
var description: String {
var urlString = relativeString
if let scheme, scheme.lowercased().utf8.elementsEqual(Self.dataSchemeUTF8), urlString.utf8.count > 128 {
let prefix = urlString.utf8.prefix(120)
let suffix = urlString.utf8.suffix(8)
urlString = "\(prefix) ... \(suffix)"
}
if let baseURL {
return "\(urlString) -- \(baseURL.description)"
}
return urlString
}
var debugDescription: String {
return description
}
#if FOUNDATION_FRAMEWORK
func bridgeToNSURL() -> NSURL {
return _nsurl
}
private func isFileReferenceURL() -> Bool {
#if NO_FILESYSTEM
return false
#else
return isFileURL && _parseInfo.pathHasFileID
#endif
}
internal func convertingFileReference() -> any _URLProtocol & AnyObject {
#if NO_FILESYSTEM
return self
#else
guard isFileReferenceURL() else { return self }
guard let url = bridgeToNSURL().filePathURL else {
return _SwiftURL(string: "com-apple-unresolvable-file-reference-url:")!
}
return url._url
#endif
}
#else
internal func convertingFileReference() -> _SwiftURL {
return self
}
#endif // FOUNDATION_FRAMEWORK
static func == (lhs: _SwiftURL, rhs: _SwiftURL) -> Bool {
return lhs.relativeString == rhs.relativeString && lhs.baseURL == rhs.baseURL
}
func hash(into hasher: inout Hasher) {
// Historically, the CF/NSURL hash only includes the relative string
hasher.combine(relativeString)
}
/// Convenience for constructing a URL string from components without validation.
private struct URLStringBuilder {
typealias Parser = _SwiftURL.Parser
var scheme: String?
var user: String?
var password: String?
var host: String?
var portString: String?
var path: String
var query: String?
var fragment: String?
var hasAuthority: Bool {
return user != nil || password != nil || host != nil || portString != nil
}
init(parseInfo: URLParseInfo) {
if let scheme = parseInfo.scheme {
self.scheme = String(scheme)
}
if let user = parseInfo.user{
self.user = String(user)
}
if let password = parseInfo.password {
self.password = String(password)
}
if let host = parseInfo.host {
// We don't need to check for IDNA-encoding since only CFURL uses
// the original string, and CFURL does not support INDA-encoding.