-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathadd
executable file
·45 lines (35 loc) · 1.16 KB
/
add
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
#!/usr/bin/env swift
import Foundation
import Dispatch
guard CommandLine.arguments.count == 3 else {
print("Usage: ./add <url> <name>")
exit(1)
}
struct RegistryFile: Codable {
struct Entry: Codable {
let name: String
let url: String
let description: String?
}
public var entries: [Entry]
}
let decoder = JSONDecoder()
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
var letter = CommandLine.arguments[2].uppercased()
letter = String(letter[letter.startIndex])
let url = URL(fileURLWithPath: "Registry/\(letter).json")
let data = try! Data(contentsOf: url)
var file = try! decoder.decode(RegistryFile.self, from: data)
let existing = Set(file.entries.map { $0.name })
guard !existing.contains(CommandLine.arguments[2]) else {
print("Error: \(CommandLine.arguments[2]) already exists in the registry")
exit(1)
}
print("Enter description (empty for none):")
var description = readLine()
if let d = description, d.isEmpty {
description = nil
}
file.entries.append(.init(name: CommandLine.arguments[2], url: CommandLine.arguments[1], description: description))
try! encoder.encode(file).write(to: url)