How to get an argument from command line using Gradle task? - android

I'm trying to get an argument from the command line using a Gradle task:
class myApk extends DefaultTask {
#Option(option="apkName", description="apkName for your file")
String apkName
#TaskAction
void uploadApk() {
def arg = "curl -F \"demo${apkName}.apk=" +
"#${project.projectDir}\\app\\build\\outputs\\apk\\debug\\app-debug.apk\" " +
"https://URL"
project.exec {
commandLine("cmd", "/c", arg)
}
}
}
task uploadApk(type: myApk) { }
But after typing gradle uploadApk --apkName=foo in the terminal I get this kind of exception:
Problem configuring task :app:uploadApk from command line.
> Unknown command-line option '--apkName'.
P.S. I've read this topic(How to pass arguments from command line to gradle), but it doesn't seem helpful for this problem;(

Thanks to the comment above, I used -P to work it out

Related

java.lang.ClassNotFoundException on frida

I am trying to hook function of android messaging application.
I run frida hook script. then I get a following error:
Error: java.lang.ClassNotFoundException: Didn't find class "i0.a.a.a.e3.z" on path: DexPathList[[/data/app/xxxxx==/base.apk]]
In Jadx-Gui, base.apk is decompiled as follows
package i0.a.a.a.e3;
/* loaded from: classes5.dex */
public final class z {
}
script is as follows
let z = Java.use("i0.a.a.a.e3.z");
How can I solve this error?
Try running your hook inside the Java.perform() method of Frida.
Java.perform(function() {
let z = Java.use("i0.a.a.a.e3.z");
z["somefunction"].implementation = function (str) {
console.log('somefunctionis called' + ', ' + 'str: ' + str);
let ret = this.somefunction(str);
console.log('somefunctionret value is ' + ret);
return ret;
};
})
It solved my problem that was similar to yours.

hudson.FilePath is missing steps wrapped in node/ try catch

I am running a Jenkins pipeline script. I keep get the error that org.jenkinsci.plugins.workflow.steps.MissingContextVariableException: Required context class hudson.FilePath is missing Perhaps you forgot to surround the code with a step that provides this, such as: node in the stack trace. The actual credentials in my script on Jenkins are there but for the sake of this example they were given symbols.
Here is my script that I am running:
try {
node {
stage('Preparation') {
git credentialsId: 'validCredentials', url: 'repo', branch: 'branch'
}
stage('Clean Build') {
dir("directory-to-where-my gradle-wrapper-is-located") {
sh "pwd"
sh 'ls -al'
sh './gradlew clean build'
}
}
}
}catch (caughtError) {
err = caughtError
currentBuild.result = "FAILURE"
} finally {
if(currentBuild.result == "FAILURE"){
sh "echo 'Build FAILURE'"
}else{
sh "echo 'Build SUCCESSFUL'"
}
}
any ideas?

Java or Kotlin file `MainApplication.java` does not include package declaration

I was trying to install expo-av into a non-expo react-native project. After installing react-native-unimodules and adjusting the android/app/build.gradle file, I am not able to build the android app anymore.
This is the main error I get:
The terminal looks like this: Java or Kotlin file MainApplication.java does not include package declaration.
ENVFILE=.env react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 2152 file(s) to forward-jetify. Using 16 workers...
info JS server already running.
info Installing the app...
Configuration on demand is an incubating feature.
> Configure project :app
Reading env from: .env
FAILURE: Build failed with an exception.
* Where:
Script '/Users/*REDACTED*/HF-Projects/*REDACTED*/node_modules/react-native-unimodules/gradle.groovy' line: 75
* What went wrong:
A problem occurred evaluating project ':app'.
> Java or Kotlin file /Users/*REDACTED*/HF-Projects/*REDACTED*/android/app/src/main/java/com/*REDACTED*/MainApplication.java does not include package declaration
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 14s
I searched for package on that file and found 26 occurrences.
There is this packages variable on this ReactNativeHost instance.
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
#Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
#Override
protected List<ReactPackage> getPackages() {
#SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
// Add unimodules
List<ReactPackage> unimodules = Arrays.<ReactPackage>asList(
new ModuleRegistryAdapter(mModuleRegistryProvider)
);
packages.addAll(unimodules);
return packages;
}
#Override
protected String getJSMainModuleName() {
return "index";
}
#Override
protected JSIModulePackage getJSIModulePackage() {
return new ReanimatedJSIModulePackage(); // <- add
}
};
Does anybody know about this error?
The short answer is:
This is a simple validation that looks for the main package of that java class.
On top of the file, there should be a package com.yourcompany.example.
It happened that my MainApplication.java class had TWO BLANK SPACES right after packages.
So the regex didn't find it.
The regex used in this validation may be found on the file node_modules/react-native-unimodules/gradle.groovy line 67.
Regex used: /^package ([0-9a-zA-Z._]*);?$/
def readPackageFromJavaOrKotlinFile(String filePath) {
def file = new File(filePath)
def fileReader = new BufferedReader(new FileReader(file))
def fileContent = ""
while ((fileContent = fileReader.readLine()) != null) {
def match = fileContent =~ /^package ([0-9a-zA-Z._]*);?$/
if (match.size() == 1 && match[0].size() == 2) {
fileReader.close()
return match[0][1]
}
}
fileReader.close()
throw new GradleException("Java or Kotlin file $file does not include package declaration")
}

How to upload file using Gradle task properly?

I'm trying to upload a debug apk file to the server by Gradle. I'm using a special name for it, smth like "demo-testing.apk" or "demo-first.apk".
class Apk extends DefaultTask {
String apkName
#TaskAction
void uploadApk() {
exec {
commandLine(
"cmd",
"-c",
"curl -F \"demo${apkName}.apk=" +
"#${DEFAULT_BUILD_DIR_NAME}/outputs/apk/debug/app-debug.apk\" " +
"https://URL"
)
}
}
}
tasks.register("first", Apk) {
group = 'apkUploads'
description = 'Uploads first apk'
apkName = '-first'
}
But it doesn't execute(with proper URL in the command line arguments) due to this exception:
Caused by: org.gradle.internal.metaobject.AbstractDynamicObject$CustomMessageMissingMethodException: Could not find method exec() for arguments [Apk$_uploadApk_closure1#58ed1
b0a] on task ':first' of type Apk.
Can someone please tell me what I'm doing wrong?
So thanks to the comment above I should have invoke project.exec instead of exec and it worked

Android Studio Gradle sourceSets copy

Android Studio 2.0 Preview 2, Gradle Wrapper 2.8, Mac OS X
-MainProjectWorkspace
-|-build.gradle
-|-settings.gradle
-|-gradle.properties
-|-gradle
-|-MyLibraryDependencies
-|-MyMainModule
--|-build.gradle
--|-build
--|-src
---|-androidTest
---|-main
----|-assets
----|-jniLibs
----|-libs
----|-java
-----|-com
----|-res
----|-AndroidManifest.xml
MyMainModule/build.gradle
//Not a single SourceSets configurations.
productFlavors {
flavor1 {
}
flavor2 {
}
}
buildTypes {
release {
}
debug {
}
}
A genius developer left System.out.println statements, instead of Log statements in several hundreds of Java source-files in 'src/main/java'. Ideally, we do not want Sysout statements getting bundled with either of the applicationVariants, specially flavor1Release and flavor2Release.
Before we make amends to those hundreds of Java source-files and eventually switch the Sysout statements to Log statements, we would need to turn them off urgently.
Two possible solutions -
Execute a simple script that will remove all the Sysout statements in the Java source-files in 'src/main/java'. But about that, variants flavor1Debug and flavor2Debug need the Loggers displaying what's going on in the App.
Execute a simple Gradle task at build-time, copy Java source-files from 'src/main/java' to 'src/release/java', ensuring Sysout statements are omitted.
Solution 2 appears to be quickest, easiest, elegant. Particularly when the Gradle Custom-task is executed independently. Except for that, Gradle-sync in Android-Studio seems to be copying everything from 'src/main' to 'src/release' including assets, jniLibs, libs, res and even the AndroidManifest.xml. Fortunately, the Java source-files are ripped-off the Sysout statements in 'src/release', which is the expected result, and ideally, only 'src/release/java' should remain without any other folders.
task prepareRelease(type: Task) {
Pattern sysoutRegex = Pattern.compile(<Sysout-Pattern>)
try {
File releaseFolder = file("src/release")
File mainFolder = file("src/main")
ByteArrayOutputStream output = new ByteArrayOutputStream()
exec {
commandLine = "sh"
args = ["-c", "find ${mainFolder.canonicalPath} -name '*' -type f -print ",
"| xargs egrep -l '${sysoutRegex.pattern()}'"]
standardOutput = output
}
def fileList = output.toString().split(System.getProperty("line.separator"))
fileList.each { line ->
File srcFile = file(line)
File destFile = file(srcFile.canonicalPath.replace("main", "release"))
def content = srcFile.readLines()
if (!destFile.exists()) {
destFile.parentFile.mkdirs()
destFile.createNewFile()
destFile.writable = true
}
destFile.withWriter { out ->
content.eachWithIndex { contentLine, index ->
if (!sysoutRegex.matcher(contentLine).find()) {
out.println contentLine
}
}
}
} catch (Exception fail) {
throw fail
}
}
There is nothing in the custom Gradle-task that may cause this error of making "src/release" an exact copy of "src/main", which was not intended to be.
Any pointers to prevent this default copy of "src/main" to "src/release" will be greatly appreciated.
Based off RaGe's comment - "How about using *.java as your find pattern instead of * ?"
Kudos. I was not supposed to break the "find | xargs egrep " before the '|' into two separate args in the args[] in the exec task. Indeed, a Genius!!!

Categories

Resources