Rename file in gradle with passed parameter - android

I'm packaging up my build artefacts from a gradle build. It's an Android Studio project.
I have tasks that successfully create a zip file containing two jars. Let's say the zip file is called 'my.zip'.
I have the following gradle task:
task renameArtifacts (type: Copy) {
from ('build/')
include 'my.zip'
destinationDir file('build/')
doLast {
println "my-${versionString}.zip"
rename('build/my.zip', "build/my-${versionString}.zip")
}
}
And I'm calling it with gradle -PversionString="123" :sdk:renameArtifacts
I have a println in the doLast closure and can see the my string interpolation is working correctly as it outputs my-123.zip.
However, 'my.zip' is not renamed to 'my-123.zip'. It remains 'my.zip' and in fact results in a file with a size of zero bytes and is no longer openable as a zip file.
I'm obviously going wrong somewhere, but where?
Full gradle file:
apply plugin: 'com.android.library'
android {
compileSdkVersion 22
buildToolsVersion "23.0.3"
defaultConfig {
minSdkVersion 14
targetSdkVersion 14
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:support-v4:22.2.0'
compile files('libs/urbanairship-lib-3.1.0.jar')
compile files('libs/jackson-annotations-2.2.2.jar')
compile files('libs/jackson-core-2.2.2.jar')
compile files('libs/jackson-databind-2.2.2.jar')
}
task updateVersionNumber() << {
ant.replace(file: 'src/main/java/com/my/Version.java', token: '{{VERSION}}', value: versionString)
}
task javadoc(type: Javadoc) {
source = android.sourceSets.main.java.srcDirs
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
destinationDir = file("build/javadoc")
failOnError false
}
task createJavaDocJar(type: Jar) {
from ('build/javadoc')
destinationDir file('build')
baseName = 'my_doc'
}
createJavaDocJar.dependsOn(javadoc)
task packageMyJarAndDependencies(type: Jar) {
from (zipTree('libs/jackson-annotations-2.2.2.jar')) {
exclude 'META-INF/maven/'
exclude 'META-INF/services/'
}
from (zipTree('libs/jackson-core-2.2.2.jar')) {
exclude 'META-INF/maven/'
exclude 'META-INF/services/'
}
from (zipTree('libs/jackson-databind-2.2.2.jar')) {
exclude 'META-INF/maven/'
exclude 'META-INF/services/'
}
from (zipTree('libs/urbanairship-lib-3.1.0.jar'))
from (zipTree('build/intermediates/bundles/release/classes.jar'))
}
task createFinalJar(type: Copy) {
from('build/libs/')
into('build')
include('sdk.jar')
rename('sdk.jar', 'my.jar')
}
createFinalJar.dependsOn(clean, build, packageMyJarAndDependencies)
packageMyJarAndDependencies.mustRunAfter build
build.mustRunAfter clean
task zipArtifacts(type: Zip) {
from ('build/')
from ('build/libs')
include 'my_doc.jar'
include 'my.jar'
baseName = 'my_lib'
destinationDir file('build')
}
zipArtifacts.dependsOn(createFinalJar, createJavaDocJar)
task renameArtifacts (type: Copy) {
from ('build/')
into('build')
include 'my_lib.zip'
doLast {
println "my_lib-${versionString}.zip"
rename "my_lib.zip", "my_lib-${versionString}.zip"
}
}
renameArtifacts.dependsOn(zipArtifacts)

rename is a method on CopyProcessingSpec, that configures the task to perform some renamings while operating. If you wrap it in doLast, the copying has already happened, and no rename will be performed. Furthermore, rename takes only file names, not relative or absolute file paths. This should work:
project.ext.versionString = versionString
task renameArtifacts (type: Copy) {
from ('build/')
include 'my.zip'
destinationDir file('build/')
rename 'my.zip', "my-${project.versionString}.zip"
}
Edit: $versionString is not accessible in tasks. Using extra project property is the suggested way how to pass these in tasks (see here).

Related

Apache commons dependency not excluded in gradle | Android

I have a library project (Janrain:Jump) that uses the org.apache.http.legacy library. When I try to build my project I get the duplicate error like following:
com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/apache/commons/codec/StringEncoderComparator.class
So I figured that the org.apache.commons are duplicate entry because Janrain uses it and it's also included in the Android 24 (as an external library). So I tried to remove the commons from the :Jump gradle like:
configurations {
all*.exclude group: 'org.apache.commons'
}
Now, I'd expect that this removes org.apache.commons but I still get the duplicate entry gradle error.
Here is the :Jump gradle file
apply plugin: 'com.android.library'
android {
compileSdkVersion 24
buildToolsVersion "24.0.3"
//If building with strict Android 6.0 the following will need to be uncommented
//See: https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html
//And: http://stackoverflow.com/questions/31653002/how-to-use-the-legacy-apache-http-client-on-android-m
useLibrary "org.apache.http.legacy"
defaultConfig {
minSdkVersion 17
targetSdkVersion 24
// replace the below string with your own Google client ID. Make sure this is consistent
// with the values used in openid_appauth_idp_configs.xml
manifestPlaceholders = [
<my values>]
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
configurations {
all*.exclude group: 'org.apache.commons'
}
dependencies {
compile 'com.android.support:support-v4:24.2.0'
compile files('libs/org.apache.http.legacy.jar')
compile 'com.squareup.okhttp:okhttp:2.5.0'
compile 'com.squareup.okhttp:okhttp-apache:2.5.0'
compile 'com.squareup.okio:okio:1.6.0'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.squareup.retrofit:retrofit:1.8.0'
compile 'net.openid:appauth:0.4.1'
}
allprojects {
repositories {
jcenter()
}
gradle.projectsEvaluated {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
}
}
}
Why is the org.apache.commons not excluded even when I include it in configurations?
Just add this task to your build.gradle then run gradle findDuplicates to find the jars
task findDuplicates {
doLast {
def findMe = 'org/apache/commons/codec/StringEncoderComparator.class'
configurations.runtime.asFileTree.matching {
include '**/*.jar'
}.files.each { File jarFile ->
zipTree(jarFile).visit { FileVisitDetails fvd ->
if (fvd.path == findMe) {
println "Found $findMe in $jarFile.name"
}
}
}
}
}

Android Studio-how to export a jar with other jars in it?

I use below gradle to generate .jar file
When I export using below gradle I am able to generate .jar file but it has not attached the dependent MyJar file.
apply plugin: 'com.android.library'//To generate Jar
android {
compileSdkVersion 24
buildToolsVersion "25.0.0"
sourceSets {
main {
//Path to My source code
java {
srcDir 'src/main/java'
}
}
}
defaultConfig {
minSdkVersion 15
targetSdkVersion 24
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
testCompile 'junit:junit:4.12'
compile files('libs/MyJar.jar')//MyJar When generating the Jar this is not include by gradle?
}
//task to delete the old jar
task deleteOldJar(type: Delete) {
delete 'release/ExportedJar.jar'
}
//task to export contents as jar
task exportJar(type: Copy) {
from('build/intermediates/bundles/release/')
into('release/')
include('classes.jar')
//include('MyJar.jar')//Tried this but No luck
rename('classes.jar', 'ExportedJar.jar')
}
exportJar.dependsOn(deleteOldJar, build)
How to achieve this...is there any turnaround.Thanks in Advance
What you would like to achieve is to build a so-called "Fat Jar".
Add another task to your library's build.gradle:
task fatJar(type: Jar) {
baseName = project.name + '-all'
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
with jar
}
and invoke through command line:
gradlew fatJar
If you would like to add only .jar's from lib folder, then add to build.gradle:
jar {
into('lib') {
from 'libs'
}
}
And invoke from command line:
gradlew :{library_module_name}:jar

Gradle+Java+Android+AIDE making a recursive list from assets directory....

i would have loved to put this as a comment to the original question, but i have not enough access rights to make comments....
i tried to use the answer of Android+Gradle: list directories into a file for an android java project developed with AIDE....
as far as i understand all this gradle/maven stuff AIDE still uses gradle v 1.
estracted from the general build.gradle file:
dependencies {classpath 'com.android.tools.build:gradle:1.+'}
so i added the whole new assets reading task to the app build.gradle (in the app director) that now looks this way:
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.0"
defaultConfig {
applicationId "com.nohkumado.quelkar"
minSdkVersion 14
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
//try to compile a asset directory listing....
task indexAssets
{
description 'Index Build Variant assets for faster lookup by AssetManager later'
ext.assetsSrcDir = file( "${projectDir}/src/main/assets" )
ext.assetsBuildDir = file( "${buildDir}/assets" )
inputs.dir assetsSrcDir
//outputs.dir assetsBuildDir
doLast
{
android.applicationVariants.each
{
target ->
ext.variantPath = "${buildDir.name}/assets/${target.dirName}"
println "copyAssetRec:${target.dirName} -> ${ext.variantPath}"
def relativeVariantAssetPath = projectDir.name.toString() + "/" + ext.variantPath.toString()
def assetIndexFile = new File(relativeVariantAssetPath +"/assets.index")
def contents = ""
def tree = fileTree(dir: "${ext.variantPath}", exclude: ['**/.svn/**', '*.index'])
tree.visit
{
fileDetails ->
contents += "${fileDetails.relativePath}" + "\n"
}
assetIndexFile.write contents
}
}
}
indexAssets.dependsOn
{
tasks.matching { task -> task.name.startsWith( 'merge' ) && task.name.endsWith( 'Assets' ) }
}
tasks.withType( Compile )
{
compileTask -> compileTask.dependsOn indexAssets
}
}
dependencies {
compile project('::../UtilsApp:nohutils')
compile fileTree(dir: 'libs', include: ['*.jar'])
}
so i thought i did it right..... but seems not, adding that task to the gradle file, break the dependcies directive meaning that suddenly all my imports from the external library nohutils don't work anymore.....
and in fact, it happens as soon as i declare, even an empty "task indexAssets".....
unfortunately, each time i try to apply what i read in the gradle manual, fails in AIDE and since AIDE has no manual whatsoever, its just dabbling in the dark....
so if anyone has a possible explanation/solution i will gladly take it....

Android Studio project has stopped building. Error retrieving parent for item: android:TextAppearance.Material.Widget.Button.Inverse

I have been working on a project for the past 2 years of which I have moved it to Android Studio since about last 1 year(I am using Android Studio 1.5.1 currently). Just today when I opened the project to run it I got Error retrieving parent for item: android:TextAppearance.Material.Widget.Button.Inverse and android:Widget.MaterialButton.Colored errors.
The following is my app.gradle file:
import org.apache.tools.ant.taskdefs.condition.Os
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "com.opaxlabs.boatbrat"
minSdkVersion 14
targetSdkVersion 22
versionCode 20
versionName '2.0'
multiDexEnabled true
// ndk {
// moduleName "password"
// abiFilter "all"
// }
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES.txt'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/notice.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/dependencies.txt'
exclude 'META-INF/LGPL2.1'
}
dexOptions{
preDexLibraries = false
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
// sourceSets.main.jni.srcDirs = [] // disable automatic ndk-build call, which ignore our Android.mk
// sourceSets.main.jniLibs.srcDir 'src/main/libs'
//
// // call regular ndk-build(.cmd) script from app directory
// task ndkBuild(type: Exec) {
// workingDir file('src/main')
// commandLine getNdkBuildCmd()
// }
//
// tasks.withType(JavaCompile) {
// compileTask -> compileTask.dependsOn ndkBuild
// }
//
// task cleanNative(type: Exec) {
// workingDir file('src/main')
// commandLine getNdkBuildCmd(), 'clean'
// }
//
// clean.dependsOn cleanNative
// splits {
// abi {
// enable true
// reset()
// include 'x86', 'armeabi-v7a', 'mips'
// universalApk true
// }
// }
}
//repositories {
// jcenter()
// maven { url "http://dl.bintray.com/webactive/maven" }
//}
//def getNdkDir() {
// if (System.env.ANDROID_NDK_ROOT != null)
// return System.env.ANDROID_NDK_ROOT
//
// Properties properties = new Properties()
// properties.load(project.rootProject.file('local.properties').newDataInputStream())
// def ndkdir = properties.getProperty('ndk.dir', null)
// if (ndkdir == null)
// throw new GradleException("NDK location not found. Define location with ndk.dir in the local.properties file or with an ANDROID_NDK_ROOT environment variable.")
//
// return ndkdir
//}
//
//def getNdkBuildCmd() {
// def ndkbuild = getNdkDir() + "/ndk-build"
// if (Os.isFamily(Os.FAMILY_WINDOWS))
// ndkbuild += ".cmd"
//
// return ndkbuild
//}
repositories {
jcenter()
maven { url "http://dl.bintray.com/webactive/maven" }
}
dependencies {
compile 'com.android.support:multidex:1.0.0'
// compile 'com.android.support:support-v4:+'
compile 'com.google.android.gms:play-services:+'
// {
// exclude module: 'play-services-analytics'
// }
// compile ('com.google.android.gms:play-services-analytics:7.3.0')
compile 'com.android.support:appcompat-v7:22.+'
// compile 'com.stripe:stripe-android:+'
// compile files('libs/PayPal_MPL.jar')
compile files('libs/cwac-adapter-1.0.2.jar')
compile files('libs/devsmartlib.jar')
compile files('libs/fluent-hc-4.3.3.jar')
compile files('libs/httpasyncclient-4.0.1.jar')
compile files('libs/httpasyncclient-cache-4.0.1.jar')
compile files('libs/httpclient-4.3.2.jar')
compile files('libs/httpclient-cache-4.3.1.jar')
compile files('libs/httpcore-4.3.2.jar')
compile files('libs/httpmime-4.3.3.jar')
compile files('libs/universal-image-loader-1.9.2-with-sources.jar')
compile files('libs/endless-1.2.3.jar')
compile files('libs/jncryptor-1.2.0.jar')
compile files('libs/commons-codec-1.7-SNAPSHOT-android.jar')
compile 'com.eway.payment:android-sdk:1.1'
}
I am using lower version build tools as the project has a lot of code that is deprecated and using later tools and sdk might complicate the problem. I even tried to build with version 23 but that did not help.
I tried the following:
This
and
this
but they are essentially saying things I have already done.
Any help will be greatly appreciated. Thanks in advance.
Since you are using
compile 'com.google.android.gms:play-services:+'
you are using the latest version compile 'com.google.android.gms:play-services:8.4.0' which has a dependency with support libraries v23.
You have to compile with API 23.
Change this line:
compileSdkVersion 23
In general is not a good practice the use of + in your dependencies because you can't replicate the build in the future with the same libraries and you don't know which version you are using.

Gradle could not find manifest file

I am trying to build a project but I have the following error when I try to build it from command line:
error: Could not find the AndroidManifest.xml file, going up from path [C:\Users\User\Documents\work
space\app\app\app\build\generated\source\apt\debug] found using dummy file []
(max atempts: file:///C:/Users/User/Documents/workspace/app/app/app/build/generated/source/apt/debug/dummy1449680140847.java)
My manifest.xml is under the main foulder in the project structure.
and this is my gradle file:
import com.android.builder.core.DefaultManifestParser
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.3'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
apply plugin: 'com.android.application'
apply plugin: 'android-apt'
android {
compileSdkVersion 22
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "com.ponideapps.recetapp"
minSdkVersion 14
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
// This is important, it will run lint checks but won't abort build
lintOptions {
abortOnError false
}
task srcZip(type: Zip) {
from projectDir
def manifestParser = new DefaultManifestParser()
def versionName = manifestParser.getVersionName(android.sourceSets.main.manifest.srcFile)
archiveName = "${project.name}-${versionName}.${extension}"
exclude 'build', 'gen', 'bin', '.DS_Store', '.settings', 'local.properties', '.gradle', '*.apk', '.idea', '*.iml', '*.log',
'*/build', "*/gen", "*/bin", '*/*.iml', '*/*.log'
}
assemble.dependsOn srcZip
}
allprojects {
repositories {
mavenCentral()
}
}
android.applicationVariants.all { variant ->
println "Defining task generate${variant.name.capitalize()}Javadoc"
task("generate${variant.name.capitalize()}Javadoc", type: Javadoc) {
description "Generates Javadoc for $variant.name."
source = variant.javaCompile.source
//source = files()
//variant.sourceSets.each{ sourceSet ->
// sourceSet.javaDirectories.each{ javaDirectory ->
// //println("adding source dir for javadoc generation: " + javaDirectory)
// source += files(javaDirectory)
// }
//}
//source += files("$buildDir/generated/source/r/" + variant.dirName)
ext.androidJar = "${android.sdkDirectory}/platforms/${android.compileSdkVersion}/android.jar"
classpath = files(variant.javaCompile.classpath.files) + files(ext.androidJar)
//why doesn't this help? This should add the classfiles for the apt & R files
//+ files("$buildDir/intermediates/classes/" + variant.dirName)
//this would allow markdown comments, however, the plugin seems to be broken and always claims it cannot write a file it has just written :(
//options.doclet = 'com.visural.doclets.markdown.standard.Standard'
//options.docletpath = ["./libs/MarkdownDoclet-3.0.jar"]
options.links("http://docs.oracle.com/javase/7/docs/api/", "http://www.joda.org/joda-time/apidocs/");
//this is necessary to create links to the android documentation: the android website does not
//contain the list necessary to create javadoc, the local installation does
options.linksOffline("http://d.android.com/reference", "${android.sdkDirectory}/docs/reference");
exclude '**/BuildConfig.java'
exclude '**/R.java'
options.memberLevel = JavadocMemberLevel.PROTECTED
//this is very much necessary, as the apt files & the R.class would otherwise break the javadoc
failOnError false
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.android.support:design:22.2.1'
//android annotations
compile files('libs/androidannotations-api-3.0.1.jar')
apt files('libs_annotations/androidannotations-3.0.1.jar')
}
apt {
arguments {
resourcePackageName "com.ponideapps.recetapp"
}
}
Does someone where is the problem?
Thank you very much in advance!
Add this:
apt {
arguments {
resourcePackageName "com.ponideapps.recetapp"
androidManifestFile variant.outputs[0]?.processResources?.manifestFile
}
}

Categories

Resources