Skip to content

Commit 4469763

Browse files
feat(file-tools): add batch rename rules and planner
1 parent ea9259b commit 4469763

9 files changed

Lines changed: 1813 additions & 27 deletions

File tree

‎CorePackage/Sources/FileMintCore/BatchRenamePlanner.swift‎

Lines changed: 334 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 308 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,308 @@
1+
import CoreFoundation
2+
import Foundation
3+
4+
public enum BatchRenameRule: Equatable, Sendable {
5+
case replace(search: String, replacement: String)
6+
case prepend(String)
7+
case append(String)
8+
case number(BatchRenameNumbering)
9+
case uppercase
10+
case lowercase
11+
12+
public static func == (lhs: Self, rhs: Self) -> Bool {
13+
switch (lhs, rhs) {
14+
case let (.replace(leftSearch, leftReplacement), .replace(rightSearch, rightReplacement)):
15+
leftSearch.utf8.elementsEqual(rightSearch.utf8)
16+
&& leftReplacement.utf8.elementsEqual(rightReplacement.utf8)
17+
case let (.prepend(left), .prepend(right)), let (.append(left), .append(right)):
18+
left.utf8.elementsEqual(right.utf8)
19+
case let (.number(left), .number(right)):
20+
left == right
21+
case (.uppercase, .uppercase), (.lowercase, .lowercase):
22+
true
23+
default:
24+
false
25+
}
26+
}
27+
}
28+
29+
public struct BatchRenameNumbering: Equatable, Sendable {
30+
public enum Position: Equatable, Sendable {
31+
case before
32+
case after
33+
}
34+
35+
public enum Body: Equatable, Sendable {
36+
case current
37+
case unified(String)
38+
39+
public static func == (lhs: Self, rhs: Self) -> Bool {
40+
switch (lhs, rhs) {
41+
case (.current, .current): true
42+
case let (.unified(left), .unified(right)): left.utf8.elementsEqual(right.utf8)
43+
default: false
44+
}
45+
}
46+
}
47+
48+
public var start: Int64
49+
public var step: Int64
50+
public var width: Int
51+
public var separator: String
52+
public var position: Position
53+
public var body: Body
54+
55+
public init(
56+
start: Int64 = 1,
57+
step: Int64 = 1,
58+
width: Int = 3,
59+
separator: String = "_",
60+
position: Position = .after,
61+
body: Body = .current
62+
) {
63+
self.start = start
64+
self.step = step
65+
self.width = width
66+
self.separator = separator
67+
self.position = position
68+
self.body = body
69+
}
70+
71+
public static func == (lhs: Self, rhs: Self) -> Bool {
72+
lhs.start == rhs.start && lhs.step == rhs.step && lhs.width == rhs.width
73+
&& lhs.separator.utf8.elementsEqual(rhs.separator.utf8)
74+
&& lhs.position == rhs.position && lhs.body == rhs.body
75+
}
76+
}
77+
78+
public enum BatchRenameRuleError: Error, Equatable, Sendable {
79+
case invalidRowCount
80+
case invalidSortedOrdinal
81+
case tooManyRules
82+
case emptySearch(ruleIndex: Int)
83+
case literalTooLong(ruleIndex: Int)
84+
case invalidNumbering(ruleIndex: Int)
85+
case numberingOverflow(ruleIndex: Int)
86+
/// A nil index identifies an oversized input, before applying any rule.
87+
case workingBodyTooLong(ruleIndex: Int?)
88+
}
89+
90+
/// Pure body transformations. The name policy validates the final component;
91+
/// temporary empty bodies and filename-invalid characters are not repaired here.
92+
public enum BatchRenameRuleEngine {
93+
public static let maximumRuleCount = 32
94+
public static let maximumLiteralUTF8Bytes = 1_024
95+
public static let maximumWorkingBodyUTF8Bytes = 4_096
96+
public static let maximumRowCount = 1_000
97+
98+
/// Checks every parameter and the last row's numbering, even when an earlier
99+
/// row would be unchanged. The planner owns the two-item selection minimum.
100+
public static func validate(_ rules: [BatchRenameRule], rowCount: Int) throws {
101+
guard (1...maximumRowCount).contains(rowCount) else {
102+
throw BatchRenameRuleError.invalidRowCount
103+
}
104+
guard rules.count <= maximumRuleCount else {
105+
throw BatchRenameRuleError.tooManyRules
106+
}
107+
108+
for (index, rule) in rules.enumerated() {
109+
switch rule {
110+
case let .replace(search, replacement):
111+
guard !search.isEmpty else {
112+
throw BatchRenameRuleError.emptySearch(ruleIndex: index)
113+
}
114+
try validateLiteral(search, ruleIndex: index)
115+
try validateLiteral(replacement, ruleIndex: index)
116+
case let .prepend(text), let .append(text):
117+
try validateLiteral(text, ruleIndex: index)
118+
case let .number(numbering):
119+
guard numbering.start >= 0, numbering.step >= 1,
120+
(1...20).contains(numbering.width) else {
121+
throw BatchRenameRuleError.invalidNumbering(ruleIndex: index)
122+
}
123+
try validateLiteral(numbering.separator, ruleIndex: index)
124+
if case let .unified(body) = numbering.body {
125+
try validateLiteral(body, ruleIndex: index)
126+
}
127+
_ = try numberValue(numbering, ordinal: rowCount - 1, ruleIndex: index)
128+
case .uppercase, .lowercase:
129+
break
130+
}
131+
}
132+
}
133+
134+
public static func apply(
135+
_ rules: [BatchRenameRule],
136+
to originalBody: String,
137+
sortedOrdinal: Int,
138+
rowCount: Int
139+
) throws -> String {
140+
try validate(rules, rowCount: rowCount)
141+
guard (0..<rowCount).contains(sortedOrdinal) else {
142+
throw BatchRenameRuleError.invalidSortedOrdinal
143+
}
144+
try validateWorkingSize(originalBody.utf8.count, ruleIndex: nil)
145+
146+
var body = originalBody
147+
for (index, rule) in rules.enumerated() {
148+
switch rule {
149+
case let .replace(search, replacement):
150+
body = try replacing(search, with: replacement, in: body, ruleIndex: index)
151+
case let .prepend(text):
152+
try validateWorkingSize(text.utf8.count + body.utf8.count, ruleIndex: index)
153+
body = text + body
154+
case let .append(text):
155+
try validateWorkingSize(body.utf8.count + text.utf8.count, ruleIndex: index)
156+
body += text
157+
case let .number(numbering):
158+
body = try numbered(body, with: numbering, ordinal: sortedOrdinal, ruleIndex: index)
159+
case .uppercase:
160+
body = try changingCase(body, uppercase: true, ruleIndex: index)
161+
case .lowercase:
162+
body = try changingCase(body, uppercase: false, ruleIndex: index)
163+
}
164+
}
165+
return body
166+
}
167+
168+
private static func validateLiteral(_ literal: String, ruleIndex: Int) throws {
169+
guard literal.utf8.count <= maximumLiteralUTF8Bytes else {
170+
throw BatchRenameRuleError.literalTooLong(ruleIndex: ruleIndex)
171+
}
172+
}
173+
174+
private static func validateWorkingSize(_ bytes: Int, ruleIndex: Int?) throws {
175+
guard bytes <= maximumWorkingBodyUTF8Bytes else {
176+
throw BatchRenameRuleError.workingBodyTooLong(ruleIndex: ruleIndex)
177+
}
178+
}
179+
180+
private static func numberValue(
181+
_ numbering: BatchRenameNumbering,
182+
ordinal: Int,
183+
ruleIndex: Int
184+
) throws -> Int64 {
185+
let (offset, multiplyOverflow) = Int64(ordinal).multipliedReportingOverflow(by: numbering.step)
186+
let (value, addOverflow) = numbering.start.addingReportingOverflow(offset)
187+
guard !multiplyOverflow, !addOverflow else {
188+
throw BatchRenameRuleError.numberingOverflow(ruleIndex: ruleIndex)
189+
}
190+
return value
191+
}
192+
193+
private static func numbered(
194+
_ currentBody: String,
195+
with numbering: BatchRenameNumbering,
196+
ordinal: Int,
197+
ruleIndex: Int
198+
) throws -> String {
199+
let value = try numberValue(numbering, ordinal: ordinal, ruleIndex: ruleIndex)
200+
let body: String
201+
switch numbering.body {
202+
case .current: body = currentBody
203+
case let .unified(text): body = text
204+
}
205+
206+
var digitCount = 1
207+
var remaining = value
208+
while remaining >= 10 {
209+
remaining /= 10
210+
digitCount += 1
211+
}
212+
let paddedCount = max(digitCount, numbering.width)
213+
let size = body.isEmpty ? paddedCount : body.utf8.count + numbering.separator.utf8.count + paddedCount
214+
try validateWorkingSize(size, ruleIndex: ruleIndex)
215+
216+
let digits = String(repeating: "0", count: paddedCount - digitCount) + String(value)
217+
guard !body.isEmpty else { return digits }
218+
switch numbering.position {
219+
case .before: return digits + numbering.separator + body
220+
case .after: return body + numbering.separator + digits
221+
}
222+
}
223+
224+
private static func replacing(
225+
_ search: String,
226+
with replacement: String,
227+
in body: String,
228+
ruleIndex: Int
229+
) throws -> String {
230+
// UTF-8 exact matching is scalar-exact for valid Swift strings, including
231+
// matches inside a grapheme cluster. It never equates NFC and NFD text.
232+
let source = Array(body.utf8)
233+
let pattern = Array(search.utf8)
234+
guard pattern.count <= source.count else { return body }
235+
let inserted = Array(replacement.utf8)
236+
var prefix = [Int](repeating: 0, count: pattern.count)
237+
var matched = 0
238+
for index in 1..<pattern.count {
239+
while matched > 0, pattern[index] != pattern[matched] {
240+
matched = prefix[matched - 1]
241+
}
242+
if pattern[index] == pattern[matched] { matched += 1 }
243+
prefix[index] = matched
244+
}
245+
246+
var starts: [Int] = []
247+
var size = source.count
248+
matched = 0
249+
for index in source.indices {
250+
while matched > 0, source[index] != pattern[matched] {
251+
matched = prefix[matched - 1]
252+
}
253+
if source[index] == pattern[matched] { matched += 1 }
254+
if matched == pattern.count {
255+
starts.append(index + 1 - pattern.count)
256+
size += inserted.count - pattern.count
257+
// Every match has the same size delta. Once an expanding rule
258+
// exceeds the budget, later matches cannot make it fit again.
259+
try validateWorkingSize(size, ruleIndex: ruleIndex)
260+
matched = 0 // Consume the match; overlaps are never reused.
261+
}
262+
}
263+
guard !starts.isEmpty else { return body }
264+
265+
var result: [UInt8] = []
266+
result.reserveCapacity(size)
267+
var cursor = 0
268+
for start in starts {
269+
result.append(contentsOf: source[cursor..<start])
270+
result.append(contentsOf: inserted)
271+
cursor = start + pattern.count
272+
}
273+
result.append(contentsOf: source[cursor...])
274+
return String(decoding: result, as: UTF8.self)
275+
}
276+
277+
private static func changingCase(_ body: String, uppercase: Bool, ruleIndex: Int) throws -> String {
278+
// Budget the default Unicode mapping without constructing the combined
279+
// output. Its only language-independent contextual mapping is Final_Sigma;
280+
// final/non-final sigma have the same UTF-8 length. Locale-specific
281+
// Turkish/Azeri/Lithuanian tailoring is intentionally not used.
282+
// See Unicode SpecialCasing.txt, Language-Insensitive Mappings.
283+
var size = 0
284+
for scalar in body.unicodeScalars {
285+
let mapped = defaultCaseMapping(String(scalar), uppercase: uppercase)
286+
size += mapped.utf8.count
287+
try validateWorkingSize(size, ruleIndex: ruleIndex)
288+
}
289+
// Map the whole string after budgeting to retain word-final sigma.
290+
let result = defaultCaseMapping(body, uppercase: uppercase)
291+
try validateWorkingSize(result.utf8.count, ruleIndex: ruleIndex)
292+
return result
293+
}
294+
295+
private static func defaultCaseMapping(_ text: String, uppercase: Bool) -> String {
296+
let mutable = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, text as CFString)!
297+
// CoreFoundation's nil locale selects no language tailoring; it does
298+
// not resolve the user's locale. Its lowercase path still applies the
299+
// contextual Final_Sigma rule. Keep budgeting on this same API path.
300+
// Apple CFString.c: _CFCanUseLocale, CFStringUppercase/CFStringLowercase.
301+
if uppercase {
302+
CFStringUppercase(mutable, nil)
303+
} else {
304+
CFStringLowercase(mutable, nil)
305+
}
306+
return mutable as String
307+
}
308+
}

0 commit comments

Comments
 (0)