-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathURL+SwiftLint.swift
More file actions
85 lines (73 loc) · 2.58 KB
/
URL+SwiftLint.swift
File metadata and controls
85 lines (73 loc) · 2.58 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
import Foundation
public extension URL {
static var cwd: URL {
FileManager.default.currentDirectoryPath.url(directoryHint: .isDirectory)
}
var filepath: String {
withUnsafeFileSystemRepresentation { String(cString: $0!) }
}
var isSwiftFile: Bool {
isFile && pathExtension == "swift"
}
var isFile: Bool {
var isDirectoryObjC: ObjCBool = false
if FileManager.default.fileExists(atPath: filepath, isDirectory: &isDirectoryObjC) {
return !isDirectoryObjC.boolValue
}
return false
}
var isDirectory: Bool {
var isDirectoryObjC: ObjCBool = false
if FileManager.default.fileExists(atPath: filepath, isDirectory: &isDirectoryObjC) {
return isDirectoryObjC.boolValue
}
return false
}
/// Path relative to the current working directory.
///
/// > Warning: Use this representation only for displaying file paths to users. It is not
/// suitable for file operations.
var relativeDisplayPath: String {
let path = path.replacing(Self.cwd.path, with: "")
if path.starts(with: "/") {
return String(path.dropFirst())
}
return path
}
var exists: Bool {
isFileURL && FileManager.default.fileExists(atPath: filepath)
}
func relative(to base: URL) -> URL {
guard base.isFileURL, isFileURL else {
return self
}
let baseComponents = base.standardizedFileURL.pathComponents
let selfComponents = standardizedFileURL.pathComponents
var index = 0
while index < baseComponents.count, index < selfComponents.count,
baseComponents[index] == selfComponents[index] {
index += 1
}
var newPath = base
for _ in index..<baseComponents.count {
newPath.deleteLastPathComponent()
}
for component in selfComponents[index...] {
newPath.append(path: component)
}
return newPath
}
}
public extension String {
func url(relativeTo base: URL? = nil, directoryHint: URL.DirectoryHint = .inferFromPath) -> URL {
guard var base else {
return URL(filePath: self, directoryHint: directoryHint).standardizedFileURL
}
if base.isDirectory {
let lastComponent = base.lastPathComponent
base.deleteLastPathComponent()
base.append(path: lastComponent, directoryHint: .isDirectory)
}
return URL(filePath: self, directoryHint: directoryHint, relativeTo: base).standardizedFileURL
}
}