Skip to content

Commit

Permalink
#535 image generator, changed metadata property name
Browse files Browse the repository at this point in the history
  • Loading branch information
ExNDY committed Dec 19, 2023
1 parent 8107778 commit de2e6ed
Show file tree
Hide file tree
Showing 8 changed files with 186 additions and 45 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import com.squareup.kotlinpoet.PropertySpec.Builder
import com.squareup.kotlinpoet.TypeSpec
import dev.icerock.gradle.metadata.GeneratedObject
import dev.icerock.gradle.metadata.GeneratedObjectModifier
import dev.icerock.gradle.metadata.GeneratedProperties
import dev.icerock.gradle.metadata.GeneratedProperty
import dev.icerock.gradle.metadata.addActual
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
Expand Down Expand Up @@ -39,7 +39,7 @@ abstract class BaseGenerator<T> : MRGenerator.Generator {
// If target object is actual object: skip read files again
//
// Structure: language - key - value
val languageMap: Map<LanguageType, Map<KeyType, T>> = if (targetObject.isActualObject) {
val languageMap: Map<LanguageType, Map<KeyType, T>> = if (targetObject.isActualObject || targetObject.isTargetObject) {
emptyMap()
} else {
loadLanguageMap()
Expand All @@ -55,7 +55,6 @@ abstract class BaseGenerator<T> : MRGenerator.Generator {
beforeGenerateResources(objectBuilder, languagesAllMaps)

val stringsClass = createTypeSpec(
project,
inputMetadata = inputMetadata,
generatedObjects = generatedObjects,
targetObject = targetObject,
Expand All @@ -76,7 +75,6 @@ abstract class BaseGenerator<T> : MRGenerator.Generator {
}

private fun createTypeSpec(
project: Project,
inputMetadata: MutableList<GeneratedObject>,
generatedObjects: MutableList<GeneratedObject>,
targetObject: GeneratedObject,
Expand All @@ -85,20 +83,20 @@ abstract class BaseGenerator<T> : MRGenerator.Generator {
objectBuilder: TypeSpec.Builder,
): TypeSpec? {
if (targetObject.isActual) {
objectBuilder.addModifiers(*getClassModifiers())
objectBuilder.addModifiers(KModifier.ACTUAL)
}

if (targetObject.isActualObject || targetObject.isTargetObject) {
extendObjectBodyAtStart(objectBuilder)
}

val generatedProperties = mutableListOf<GeneratedProperties>()
val generatedProperties = mutableListOf<GeneratedProperty>()

keys.forEach { key ->
val name = key.replace(".", "_")

//Create metadata property
var generatedProperty = GeneratedProperties(
var generatedProperty = GeneratedProperty(
modifier = GeneratedObjectModifier.None,
name = name,
data = JsonObject(
Expand All @@ -111,7 +109,7 @@ abstract class BaseGenerator<T> : MRGenerator.Generator {

val property: Builder = PropertySpec.builder(name, resourceClassName)

if (targetObject.isObject) {
if (targetObject.isActualObject || targetObject.isTargetObject) {
// Add modifier for property and setup metadata
generatedProperty = generatedProperty.copy(
modifier = addActualOverrideModifier(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import dev.icerock.gradle.generator.js.JsColorsGenerator
import dev.icerock.gradle.generator.jvm.JvmColorsGenerator
import dev.icerock.gradle.metadata.GeneratedObject
import dev.icerock.gradle.metadata.GeneratedObjectModifier
import dev.icerock.gradle.metadata.GeneratedProperties
import dev.icerock.gradle.metadata.GeneratedProperty
import dev.icerock.gradle.metadata.GeneratorType
import dev.icerock.gradle.metadata.addActual
import dev.icerock.gradle.metadata.objectsWithProperties
Expand Down Expand Up @@ -44,7 +44,7 @@ abstract class ColorsGenerator(

override val type: GeneratorType = GeneratorType.Colors

open fun beforeGenerate(objectBuilder: TypeSpec.Builder, keys: List<String>) {}
open fun beforeGenerate(objectBuilder: TypeSpec.Builder, keys: List<String>) = Unit

@Suppress("SpreadOperator")
override fun generate(
Expand Down Expand Up @@ -74,7 +74,7 @@ abstract class ColorsGenerator(
// Read target colors
val targetColors: List<ColorNode> = parseColors()
val allColors: List<ColorNode> = (previousColors + targetColors).distinct()
val generatedProperties: MutableList<GeneratedProperties> = mutableListOf()
val generatedProperties: MutableList<GeneratedProperty> = mutableListOf()

beforeGenerate(objectBuilder, allColors.map { it.name })

Expand All @@ -84,13 +84,13 @@ abstract class ColorsGenerator(
val property = PropertySpec.builder(colorNode.name, resourceClassName)

// Create metadata property
var generatedProperty = GeneratedProperties(
var generatedProperty = GeneratedProperty(
modifier = GeneratedObjectModifier.None,
name = colorNode.name,
data = json.encodeToJsonElement(colorNode)
)

if (targetObject.isObject) {
if (targetObject.isActualObject || targetObject.isTargetObject) {
// Setup property modifier and correction metadata info
generatedProperty = generatedProperty.copy(
modifier = addActualOverrideModifier(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,24 @@ import dev.icerock.gradle.generator.common.CommonImagesGenerator
import dev.icerock.gradle.generator.js.JsImagesGenerator
import dev.icerock.gradle.generator.jvm.JvmImagesGenerator
import dev.icerock.gradle.metadata.GeneratedObject
import dev.icerock.gradle.metadata.GeneratedObjectModifier
import dev.icerock.gradle.metadata.GeneratedProperty
import dev.icerock.gradle.metadata.GeneratorType
import dev.icerock.gradle.metadata.addActual
import dev.icerock.gradle.metadata.objectsWithProperties
import dev.icerock.gradle.utils.withoutScale
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.decodeFromJsonElement
import org.gradle.api.Project
import org.gradle.api.file.FileTree
import org.gradle.api.logging.Logger
import java.io.File

abstract class ImagesGenerator(
private val resourcesFileTree: FileTree
private val resourcesFileTree: FileTree,
) : MRGenerator.Generator {

override val inputFiles: Iterable<File>
Expand All @@ -45,62 +54,191 @@ abstract class ImagesGenerator(
resourcesGenerationDir: File,
objectBuilder: TypeSpec.Builder,
): TypeSpec? {
val fileMap: Map<String, List<File>> = inputFiles.groupBy { file ->
// SVGs do not have scale suffixes, so we need to remove the extension first
val key = file
.nameWithoutExtension
.withoutScale
val previousFilesMap: Map<String, List<File>> = getPreviousImageFilesMap(
inputMetadata = inputMetadata,
targetObject = targetObject
)

"$key.${file.extension}"
val imageFileMap: Map<String, List<File>> = if (
targetObject.isActualObject || targetObject.isTargetObject
) {
emptyMap()
} else {
inputFiles.getImageMap()
}

beforeGenerateResources(objectBuilder, fileMap.keys.sorted())

val typeSpec = createTypeSpec(fileMap.keys.sorted(), objectBuilder)
val allImagesMap: Map<String, List<File>> = getAllImagesMap(previousFilesMap, imageFileMap)

beforeGenerateResources(objectBuilder, allImagesMap.keys.sorted())

val typeSpec: TypeSpec? = createTypeSpec(
inputMetadata = inputMetadata,
generatedObjects = generatedObjects,
targetObject = targetObject,
fileNames = allImagesMap.keys.sorted(),
allImagesMap = allImagesMap,
objectBuilder = objectBuilder
)

generateResources(
resourcesGenerationDir = resourcesGenerationDir,
keyFileMap = fileMap.mapKeys { (key, _) ->
keyFileMap = allImagesMap.mapKeys { (key, _) ->
key.substringBeforeLast(".") // Remove file extension from keys
}
)

return typeSpec
}

@Suppress("SpreadOperator")
private fun createTypeSpec(fileNames: List<String>, objectBuilder: TypeSpec.Builder): TypeSpec {
objectBuilder.addModifiers(*getClassModifiers())
private fun createTypeSpec(
inputMetadata: MutableList<GeneratedObject>,
generatedObjects: MutableList<GeneratedObject>,
targetObject: GeneratedObject,
fileNames: List<String>,
allImagesMap: Map<String, List<File>>,
objectBuilder: TypeSpec.Builder,
): TypeSpec? {
if (targetObject.isActual) {
objectBuilder.addModifiers(KModifier.ACTUAL)
}

if (targetObject.isActualObject || targetObject.isTargetObject) {
extendObjectBodyAtStart(objectBuilder)
}

extendObjectBodyAtStart(objectBuilder)
val generatedProperties = mutableListOf<GeneratedProperty>()

fileNames.forEach { fileName ->
fileNames.forEach { fileName: String ->
val updatedFileName = fileName.substringBeforeLast(".")
.replace(".", "_") + ".${fileName.substringAfterLast(".")}"
val propertyName = updatedFileName.substringBeforeLast(".")
val property = PropertySpec.builder(propertyName, resourceClassName)

property.addModifiers(*getPropertyModifiers())
getPropertyInitializer(updatedFileName)?.let { property.initializer(it) }
var generatedProperty = GeneratedProperty(
modifier = GeneratedObjectModifier.None,
name = propertyName,
data = JsonObject(
content = getPropertyMetadata(
fileName = fileName,
allImagesMap = allImagesMap
)
)
)

if (targetObject.isActualObject || targetObject.isTargetObject) {
// Add modifier for property and setup metadata
generatedProperty = generatedProperty.copy(
modifier = addActualOverrideModifier(
propertyName = propertyName,
property = property,
inputMetadata = inputMetadata,
targetObject = targetObject
)
)

getPropertyInitializer(updatedFileName)?.let {
property.initializer(it)
}
}

objectBuilder.addProperty(property.build())
generatedProperties.add(generatedProperty)
}

extendObjectBodyAtEnd(objectBuilder)

return objectBuilder.build()
return if (generatedProperties.isNotEmpty()) {
// Add object in metadata with remove expect realisation
generatedObjects.addActual(
targetObject.copy(properties = generatedProperties)
)

objectBuilder.build()
} else {
null
}
}

private fun getPropertyMetadata(
fileName: String,
allImagesMap: Map<String, List<File>>,
): Map<String, JsonElement> {
//Structure: FileName, Path
val resultMap = mutableMapOf<String, JsonPrimitive>()

allImagesMap[fileName]?.forEach {
resultMap[it.name] = JsonPrimitive(it.path)
}

return resultMap
}

private fun getPreviousImageFilesMap(
inputMetadata: List<GeneratedObject>,
targetObject: GeneratedObject,
): Map<String, List<File>> {
if (!targetObject.isObject || !targetObject.isActual) return emptyMap()

val json = Json
val objectsWithProperties: List<GeneratedObject> = inputMetadata.objectsWithProperties(
targetObject = targetObject
)

val fileImage = mutableListOf<File>()

objectsWithProperties.forEach { generatedObject ->
generatedObject.properties.forEach { property ->
val data = json.decodeFromJsonElement<Map<String, JsonPrimitive>>(property.data)

data.forEach {
fileImage.add(File(it.value.content))
}
}
}

return fileImage.getImageMap()
}

private fun Iterable<File>.getImageMap(): Map<String, List<File>> {
return this.groupBy { file ->
// SVGs do not have scale suffixes, so we need to remove the extension first
val key = file
.nameWithoutExtension
.withoutScale

"$key.${file.extension}"
}
}

private fun getAllImagesMap(
previousFilesMap: Map<String, List<File>>,
imageFileMap: Map<String, List<File>>,
): Map<String, List<File>> {
val resultMap = mutableMapOf<String, List<File>>()

previousFilesMap.forEach { map ->
resultMap[map.key] = map.value
}

imageFileMap.forEach { map ->
resultMap[map.key] = map.value
}

return resultMap
}

override fun getImports(): List<ClassName> = emptyList()

protected open fun beforeGenerateResources(
objectBuilder: TypeSpec.Builder,
keys: List<String>
keys: List<String>,
) {
}

protected open fun generateResources(
resourcesGenerationDir: File,
keyFileMap: Map<String, List<File>>
keyFileMap: Map<String, List<File>>,
) {
}

Expand All @@ -112,7 +250,7 @@ abstract class ImagesGenerator(

class Feature(
private val settings: MRGenerator.Settings,
private val logger: Logger
private val logger: Logger,
) : ResourceGeneratorFeature<ImagesGenerator> {
override fun createCommonGenerator(): ImagesGenerator = CommonImagesGenerator(
ownInputFileTree = settings.ownResourcesFileTree,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ abstract class StringsGenerator(
targetObject: GeneratedObject,
): Map<LanguageType, Map<KeyType, String>> {
if (!targetObject.isObject || !targetObject.isActual) return emptyMap()

val json = Json
val objectsWithProperties: List<GeneratedObject> = inputMetadata.objectsWithProperties(targetObject)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ class CommonMRGenerator(
processMRClass(mrClassSpec)

//Create file only if generated expect objects has expect MR object
if (generatedExpectObjects.isNotEmpty()){
if (generatedExpectObjects.isNotEmpty()) {
val mrClass: TypeSpec = mrClassSpec.build()
fileSpec.addType(mrClass)

Expand Down Expand Up @@ -220,16 +220,19 @@ class CommonMRGenerator(
val generatorType: GeneratorType =
if (it.path.matches(StringsGenerator.STRINGS_REGEX)) {
GeneratorType.Strings
} else if (it.path.matches(PluralsGenerator.PLURALS_REGEX)) {
}
else if (it.path.matches(PluralsGenerator.PLURALS_REGEX)) {
GeneratorType.Plurals
} else if (it.path.matches(ColorsGenerator.COLORS_REGEX)) {
GeneratorType.Colors
} else return@forEach
}
else if (it.path.matches(ColorsGenerator.COLORS_REGEX)) {
GeneratorType.Colors
}
else if (it.parentFile.name == "images") {
GeneratorType.Images
} else return@forEach

//TODO: Implement with generator
// else if (it.parentFile.name == "images") {
// GeneratorType.Images
// } else if (it.parentFile.name == "files") {
// else if (it.parentFile.name == "files") {
// GeneratorType.Files
// } else if (it.parentFile.name == "assets") {
// GeneratorType.Assets
Expand Down
Loading

0 comments on commit de2e6ed

Please sign in to comment.