|
| 1 | +// |
| 2 | +// RewriteTool.swift |
| 3 | +// |
| 4 | +// |
| 5 | +// Created by Iggy Drougge on 2023-10-16. |
| 6 | +// |
| 7 | + |
| 8 | +import ArgumentParser |
| 9 | +import SwiftSyntax |
| 10 | +import SwiftParser |
| 11 | +import Foundation |
| 12 | + |
| 13 | +@main |
| 14 | +struct RewriteTool: ParsableCommand { |
| 15 | + @Argument var files: [String] = [] |
| 16 | + |
| 17 | + mutating func run() throws { |
| 18 | + for file in files { |
| 19 | + let resource = URL(filePath: file) |
| 20 | + let contents = try String(contentsOf: resource) |
| 21 | + let sources = Parser.parse(source: contents) |
| 22 | + let converted = RewriteImageLiteral().visit(sources) |
| 23 | + try converted.description.write(to: resource, atomically: true, encoding: .utf8) |
| 24 | + } |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +class RewriteImageLiteral: SyntaxRewriter { |
| 29 | + override func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax { |
| 30 | + guard let calledExpression = node.calledExpression.as(DeclReferenceExprSyntax.self) |
| 31 | + else { |
| 32 | + return super.visit(node) |
| 33 | + } |
| 34 | + switch calledExpression.baseName.tokenKind { |
| 35 | + case .identifier("UIImage"): return rewriteUIKitImage(node) |
| 36 | + case .identifier("Image"): return rewriteSwiftUIImage(node) |
| 37 | + case _: return super.visit(node) |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + // Since `UIImage(named:)` returns an optional, and `UIImage(resource:)` does not, we need to remove the trailing question mark. |
| 42 | + override func visit(_ node: OptionalChainingExprSyntax) -> ExprSyntax { |
| 43 | + guard let expression = node.expression.as(FunctionCallExprSyntax.self), |
| 44 | + let calledExpression = expression.calledExpression.as(DeclReferenceExprSyntax.self), |
| 45 | + case .identifier("UIImage") = calledExpression.baseName.tokenKind |
| 46 | + else { |
| 47 | + return super.visit(node) |
| 48 | + } |
| 49 | + return rewriteUIKitImage(expression) |
| 50 | + } |
| 51 | + |
| 52 | + // Since `UIImage(named:)` returns an optional, and `UIImage(resource:)` does not, we need to remove force unwrap exclamation marks. |
| 53 | + override func visit(_ node: ForceUnwrapExprSyntax) -> ExprSyntax { |
| 54 | + guard let expression = node.expression.as(FunctionCallExprSyntax.self), |
| 55 | + let calledExpression = expression.calledExpression.as(DeclReferenceExprSyntax.self), |
| 56 | + case .identifier("UIImage") = calledExpression.baseName.tokenKind |
| 57 | + else { |
| 58 | + return super.visit(node) |
| 59 | + } |
| 60 | + return rewriteUIKitImage(expression) |
| 61 | + } |
| 62 | + |
| 63 | + private func rewriteUIKitImage(_ node: FunctionCallExprSyntax) -> ExprSyntax { |
| 64 | + guard let argument = node.arguments.first, |
| 65 | + argument.label?.text == "named", |
| 66 | + let stringLiteralExpression = argument.expression.as(StringLiteralExprSyntax.self), |
| 67 | + let value = stringLiteralExpression.representedLiteralValue, // String interpolation is not allowed. |
| 68 | + !value.isEmpty |
| 69 | + else { |
| 70 | + return super.visit(node) |
| 71 | + } |
| 72 | + |
| 73 | + var node = node |
| 74 | + |
| 75 | + let resourceName = normaliseLiteralName(value) |
| 76 | + |
| 77 | + let expression = MemberAccessExprSyntax( |
| 78 | + period: .periodToken(), |
| 79 | + declName: DeclReferenceExprSyntax(baseName: .identifier(resourceName)) |
| 80 | + ) |
| 81 | + |
| 82 | + let newArgument = LabeledExprSyntax( |
| 83 | + label: .identifier("resource"), |
| 84 | + colon: .colonToken(trailingTrivia: .space), |
| 85 | + expression: expression |
| 86 | + ) |
| 87 | + |
| 88 | + node.arguments = LabeledExprListSyntax([newArgument]) |
| 89 | + |
| 90 | + return super.visit(node) |
| 91 | + } |
| 92 | + |
| 93 | + private func rewriteSwiftUIImage(_ node: FunctionCallExprSyntax) -> ExprSyntax { |
| 94 | + guard let calledExpression = node.calledExpression.as(DeclReferenceExprSyntax.self), |
| 95 | + case .identifier("Image") = calledExpression.baseName.tokenKind, |
| 96 | + let argument = node.arguments.first, |
| 97 | + argument.label == .none, |
| 98 | + let stringLiteralExpression = argument.expression.as(StringLiteralExprSyntax.self), |
| 99 | + let value = stringLiteralExpression.representedLiteralValue, // String interpolation is not allowed. |
| 100 | + !value.isEmpty |
| 101 | + else { return super.visit(node) } |
| 102 | + |
| 103 | + var node = node |
| 104 | + |
| 105 | + let resourceName = normaliseLiteralName(value) |
| 106 | + |
| 107 | + let expression = MemberAccessExprSyntax( |
| 108 | + period: .periodToken(), |
| 109 | + declName: DeclReferenceExprSyntax(baseName: .identifier(resourceName)) |
| 110 | + ) |
| 111 | + |
| 112 | + let newArgument = LabeledExprSyntax( |
| 113 | + label: .none, |
| 114 | + colon: .none, |
| 115 | + expression: expression |
| 116 | + ) |
| 117 | + |
| 118 | + node.arguments = LabeledExprListSyntax([newArgument]) |
| 119 | + |
| 120 | + return super.visit(node) |
| 121 | + } |
| 122 | +} |
| 123 | + |
| 124 | +private let separators = CharacterSet(charactersIn: " _-") |
| 125 | + |
| 126 | +private func normaliseLiteralName(_ name: String) -> String { |
| 127 | + let (path, name) = extractPathComponents(from: name) |
| 128 | + |
| 129 | + let components = name.components(separatedBy: separators) |
| 130 | + |
| 131 | + guard let head = components.first.map(lowercaseFirst) |
| 132 | + else { return String() } |
| 133 | + |
| 134 | + let tail = components |
| 135 | + .dropFirst() |
| 136 | + .map(uppercaseFirst) |
| 137 | + .joined() |
| 138 | + |
| 139 | + var resourceName = head + tail |
| 140 | + |
| 141 | + if resourceName.hasSuffix("Image") || resourceName.hasSuffix("Color") { |
| 142 | + resourceName.removeLast(5) |
| 143 | + } |
| 144 | + |
| 145 | + if resourceName.first!.isNumber, resourceName.first!.isASCII { |
| 146 | + resourceName = "_" + resourceName |
| 147 | + } |
| 148 | + |
| 149 | + return path + resourceName |
| 150 | +} |
| 151 | + |
| 152 | +private func extractPathComponents(from name: String) -> (path: String, name: String) { |
| 153 | + // If literal contains a slash, it maps to a child type of `ImageResource`: |
| 154 | + // "Images/abc_def" → ".Images.abcDef" |
| 155 | + var pathComponents = name.components(separatedBy: "/") |
| 156 | + let name = pathComponents.last ?? name |
| 157 | + pathComponents = pathComponents.dropLast().map(uppercaseFirst(in:)) |
| 158 | + if !pathComponents.isEmpty { |
| 159 | + pathComponents.append("") // Add empty portion for trailing dot when joining. |
| 160 | + } |
| 161 | + let path = pathComponents.joined(separator: ".") |
| 162 | + |
| 163 | + return (path, name) |
| 164 | +} |
| 165 | + |
| 166 | +private func lowercaseFirst(in string: some StringProtocol) -> any StringProtocol { |
| 167 | + // If first letter is lower-case or non-alphabetic, return string as is. |
| 168 | + guard let first = string.first, |
| 169 | + first.isUppercase |
| 170 | + else { return string } |
| 171 | + // If the entire string is uppercase, just lowercase it all. |
| 172 | + if string.allSatisfy(\.isUppercase) { |
| 173 | + return string.lowercased() |
| 174 | + } |
| 175 | + // Split string where lower case begins. |
| 176 | + let tail = string.drop(while: \.isUppercase) |
| 177 | + // If only initial letter is uppercase, lower case it and return. "Abc" → "abc" |
| 178 | + if string.index(after: string.startIndex) == tail.startIndex { |
| 179 | + return first.lowercased() + string.dropFirst() |
| 180 | + } |
| 181 | + // If tail is not empty, string consists of a sequence of uppercase characters |
| 182 | + // followed by one or several lowercase characters. Lowercase all but the last |
| 183 | + // uppercase character, concatenating it with the lowercase ones. "ABcd" → "aBcd" |
| 184 | + if tail.startIndex != string.endIndex { |
| 185 | + return string[..<tail.startIndex].dropLast().lowercased() + string[..<tail.startIndex].suffix(1) + tail |
| 186 | + } |
| 187 | + // Otherwise, just lowercase initial letter. |
| 188 | + return first.lowercased() + string.dropFirst() |
| 189 | +} |
| 190 | + |
| 191 | +private func uppercaseFirst(in string: some StringProtocol) -> String { |
| 192 | + guard let first = string.first else { return String() } |
| 193 | + return first.uppercased() + string.dropFirst() |
| 194 | +} |
0 commit comments