-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate.swift
66 lines (55 loc) · 2.1 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
import Foundation
// Run using `swift generate.swift` for JSON output, or `swift generate.swift -t` for text output.
struct LanguageInfo: Codable {
let name: String
let symbol: String
}
let isTextMode = CommandLine.arguments.last == "-t"
let outputLocale = NSLocale(localeIdentifier: "en_US")
// All lang infos keyed by display name, so we can sort output by display name
var langsByDisplayName: [String: LanguageInfo] = [:]
for localeCode in Locale.availableIdentifiers {
if let displayName = outputLocale.displayName(forKey: NSLocale.Key.identifier, value: localeCode) {
let langInfo = LanguageInfo(name: displayName, symbol: localeCode.replacingOccurrences(of: "_", with: "-"))
langsByDisplayName[displayName] = langInfo
}
}
// `availableIdentifiers` don't include all language codes (for example `ie` for Interlingue is missing)
// `isoLanguageCodes` includes the missing ones.
for langCode in Locale.isoLanguageCodes {
if let displayName = outputLocale.displayName(forKey: NSLocale.Key.languageCode, value: langCode) {
let langInfo = LanguageInfo(name: displayName, symbol: langCode)
langsByDisplayName[displayName] = langInfo
}
}
// Sort lang infos for output
var allLanguageInfos: [LanguageInfo] = []
for name in langsByDisplayName.keys.sorted() {
if let langInfo = langsByDisplayName[name] {
allLanguageInfos.append(langInfo)
}
}
if isTextMode {
// Output Text
for langInfo in allLanguageInfos {
puts("\(langInfo.name) (\(langInfo.symbol))")
}
} else {
// Output JSON
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
do {
let encodedData = try encoder.encode(allLanguageInfos)
if let prettyJson = String(data: encodedData, encoding: .utf8) {
print(prettyJson)
}
} catch {
print("Error during JSON encoding: \(error.localizedDescription)")
exit(-1)
}
}
// Ensure we have no duplicate symbols
let allSymbols = Set(allLanguageInfos.map { $0.symbol })
if (allLanguageInfos.count != allSymbols.count) {
print("WARNING: Symbols are not unique.")
}