-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_examples.swift
More file actions
executable file
·202 lines (178 loc) · 8.06 KB
/
generate_examples.swift
File metadata and controls
executable file
·202 lines (178 loc) · 8.06 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#!/usr/bin/env swift
import Foundation
struct ParsedExample {
let title: String
let subtitle: String
let description: String
let typeCase: String
let dateString: String
let structName: String
let isFeatured: Bool
let success: Bool
}
func firstMatch(in text: String, pattern: String) -> String? {
guard let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) else {
return nil
}
let range = NSRange(text.startIndex..<text.endIndex, in: text)
guard let match = regex.firstMatch(in: text, options: [], range: range), match.numberOfRanges > 1,
let range = Range(match.range(at: 1), in: text) else {
return nil
}
let value = String(text[range]).trimmingCharacters(in: .whitespacesAndNewlines)
let slashTrimmed = value.trimmingCharacters(in: CharacterSet(charactersIn: "/").union(.whitespacesAndNewlines))
return slashTrimmed.isEmpty ? nil : value
}
func normalizedTitle(from raw: String?, structName: String) -> (title: String, number: Int?) {
let candidates = [raw, structName]
for candidate in candidates.compactMap({ $0 }) {
let trimmed = candidate.trimmingCharacters(in: .whitespacesAndNewlines)
if let match = firstMatch(in: trimmed, pattern: "Example\\s*0*([0-9]+)") {
if let number = Int(match) {
let title = String(format: "Example %03d", number)
return (title, number)
}
}
}
let fallback = raw?.trimmingCharacters(in: .whitespacesAndNewlines) ?? structName
return (fallback, nil)
}
func normalizedDate(_ raw: String?) -> String {
guard let raw else { return "01/01/2024" }
let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
let parts = trimmed.split(separator: "/")
guard parts.count == 3 else { return trimmed }
let yearPart = parts[2]
let fourDigitYear: String
if yearPart.count == 2, let value = Int(yearPart) {
fourDigitYear = String(2000 + value)
} else {
fourDigitYear = String(yearPart)
}
return "\(parts[0])/\(parts[1])/\(fourDigitYear)"
}
func typeCase(from raw: String?) -> String {
let trimmed = (raw ?? "Window").trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
switch trimmed {
case "volume", "volume content":
return ".VOLUME"
case "space", "immersive space", "mixed immersive space":
return ".SPACE"
case "space full", "full immersive space", "immersive full":
return ".SPACE_FULL"
case "window alt", "window_alt", "plain window content", "plain window":
return ".WINDOW_ALT"
case "window", "window content":
fallthrough
default:
return ".WINDOW"
}
}
func boolFlag(from raw: String?, default defaultValue: Bool) -> Bool {
guard let raw else { return defaultValue }
let value = raw.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
return value == "true" || value == "yes" || value == "1"
}
func swiftStringLiteral(_ value: String) -> String {
let escaped = value
.replacingOccurrences(of: "\\", with: "\\\\")
.replacingOccurrences(of: "\"", with: "\\\"")
.replacingOccurrences(of: "\n", with: "\\n")
return "\"\(escaped)\""
}
func parseExample(from content: String, fileName: String) -> ParsedExample? {
guard let structName = firstMatch(in: content, pattern: "struct\\s+([A-Za-z0-9_]+)\\s*:\\s*View") else { return nil }
let rawTitle = firstMatch(in: content, pattern: "//\\s*Title:\\s*(.+)")
let subtitle = firstMatch(in: content, pattern: "//\\s*Subtitle:\\s*(.+)") ?? "Untitled"
let description = firstMatch(in: content, pattern: "//\\s*Description:\\s*(.+)") ?? ""
let rawType = firstMatch(in: content, pattern: "//\\s*Type:\\s*(.+)")
let rawDate = firstMatch(in: content, pattern: "Created by .+ on ([0-9/]+)")
let featuredRaw = firstMatch(in: content, pattern: "//\\s*Featured:\\s*(.+)")
let successRaw = firstMatch(in: content, pattern: "//\\s*Success:\\s*(.+)")
let normalized = normalizedTitle(from: rawTitle, structName: structName)
let dateString = normalizedDate(rawDate)
return ParsedExample(
title: normalized.title,
subtitle: subtitle,
description: description,
typeCase: typeCase(from: rawType),
dateString: dateString,
structName: structName,
isFeatured: boolFlag(from: featuredRaw, default: false),
success: boolFlag(from: successRaw, default: true)
)
}
func render(entries: [ParsedExample]) -> String {
var lines: [String] = []
lines.append("// This file is auto-generated. Do not edit by hand.\n// Generated by Tools/generate_examples.swift\n")
lines.append("import SwiftUI\n")
lines.append("struct ExampleRegistry {\n static let allExamples: [Example] = [\n")
for (index, entry) in entries.enumerated() {
let prefix = " "
let descriptionLiteral = swiftStringLiteral(entry.description)
let subtitleLiteral = swiftStringLiteral(entry.subtitle)
lines.append("\(prefix)Example(\n" +
"\(prefix) title: \(swiftStringLiteral(entry.title)),\n" +
"\(prefix) type: \(entry.typeCase),\n" +
"\(prefix) date: Date(\"\(entry.dateString)\"),\n" +
"\(prefix) isFeatured: \(entry.isFeatured),\n" +
"\(prefix) subtitle: \(subtitleLiteral),\n" +
"\(prefix) description: \(descriptionLiteral),\n" +
"\(prefix) success: \(entry.success),\n" +
"\(prefix) makeView: { AnyView(\(entry.structName)()) }\n" +
"\(prefix))\(index == entries.count - 1 ? "" : ",")\n")
}
lines.append(" ]\n\n static let examplesByTitle: [String: Example] = {\n Dictionary(uniqueKeysWithValues: allExamples.map { ($0.title, $0) })\n }()\n}\n")
return lines.joined()
}
struct Arguments {
var sourcePath = "Step Into Example Code/Examples"
var outputPath = "Step Into Example Code/App/Generated/ExampleRegistry.swift"
}
func parseArguments() -> Arguments {
var arguments = Arguments()
var iterator = CommandLine.arguments.dropFirst().makeIterator()
while let arg = iterator.next() {
switch arg {
case "--src", "--source":
if let value = iterator.next() { arguments.sourcePath = value }
case "--out", "--output":
if let value = iterator.next() { arguments.outputPath = value }
default:
continue
}
}
return arguments
}
let args = parseArguments()
let fm = FileManager.default
let srcURL = URL(fileURLWithPath: args.sourcePath)
let outURL = URL(fileURLWithPath: args.outputPath)
let files = (try? fm.contentsOfDirectory(at: srcURL, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles])) ?? []
let swiftFiles = files.filter { $0.pathExtension == "swift" }.sorted { $0.lastPathComponent < $1.lastPathComponent }
var parsedEntries: [ParsedExample] = []
for file in swiftFiles {
guard let content = try? String(contentsOf: file, encoding: .utf8) else { continue }
if let entry = parseExample(from: content, fileName: file.lastPathComponent) {
parsedEntries.append(entry)
} else {
fputs("⚠️ Skipping \(file.lastPathComponent) (could not parse)\n", stderr)
}
}
// Sort by example number when possible
parsedEntries.sort { lhs, rhs in
let leftMatch = firstMatch(in: lhs.title, pattern: "Example\\s*0*([0-9]+)")
let rightMatch = firstMatch(in: rhs.title, pattern: "Example\\s*0*([0-9]+)")
if let l = leftMatch.flatMap(Int.init), let r = rightMatch.flatMap(Int.init) {
return l < r
}
return lhs.title < rhs.title
}
let output = render(entries: parsedEntries)
try fm.createDirectory(at: outURL.deletingLastPathComponent(), withIntermediateDirectories: true)
try output.write(to: outURL, atomically: true, encoding: .utf8)
if swiftFiles.isEmpty {
fputs("❌ No .swift files found at \(srcURL.path)\n", stderr)
exit(1)
}
print("Scanned \(swiftFiles.count) files; generated \(parsedEntries.count) examples -> \(args.outputPath)")