Skip to content

Commit

Permalink
Split R.swift output
Browse files Browse the repository at this point in the history
  • Loading branch information
wiSalah committed Sep 10, 2020
1 parent 269888b commit 30b24b5
Show file tree
Hide file tree
Showing 4 changed files with 107 additions and 25 deletions.
7 changes: 4 additions & 3 deletions Sources/RswiftCore/Generators/StringsStructGenerator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ struct StringsStructGenerator: ExternalOnlyStructGenerator {
functions: [],
structs: structs,
classes: [],
os: []
os: [],
shouldSplit: true
)
}

Expand Down Expand Up @@ -299,10 +300,10 @@ struct StringsStructGenerator: ExternalOnlyStructGenerator {
body: """
guard let preferredLanguages = preferredLanguages else {
let format = \(values.swiftCode(bundle: "hostingBundle"))
return String(format: format, locale: applicationLocale, \(args))
return String(format: format, locale: R.applicationLocale, \(args))
}
guard let (locale, bundle) = localeBundle(tableName: "\(values.tableName)", preferredLanguages: preferredLanguages) else {
guard let (locale, bundle) = R.localeBundle(tableName: "\(values.tableName)", preferredLanguages: preferredLanguages) else {
return "\(values.key)"
}
Expand Down
56 changes: 45 additions & 11 deletions Sources/RswiftCore/RswiftCore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -98,15 +98,15 @@ public struct RswiftCore {
}

// Generate regular R file
let fileContents = generateRegularFileContents(resources: resources, generators: structGenerators)
writeIfChanged(contents: fileContents, toURL: callInformation.outputURL)
let filesContents = generateRegularFilesContents(resources: resources, generators: structGenerators)
writeIfChanged(contents: filesContents, toURL: callInformation.outputURL)

// Generate UITest R file
if let uiTestOutputURL = callInformation.uiTestOutputURL {
let uiTestFileContents = generateUITestFileContents(resources: resources, generators: [
AccessibilityIdentifierStructGenerator(nibs: resources.nibs, storyboards: resources.storyboards)
])
writeIfChanged(contents: uiTestFileContents, toURL: uiTestOutputURL)
writeIfChanged(contents: [uiTestFileContents], toURL: uiTestOutputURL)
}

} catch let error as ResourceParsingError {
Expand All @@ -123,7 +123,7 @@ public struct RswiftCore {
}
}

private func generateRegularFileContents(resources: Resources, generators: [StructGenerator]) -> String {
private func generateRegularFilesContents(resources: Resources, generators: [StructGenerator]) -> [String] {
let aggregatedResult = AggregatedStructGenerator(subgenerators: generators)
.generatedStructs(at: callInformation.accessLevel, prefix: "")

Expand All @@ -143,11 +143,32 @@ public struct RswiftCore {
internalStruct
]

return codeConvertibles
.compactMap { $0?.swiftCode }
.joined(separator: "\n\n")
+ "\n" // Newline at end of file
let mainFileContent = codeConvertibles.compactMap { $0?.swiftCode }.joined(separator: "\n\n") + "\n"
let extensionsStructs = getExtensionsStructs(mainStruct: externalStruct)
let extensionsStructsFilesContents = extensionsStructs.flatMap({
extensionsFilesContents(extensionStruct: $0)
})
return [mainFileContent] + extensionsStructsFilesContents
}

private func getExtensionsStructs(mainStruct: Struct) -> [Struct] {
guard !mainStruct.shouldSplit else { return [mainStruct] }
return mainStruct.structs.flatMap({ getExtensionsStructs(mainStruct: $0) })
}

private func extensionsFilesContents(extensionStruct: Struct) -> [String] {
return extensionStruct.swiftCodeExtensions.map({
[
HeaderPrinter().swiftCode,
ImportPrinter(
modules: callInformation.imports,
extractFrom: [extensionStruct],
exclude: [Module.custom(name: callInformation.productModuleName)]
).swiftCode,
$0
].joined(separator: "\n\n") + "\n"
})
}

private func generateUITestFileContents(resources: Resources, generators: [StructGenerator]) -> String {
let (externalStruct, _) = AggregatedStructGenerator(subgenerators: generators)
Expand Down Expand Up @@ -177,12 +198,25 @@ private func loadPropertyList(name: String, url: URL, callInformation: CallInfor
}
}

private func writeIfChanged(contents: String, toURL outputURL: URL) {
let currentFileContents = try? String(contentsOf: outputURL, encoding: .utf8)
private func writeIfChanged(contents: [String], toURL outputURL: URL) {
/*let currentFileContents = try? String(contentsOf: outputURL, encoding: .utf8)
guard currentFileContents != contents else { return }
do {
try contents.write(to: outputURL, atomically: true, encoding: .utf8)
} catch {
fail(error.localizedDescription)
}
}*/
guard let filename = outputURL.filename else { return }
let fileExtension = outputURL.pathExtension
do {
for content in contents.enumerated() {
let url = outputURL
.deletingLastPathComponent()
.appendingPathComponent("\(filename)+\(content.offset+1)")
.appendingPathExtension(fileExtension)
try content.element.write(to: url, atomically: true, encoding: .utf8)
}
} catch {
fail(error.localizedDescription)
}
}
63 changes: 52 additions & 11 deletions Sources/RswiftCore/SwiftTypes/Struct.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@

import Foundation

private struct Constants {
static let maxPropertiesPerSplit = 300
static let maxFunctionsPerSplit = 70
}

struct Struct: UsedTypesProvider, SwiftCodeConverible {
let availables: [String]
let comments: [String]
Expand All @@ -21,6 +26,7 @@ struct Struct: UsedTypesProvider, SwiftCodeConverible {
var structs: [Struct]
var classes: [Class]
let os: [String]
var shouldSplit: Bool = false

var isEmpty: Bool {
return properties.isEmpty
Expand Down Expand Up @@ -53,17 +59,22 @@ struct Struct: UsedTypesProvider, SwiftCodeConverible {
.map { $0.description }
.joined(separator: "\n")

let varsString = properties
.map { $0.swiftCode }
.sorted()
.map { $0.description }
.joined(separator: "\n")
var varsString: String?
var functionsString: String?

let functionsString = functions
.map { $0.swiftCode }
.sorted()
.map { $0.description }
.joined(separator: "\n\n")
if self is ExternalOnlyStructGenerator == false {
varsString = properties
.map { $0.swiftCode }
.sorted()
.map { $0.description }
.joined(separator: "\n")

functionsString = functions
.map { $0.swiftCode }
.sorted()
.map { $0.description }
.joined(separator: "\n\n")
}

let structsString = structs
.map { $0.swiftCode }
Expand All @@ -80,11 +91,41 @@ struct Struct: UsedTypesProvider, SwiftCodeConverible {
// File private `init`, so that struct can't be initialized from the outside world
let fileprivateInit = "fileprivate init() {}"

let bodyComponents = [typealiasString, varsString, functionsString, structsString, classesString, fileprivateInit].filter { $0 != "" }
let bodyComponents = [typealiasString, varsString ?? "", functionsString ?? "", structsString, classesString, fileprivateInit].filter { $0 != "" }
let bodyString = bodyComponents.joined(separator: "\n\n").indent(with: " ")

return OSPrinter(code: "\(commentsString)\(availablesString)\(accessModifierString)struct \(type)\(implementsString) {\n\(bodyString)\n}", supportedOS: os).swiftCode
}

var swiftCodeExtensions: [String] {
guard self is ExternalOnlyStructGenerator else { return [] }

let availablesString = availables.map { "@available(\($0))\n" }.joined(separator: "")

let propertiesSplits = properties
.chunked(into: Constants.maxPropertiesPerSplit)
.map({ chunk in
chunk.map({ $0.swiftCode })
.sorted()
.map({ $0.description })
.joined(separator: "\n")
.indent(with: " ")
})

let functionsSplits = functions
.chunked(into: Constants.maxFunctionsPerSplit)
.map({ chunk in
chunk.map({ $0.swiftCode })
.sorted()
.map({ $0.description })
.joined(separator: "\n\n")
.indent(with: " ")
})

return (propertiesSplits + functionsSplits).map({
OSPrinter(code: "\(availablesString)extension \(type) {\n\($0)\n}", supportedOS: os).swiftCode
})
}

static var empty: Struct {
return Struct(
Expand Down
6 changes: 6 additions & 0 deletions Sources/RswiftCore/Util/UtilExtensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ extension Array {
subscript (safe index: Int) -> Element? {
return indices ~= index ? self[index] : nil
}

func chunked(into size: Int) -> [[Element]] {
return stride(from: 0, to: count, by: size).map {
Array(self[$0 ..< Swift.min($0 + size, count)])
}
}
}

extension Array where Element: Comparable, Element: Hashable {
Expand Down

0 comments on commit 30b24b5

Please sign in to comment.