How to build jacoco test report task in Kotlin (Gradle 5) - kotlin

I have this Groovy script that I would like to convert into Kotlin (build.gradle.kts). Can somebody help me out or give me a pointer?
Groovy (works):
task jacocoTestReport(type: JacocoReport) {
group = "Reporting"
description = "Generate Jacoco coverage reports"
reports {
xml.enabled = true
html.enabled = false
csv.enabled = false
}
def fileFilter = ['**/BuildConfig.class', 'src/main/gen/**/*', 'src/main/assets/**/*',]
def debugTree = fileTree(dir: "${buildDir}/intermediates/javac/debug/classes", excludes: fileFilter)
def mainSrc = "${project.projectDir}/src/main"
sourceDirectories = files([mainSrc])
classDirectories = files([debugTree])
executionData = fileTree(dir: project.projectDir, includes: ['**/**/*.exec', '**/**/*.ec'])
}
Kotlin (my failed attempt, does not work):
tasks.register("jacocoTestReport", JacocoReport::class) {
group = "Reporting"
description = "Generate Jacoco coverage reports"
this.reports.csv.setEnabled(false)
this.reports.html.setEnabled(false)
this.reports.xml.setEnabled(true)
val debugTree = fileTree("${buildDir}/intermediates/javac/debug/classes").filter { file ->
return#filter file.absolutePath.startsWith("src/main/gen/") ||
file.absolutePath.startsWith("src/main/assets/") ||
file.absoluteFile.endsWith("BuildConfig.class")
}
val mainSrc = "${project.projectDir}/src/main"
sourceDirectories.setFrom(files(mainSrc))
classDirectories.setFrom(files(debugTree))
val executionTree = fileTree(project.projectDir).filter { file ->
return#filter !(file.absoluteFile.endsWith(".exec") || file.absoluteFile.endsWith(".ec"))
}
executionData.setFrom(executionTree)
}
Update: This may work. That no XML is created is not related to the content of the script. See accepted answer. But anyway, the accepted answer is a more logical rewrite.

Try something like this:
tasks.register("jacocoTestReport", JacocoReport::class) {
group = "Reporting"
description = "Generate Jacoco coverage reports"
reports {
csv.isEnabled = false
html.isEnabled = false
xml.isEnabled = true
}
sourceDirectories.setFrom(files("${project.projectDir}/src/main"))
classDirectories.setFrom(
fileTree("${buildDir}/intermediates/javac/debug/classes") {
setExcludes(setOf("**/BuildConfig.class", "src/main/gen/**/*", "src/main/assets/**/*"))
}
)
executionData.setFrom(
fileTree(project.projectDir) {
setIncludes(setOf("**/**/*.exec", "**/**/*.ec"))
}
)
}

Related

How to get filepath for Documents from Uri in android 10 and android 11

I am creating an app where users will upload pdf or doc files.
I have used default file chooser which returns Uri , now i need to upload those selected files to server
Its working fine upto android 9 ,i am facing issues in android 10 and 11 (i have used android:requestLegacyExternalStorage="true" for android 10 )
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
.apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "*/*"
putExtra(Intent.EXTRA_MIME_TYPES, supportedDocumentTypes.keys.toTypedArray())
}
resultLauncher.launch(intent)
In Activity Result
if (data != null) {
var path = ""
val id = data.data?.lastPathSegment!!
val selection = "_id=?"
if (id.startsWith("msf:") && Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) {
path = FileHelper(requireContext()).getRealPathFromUri(data.data!!.toString()
.replace("msf:","").toUri())!!
}else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q){
path = FileHelper(requireContext()).getRealPathFromUri(data.data!!)!!
}else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
path = getDataColumn(context, MediaStore.Downloads.EXTERNAL_CONTENT_URI,
selection, arrayOf(getPath(data.data!!)))
} else {
data.data?.also { uri ->
path = FileHelper(requireContext()).getRealPathFromUri(uri)!!
}
}
Log.e("Doc Path ::",path)
AppUtils.CustomToast(requireActivity(),path)
uploadDocs(path)
}
For getting Document_ID
private fun getPath(uri : Uri) : String {
val contentResolver = requireActivity().applicationContext.contentResolver
val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or
Intent.FLAG_GRANT_WRITE_URI_PERMISSION
// Check for the freshest data.
contentResolver.takePersistableUriPermission(uri, takeFlags)
val cursor: Cursor? = contentResolver.query(
uri, null, null, null, null, null)
var id = ""
cursor?.use { cursor1 ->
if (cursor1.moveToFirst()) {
val displayName: String = cursor1.getString(cursor1.getColumnIndex(OpenableColumns.DISPLAY_NAME))
Log.i(TAG, "Display Name: $displayName")
val names = cursor1.columnNames.joinToString(",") { it }
Log.e("names ^^^^^",names)
val sizeIndex: Int = cursor1.getColumnIndex(OpenableColumns.SIZE)
val size: String = if (!cursor1.isNull(sizeIndex)) {
cursor1.getString(sizeIndex)
} else { "Unknown" }
Log.i(TAG, "Size: $size")
id = cursor1.getString(cursor1.getColumnIndex(cursor1.columnNames[0]))
Log.e("DocId",id)
}
}
return id
}
Uploading file to server using Retrofit
val builder = MultipartBody.Builder()
builder.setType(MultipartBody.FORM)
val file = File(docPaths)
builder.addFormDataPart("documents", file.name,
RequestBody.create("multipart/form-data".toMediaTypeOrNull(), file))
val requestBody: MultipartBody = builder.build()
I am expecting some code for getting file to upload to server
Thanks In Advance

What kind of implementation that can get all the SubProjects in each IncludedBuilds in Gradle with the customized tasks?

This is the problem: it couldn't found the include project or what we called subprojects, in each includedBuilds or the rootProjects.
//build.gradle <root>
def excludedBuilds = ["docker", "internals"]
["clean", "build", "Check"].each { taskName ->
tasks.create(taskName.concat("All")) {
group = '<3 in 1>'
gradle.includedBuilds.each { build ->
if (excludedBuilds.contains(build.name)) return
dependsOn gradle.includedBuild(build.name).task(":${???}:$taskName")
// ^ HERE, how can we get all of the subProjects in each includedBuilds?
}
}
}
// figure 1.0
And what is the KOTLIN script version of this one(figure 1.0)?
can we turn this (figure 2.0) into (figure 1.0).
// figure 2.0
tasks.register("checkAll") {
group = "<HERE>"
dependsOn(gradle.includedBuild("application").task(":app:check"))
dependsOn(gradle.includedBuild("application").task(":main-frame:check"))
dependsOn(gradle.includedBuild("utilities").task(":our-strings:check"))
dependsOn(gradle.includedBuild("utilities").task(":our-maths:check"))
}
tasks.register("buildAll") {
group = "<HERE>"
dependsOn(gradle.includedBuild("application").task(":app:build"))
dependsOn(gradle.includedBuild("application").task(":main-frame:build"))
dependsOn(gradle.includedBuild("utilities").task(":our-strings:build"))
dependsOn(gradle.includedBuild("utilities").task(":our-maths:build"))
}
tasks.register("cleanAll") {
group = "<HERE>"
dependsOn(gradle.includedBuild("application").task(":app:clean"))
dependsOn(gradle.includedBuild("application").task(":main-frame:clean"))
dependsOn(gradle.includedBuild("utilities").task(":our-strings:clean"))
dependsOn(gradle.includedBuild("utilities").task(":our-maths:clean"))
}
Maybe this one could satisfied my brain? I know it kind of OFF. but yeah, it is working.(painstakingly!)
def excludedBuilds = ["<excluded build>", "<and so on>"]
def utilities = ["<subProj#1>", "<subProj#2>", "<and so on>"]
def application = ["<subProj#1>", "<subProj#2>", "<and so on>"]
def arrayz;
["clean", "build", "check"].each { taskName ->
tasks.create(taskName.concat("All")) {
group = '<3 in 1>'
gradle.includedBuilds.each { build ->
if (excludedBuilds.contains(build.name)) return
switch(build.name) {
case "application":
arrayz = application
break;
case "utilities":
arrayz = utilities
break;
default:
return
}
for(String subProj : arrayz)
dependsOn gradle.includedBuild(build.name).task(":$subProj:$taskName")
}
}
}
We can also try this one.
arrayz.each { subProj ->
dependsOn gradle.includedBuild(build.name).task(":$subProj:$taskName")
}

How can I write do noting in Kotlin?

ESelect is a enum structure. I hope it will do noting when it is ESelect.NoAction in the following code.
It will cause compile error if I write ; after ESelect.NoAction ->, how can I fix it?
Code
aHomeViewModel.selectAction.observe(mLifecycleOwner, {
when(it) {
ESelect.SelectAll - > binding.chSelect.isChecked = true
ESelect.UnselectAll - > binding.chSelect.isChecked = false
ESelect.NoAction - > ; //It will do nothing
}
})
enum class ESelect {
SelectAll,
UnselectAll,
NoAction
}
You could return Unit (which is like void in Java). The code will look like:
aHomeViewModel.selectAction.observe(mLifecycleOwner, {
when(it) {
ESelect.SelectAll -> binding.chSelect.isChecked = true
ESelect.UnselectAll -> binding.chSelect.isChecked = false
ESelect.NoAction -> Unit
}
})
See the Docu: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/
You could use when as an expression instead of a statement, and for the NoAction case assign the existing value:
binding.chSelect.isChecked = when (it) {
ESelect.SelectAll -> true
ESelect.UnselectAll -> false
ESelect.NoAction -> binding.chSelect.isChecked
}
Or use if:
if (it == ESelect.SelectAll) {
binding.chSelect.isChecked = true
} else if (it == ESelect.UnselectAll) {
binding.chSelect.isChecked = false
}

Jenkins, global vars

There is the following code that works correctly (adds a global variable successfully), but the result of executing this code in the pipeline is always FAILED. I can't catch an error using try-catch - nothing is output to the pipeline console.
If I make code with def (lines are commented out), FAILED does not occur (the pipeline is green), but the code does not work (the variable is not added.
How do I find an error or make sure that the pipeline doesn't FAIL?
import hudson.slaves.EnvironmentVariablesNodeProperty
import jenkins.model.*
try {
/*
Jenkins instance = Jenkins.getInstance()
//jenkins = Jenkins.instance //this need script approve
def globalNodeProperties = instance.getGlobalNodeProperties()
def envVarsNodePropertyList = globalNodeProperties.getAll(hudson.slaves.EnvironmentVariablesNodeProperty.class)
def newEnvVarsNodeProperty = null
def envVars = null
*/
instance = Jenkins.getInstance()
globalNodeProperties = instance.getGlobalNodeProperties()
envVarsNodePropertyList = globalNodeProperties.getAll(EnvironmentVariablesNodeProperty.class)
newEnvVarsNodeProperty = null
envVars = null
if ( envVarsNodePropertyList == null || envVarsNodePropertyList.size() == 0 ) {
newEnvVarsNodeProperty = new EnvironmentVariablesNodeProperty();
globalNodeProperties.add(newEnvVarsNodeProperty)
envVars = newEnvVarsNodeProperty.getEnvVars()
} else {
envVars = envVarsNodePropertyList.get(0).getEnvVars()
}
} catch(Exception ex) {
println("Exception error: ${ex}")
}
envVars.put("sample_var", "Sample Groovy Global Var")
instance.save()
Please check with this (function) code (it doesn't work either):
import hudson.slaves.EnvironmentVariablesNodeProperty
import jenkins.model.*
#NonCPS
def add_global_var() {
instance = Jenkins.getInstance()
globalNodeProperties = instance.getGlobalNodeProperties()
envVarsNodePropertyList = globalNodeProperties.getAll(EnvironmentVariablesNodeProperty.class)
newEnvVarsNodeProperty = null
envVars = null
if ( envVarsNodePropertyList == null || envVarsNodePropertyList.size() == 0 ) {
newEnvVarsNodeProperty = new EnvironmentVariablesNodeProperty();
globalNodeProperties.add(newEnvVarsNodeProperty)
envVars = newEnvVarsNodeProperty.getEnvVars()
} else {
envVars = envVarsNodePropertyList.get(0).getEnvVars()
}
envVars.put("snapshot_id", "Sample Groovy Global Var 4")
instance.save()
}
pipeline {
agent { node { label 'slave' } }
stages {
stage('Check global var') {
steps {
add_global_var()
}
}
}
}

Android, Gradle: Create task "on fly" - Could not find method

Gradle 3.4:
I has some gradle task:
def currentVariantName = "prod"
task runAllTestProd(dependsOn: ["test$currentVariantName" + "UnitTest", "connected$currentVariantName" + "AndroidTest"]) {
...
}
It's work fine.
But I want to create this task "on fly":
android.applicationVariants.all { variant ->
def variantName = variant.getName()
if (!variantName.equalsIgnoreCase("release")) {
def currentVariantName = variantName.capitalize()
def currentUnitTestName = "test$currentVariantName" + "UnitTest"
def currentInstrumentedTestName = "connected$currentVariantName" + "AndroidTest"
task "runAllTest$currentVariantName"(dependsOn: "[$currentUnitTestName", "$currentInstrumentedTestName]") {
description = "Run all tests for buildType: $currentVariantName"
}
}
}
Get error:
Error:(181, 0) Could not find method runAllTestProd() for arguments [{dependsOn=[testProdUnitTest}, connectedProdAndroidTest], build_219ioziv1uq8hefe7aewl6fv9$_run_closure5$_closure28#69b49ec6] on object of type com.android.build.gradle.internal.api.ApplicationVariantImpl.
Open File
I found the problem. Syntax error. Change in in row "dependsOn: ...".
Here correct code:
android.applicationVariants.all { variant ->
def variantName = variant.getName()
if (!variantName.equalsIgnoreCase("release")) {
def currentVariantName = variantName.capitalize()
def currentUnitTestName = "test$currentVariantName" + "UnitTest"
def currentInstrumentedTestName = "connected$currentVariantName" + "AndroidTest"
task "runAllTest$currentVariantName"(dependsOn: ["$currentUnitTestName", "$currentInstrumentedTestName"]) {
description = "Run all tests for buildType: $currentVariantName"
}
}
}