-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPackageJSONParser.swift
More file actions
113 lines (93 loc) · 2.84 KB
/
PackageJSONParser.swift
File metadata and controls
113 lines (93 loc) · 2.84 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
import Foundation
import SwiftyJSON
public enum PackageJSONError: Error {
case noPodspec
case scriptEntryNotFound
case fileEntryNotFound
case jsonStringGenerationFailed
}
public struct PackageJSONParser: CustomDebugStringConvertible {
private let package: PackageJSON
private let json: JSON
private let jsonURL: URL
public var jsonString: String
public var npmName: String {
package.name
}
public var version: String {
package.version
}
public var files: [String] {
package.files
}
public var podspec: String = ""
public var iosSrcDirectory: String {
package.capacitor.ios.src
}
public var pluginDirectories: [String] {
var plugins: [String] = []
for file in package.files {
if file.hasPrefix(iosSrcDirectory) {
plugins.append(file)
}
}
return plugins
}
public init(with url: URL) throws {
jsonURL = url
let data = try Data(contentsOf: url)
json = try JSON(data: data)
jsonString = try String(contentsOf: url, encoding: .utf8)
package = try JSONDecoder().decode(PackageJSON.self, from: data)
podspec = try findPodspec()
}
public mutating func changeScript(named: String, to runString: String) throws(PackageJSONError) {
if json["scripts"][named] != JSON.null {
jsonString = jsonString.replacingOccurrences(of: json["scripts"][named].stringValue, with: runString)
} else {
throw .scriptEntryNotFound
}
}
public mutating func setFiles() {
var replacements: [String] = ["ios/Plugin", "ios/Plugin/"]
var newFiles: String = """
"Package.swift",
"""
if !files.contains(where: { $0 == "ios/"}) {
newFiles = """
"ios/Sources",
"ios/Tests",
\(newFiles)
"""
} else {
replacements.append("ios/")
newFiles = """
"ios/",
\(newFiles)
"""
}
replacements.forEach {replacement in
jsonString = jsonString.replacingOccurrences(of: "\"\(replacement)\",", with: newFiles)
}
}
public func writePackageJSON() throws {
try jsonString.write(to: jsonURL, atomically: true, encoding: .utf8)
}
public var debugDescription: String {
"""
NPM Name: \(npmName)
Version: \(version)
Podspec: \(podspec)
iOS Sources: \(iosSrcDirectory)
Plugin Directories: \(pluginDirectories)
"""
}
private func findPodspec() throws(PackageJSONError) -> String {
for file in package.files {
if file.hasSuffix("podspec") {
return file
}
}
throw .noPodspec
}
}