-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate.swift
75 lines (69 loc) · 3.34 KB
/
generate.swift
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
// usage: swift generate.swift pokedex
// splits the json found in the folder into subfolders with each entry on the json
import Foundation
extension URL {
var contentsOfDirectory: [String] {
(try? FileManager.default.contentsOfDirectory(atPath: self.absoluteString)) ?? []
}
var subURLS: [URL] {
self.contentsOfDirectory.map({
self.appendingPathComponent($0)
})
}
}
let ROOT = URL(string: FileManager.default.currentDirectoryPath)!
CommandLine.arguments.forEach({ folderName in
let folder = ROOT.appendingPathComponent(folderName)
folder.contentsOfDirectory.forEach { sub in
let subfolder = folder.appendingPathComponent(sub)
let filenames = subfolder.contentsOfDirectory.filter({ !$0.starts(with: ".") })
filenames.forEach { filename in
guard let string = try? String(contentsOfFile: subfolder.appendingPathComponent(filename).absoluteString, encoding: .utf8),
let data = string.data(using: .utf8, allowLossyConversion: true),
let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [NSDictionary]
else { return }
let basename = (filename as NSString).deletingPathExtension
let entryFolder = subfolder.appendingPathComponent(basename)
json.forEach { entry in
guard let id = entry["id"] else { return }
let entryFile = entryFolder.appendingPathComponent("\(String(describing: id)).json")
do {
try FileManager.default.createDirectory(atPath: entryFolder.absoluteString, withIntermediateDirectories: true)
try JSONSerialization
.data(withJSONObject: entry, options: [.prettyPrinted, .withoutEscapingSlashes])
.write(to: URL(fileURLWithPath: entryFile.absoluteString))
} catch {
print(error)
}
}
let schema: NSMutableDictionary = NSMutableDictionary(dictionary: json.first ?? [:])
let schemaFile = entryFolder.appendingPathComponent(".schema.json")
schema.allKeys.forEach({ key in
guard let key = key as? String else { return }
let value = schema[key]
if ((value as? Bool) != nil) {
schema.setValue("boolean", forKey: key)
} else if ((value as? Int) != nil) {
schema.setValue("integer", forKey: key)
} else if ((value as? Double) != nil) {
schema.setValue("double", forKey: key)
} else if ((value as? String) != nil) {
schema.setValue("string", forKey: key)
} else if ((value as? [Any]) != nil) {
schema.setValue("array", forKey: key)
} else if ((value as? [String:Any]) != nil) {
schema.setValue("dictionary", forKey: key)
} else {
schema.setValue("unknown", forKey: key)
}
})
do {
try JSONSerialization
.data(withJSONObject: schema, options: .prettyPrinted)
.write(to: URL(fileURLWithPath: schemaFile.absoluteString))
} catch {
print(error)
}
}
}
})