Skip to content

Commit

Permalink
Read manifest for app name and some git infos for upload
Browse files Browse the repository at this point in the history
  • Loading branch information
tabere-ubique committed Sep 6, 2024
1 parent 6404a12 commit d6e516e
Show file tree
Hide file tree
Showing 11 changed files with 161 additions and 36 deletions.
2 changes: 1 addition & 1 deletion appexample/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,5 @@ dependencies {
linthPlugin {
uploadKey = "f1c8846e-0c3a-44ac-b56a-53feb91d6383"

// proxy = "192.168.8.167:8888"
//proxy = "192.168.102.147:8888"
}
3 changes: 3 additions & 0 deletions appexample/src/dev/res/values/strings.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<resources>
<string name="app_name">Dev App Example</string>
</resources>
25 changes: 3 additions & 22 deletions plugin-build/plugin/src/main/java/ch/ubique/linth/IconTask.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ package ch.ubique.linth

import ch.ubique.linth.common.IconUtils
import ch.ubique.linth.common.getMergedManifestFile
import com.android.build.gradle.BaseExtension
import ch.ubique.linth.common.getResDirs
import org.gradle.api.DefaultTask
import org.gradle.api.artifacts.ProjectDependency
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.Optional
Expand Down Expand Up @@ -41,7 +40,7 @@ abstract class IconTask : DefaultTask() {
)

val generatedResDir = File("$buildDir/generated/res/launcher-icon/")

// get banner label
val defaultLabelEnabled = false//android.defaultConfig.launcherIconLabelEnabled
val flavorLabelEnabled = true//flavor.launcherIconLabelEnabled
Expand All @@ -53,25 +52,7 @@ abstract class IconTask : DefaultTask() {
}

val manifestFile = project.getMergedManifestFile(flavor, buildType)

val androidModules: List<BaseExtension> = project.configurations
.asSequence()
.flatMap { it.dependencies }
.filterIsInstance<ProjectDependency>()
.map { it.dependencyProject }
.distinct()
.mapNotNull { it.extensions.findByType(BaseExtension::class.java) }
.toList()

val resDirs: List<File> = androidModules
.flatMap {
listOfNotNull(
it.sourceSets.findByName(flavor),
it.sourceSets.findByName("main")
)
}
.flatMap { it.res.srcDirs }
.filter { !it.path.contains("generated") }
val resDirs = project.getResDirs(flavor)

val allIcons = IconUtils.findIcons(resDirs, manifestFile)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ abstract class InjectMetaIntoManifestTask : DefaultTask() {
init {
description = "Inject Metadata into Manifest"
group = "linth"

buildId = project.findProperty("buildid")?.toString() ?: project.findProperty("ubappid")?.toString() ?: "localbuild"
buildNumber = project.findProperty("buildnumber")?.toString() ?: "0"
buildBranch = project.findProperty("branch")?.toString() ?: GitUtils.obtainBranch()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,13 @@ abstract class LinthPlugin : Plugin<Project> {
UploadRequest(
apk = it.outputFile,
appIcon = it.outputFile,
appName = "some fancy name",
appName = "", //will be set from manifest
packageName = packageName,
flavor = flavor,
branch = "someFancyBranch",
minSdk = minSdk,
targetSdk = targetSdk,
usesFeature = emptyList(),
usesFeature = emptyList(), //will be set from manifest
buildNumber = 0L,
buildTime = 0L,
buildBatch = "buildBatch",
Expand All @@ -110,6 +110,8 @@ abstract class LinthPlugin : Plugin<Project> {
}

project.tasks.register("uploadToLinth$flavorBuild", UploadToLinthBackend::class.java) { uploadTask ->
uploadTask.flavor = flavor
uploadTask.buildType = buildType
uploadTask.uploadKey = extension.uploadKey.get()
uploadTask.proxy = extension.proxy.orNull
uploadTask.uploadRequest = uploadRequest
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package ch.ubique.linth

import ch.ubique.linth.common.GitUtils
import ch.ubique.linth.common.StringUtils
import ch.ubique.linth.common.getMergedManifestFile
import ch.ubique.linth.common.getResDirs
import ch.ubique.linth.model.UploadRequest
import ch.ubique.linth.network.BackendRepository
import ch.ubique.linth.network.OkHttpInstance
Expand All @@ -12,9 +16,15 @@ import org.gradle.api.tasks.options.Option

abstract class UploadToLinthBackend : DefaultTask() {

private var buildBranch: String = "master"
private var commitHistory: String = "no commit history"

init {
description = "Uploads Apk to Linth Backend"
group = "linth"

buildBranch = project.findProperty("branch")?.toString() ?: GitUtils.obtainBranch()
commitHistory = GitUtils.obtainLastCommits()
}

@get:Input
Expand All @@ -29,6 +39,12 @@ abstract class UploadToLinthBackend : DefaultTask() {
@get:Input
abstract var uploadRequest: UploadRequest

@get:Input
abstract var flavor: String

@get:Input
abstract var buildType: String

@TaskAction
fun uploadAction() {

Expand All @@ -39,12 +55,28 @@ abstract class UploadToLinthBackend : DefaultTask() {
OkHttpInstance.setProxy(null)
}

val backendRepository = BackendRepository()
val uploadRequest = updateUploadRequestWithManifestInformation().copy(
//add git infos
branch = buildBranch,
changelog = commitHistory,
)

runBlocking {
val backendRepository = BackendRepository()
backendRepository.appsUpload(uploadRequest = uploadRequest, uploadKey = uploadKey)
logger.lifecycle("Upload to UbDiag successful.")
}
}

private fun updateUploadRequestWithManifestInformation(): UploadRequest {
val manifestFile = project.getMergedManifestFile(flavor, buildType)
val resDirs = project.getResDirs(flavor)

val appName = StringUtils.findAppName(resDirs, manifestFile) ?: error("Did not find appName in Strings.")

return uploadRequest.copy(
appName = appName
)
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,42 @@ import java.io.BufferedReader

object GitUtils {

/**
* Get the branch name from version control.
* @return
*/

fun obtainBranch(): String {
val cmdGitBranch = "git rev-parse --abbrev-ref HEAD"
val process = ProcessBuilder(*cmdGitBranch.split(" ").toTypedArray())
.redirectErrorStream(true)
.start()

var branchName: String = process.inputStream.bufferedReader().use(BufferedReader::readText).trim()
var branchName = process.inputStream.bufferedReader().use(BufferedReader::readText).trim()
if (branchName.isEmpty()) {
branchName = "develop"
}
return branchName
}

fun obtainLastCommits(numOfCommits: Int = 10): String {
/* eventuell das if-else nutzen wenn es sonst auf dem GitHub Runner nicht geht
val process = if (Os.isFamily(Os.FAMILY_WINDOWS)) {
val lastCommits = "git -C ./ log -$numOfCommits --pretty=format:\"• %s\" --no-merges"
ProcessBuilder(*lastCommits.split(" ").toTypedArray())
.redirectErrorStream(true)
.start()
} else {
val lastCommits = arrayOf("git", "-C", "./", "log", "-$numOfCommits", "--pretty=format:• %s", "--no-merges")
ProcessBuilder(*lastCommits)
.redirectErrorStream(true)
.start()
}
*/

val lastCommits = "git -C ./ log -$numOfCommits --pretty=format:\"• %s\" --no-merges"
val process = ProcessBuilder(*lastCommits.split(" ").toTypedArray())
.redirectErrorStream(true)
.start()

val last10Commits = process.inputStream.bufferedReader().use(BufferedReader::readText).trim()
return last10Commits
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ object IconUtils {
}

val xmlParser = XmlParser(manifestFile)
val fileName = xmlParser.findProperty("application", "android:icon")
val fileName = xmlParser.findAttribute("application", "android:icon")

return fileName?.split("/")?.get(1)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package ch.ubique.linth.common


import com.android.build.gradle.BaseExtension
import org.gradle.api.Project
import org.gradle.api.artifacts.ProjectDependency
import java.io.File

/**
Expand All @@ -14,3 +16,27 @@ fun Project.getMergedManifestFile(flavor: String, buildType: String): File {
"intermediates/merged_manifests/${variantName}/process${variantName}Manifest/AndroidManifest.xml"
)
}


fun Project.getResDirs(flavor: String): List<File> {
val androidModules: List<BaseExtension> = configurations
.asSequence()
.flatMap { it.dependencies }
.filterIsInstance<ProjectDependency>()
.map { it.dependencyProject }
.distinct()
.mapNotNull { it.extensions.findByType(BaseExtension::class.java) }
.toList()

val resDirs: List<File> = androidModules
.flatMap {
listOfNotNull(
it.sourceSets.findByName(flavor.lowercase()),
it.sourceSets.findByName("main")
)
}
.flatMap { it.res.srcDirs }
.filter { it.path.contains("generated").not() }

return resDirs
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package ch.ubique.linth.common

import java.io.File

object StringUtils {

private fun getLabelName(manifestFile: File): String? {
if (manifestFile.isDirectory || manifestFile.exists().not()) {
return null
}

val xmlParser = XmlParser(manifestFile)
val fileName = xmlParser.findAttribute("application", "android:label")

return fileName?.split("/")?.get(1)
}

/**
* Finds all icon files matching the icon specified in the given manifest.
*/
fun findAppName(resDirs: List<File>, manifest: File): String? {
val labelName = getLabelName(manifest) ?: return null

val stringFiles = mutableListOf<File>()
for (resDir in resDirs) {
if (resDir.exists()) {
resDir.walkTopDown().maxDepth(1)
.filter { it.isDirectory && (it.name.startsWith("values")) }
.forEach { dir ->
dir.walkTopDown().filter { it.isFile && it.name.matches(Regex(".*strings.*.xml")) }
.forEach { stringFiles.add(it) }
}
}
}
if (stringFiles.isEmpty()) return null

stringFiles.forEach {
val xmlParser = XmlParser(it)
val appName = xmlParser.findAttribute("string", "name", labelName, findTextValue = true)
if (appName != null) return appName
}

return null
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class XmlParser(
root = document.documentElement
}

fun findProperty(tag: String, property: String): String? {
fun findAttribute(tag: String, attrib: String, matchingAttribValue: String? = null, findTextValue: Boolean = false): String? {
val nodeList = root.childNodes
for (i in 0 until nodeList.length) {
val node = nodeList.item(i)
Expand All @@ -29,8 +29,22 @@ class XmlParser(
val attributes = element.attributes
for (j in 0 until attributes.length) {
val attribute = attributes.item(j)
if (attribute.nodeName == property) {
return attribute.nodeValue
if (attribute.nodeName == attrib) {
if (matchingAttribValue != null) {
if (attribute.nodeValue == matchingAttribValue) {
return if (findTextValue) {
element.firstChild.textContent
} else {
attribute.nodeValue
}
}
} else {
return if (findTextValue) {
element.firstChild.textContent
} else {
attribute.nodeValue
}
}
}
}
return null
Expand Down

0 comments on commit d6e516e

Please sign in to comment.