what's default ndk path in gradle script? - android-studio

Recently I want to have variable that contains path of current ndk(in use) path.
exactly in my gradle script my task need ndk path (that is in use), but I don't know how find it.
task initDeps(type: Exec) {
// my ndk variable: ndkPath // How define it???
doFirst {
println "NDK path: " + ndkPath
}
}
for example my ndk path that is using in this project(or android studio) is : "/home/<user_name>/Android/Sdk/ndk/21.4.7075529"
hence variable ndkPath contains "/home/<user_name>/Android/Sdk/ndk/21.4.7075529" , but it;s relative path in another platforms , cause of that I want to know what's default variable that can bring me this goal.
hint: something like that is defined can be defined local properties -> ndk.dir ,
but independent platform

Related

How to show full compile error messages info in Checker FrameWork with line numbers etc

I just started using Checker Framework and have a problem that is exactly reproducible on one of the example projects from authors of this framework. This project is available here:
https://github.com/typetools/checker-framework/tree/master/docs/examples/GradleExamples
When i run this command from root:
>gradle compileJava
i receive this compilation output:
public static /*#Nullable*/ Object nullable = null;
^
required: #Initialized #NonNull Object
list.add(null); // error on this line
^
required: #Initialized #NonNull String
2 errors
:compileJava FAILED
As you can see there is no any information about where errors occur like class name, line number in code etc.
I did not find any information in their official manual about any compiler parameters that can change output format appropriately. I want error messages look like this:
~\GradleExample.java:33 error: ';' expected
UPDATE:
I achieve this behaviour on 3 machines:
OS: Microsoft Windows 7 x64 Ultimate SP1 [version 6.1.7601];
Java: 1.8.0_73;
Gradle: 2.14.
OS: Microsoft Windows 10 x64 Pro [version 10.0.14393];
Java: 1.8.0_121;
Gradle: 3.4.1.
OS: Microsoft Windows 7 x64 Ultimate SP1 [version 6.1.7601];
Java: 1.8.0_121;
Gradle: 3.4.1.
The absence of line numbers and class names is experienced only when running with Gradle. I also tried to run checker with Maven and with Javac from command line and it worked perfectly.
To configure Checker Framework with Gradle i followed steps from manual. There are 3 steps:
Download framework;
Unzip it to create a checker-framework directory;
Configure Gradle to include Checker Framework on the classpath.
As i understand, Gradle will do steps 1 and 2 automatically when providing needed Checker Framework's jars through dependency management. Nevertheless i tried both options:
dependency management:
I simply downloaded example project and executed "gradle compileJava" from root
of the GradleJava7Example project.
manually writing paths in gradle build file:
allprojects {
tasks.withType(JavaCompile).all { JavaCompile compile ->
compile.options.compilerArgs = [
'-processor', 'org.checkerframework.checker.nullness.NullnessChecker',
'-processorpath', "C:\\checker-framework-2.1.10\\checker\\dist\\checker.jar",
"-Xbootclasspath/p:C:\\checker-framework-2.1.10\\checker\\dist\\jdk8.jar",
'-classpath', 'C:\\checker-framework-2.1.10\\checker\\dist\\checker.jar;C:\\checker-framework-2.1.10\\checker\\dist\\javac.jar'
]
}
}
I've found a workaround. I'll explain it later, but now if somebody has the same problem, add this line to you JavaCompile tasks configuration:
allprojects {
tasks.withType(JavaCompile).all { JavaCompile compile ->
System.setProperty("line.separator", "\n") // <<<<<< add this line
compile.options.compilerArgs = [
'-processor', 'org.checkerframework.checker.nullness.NullnessChecker',
'-processorpath', "${configurations.checkerFramework.asPath}",
"-Xbootclasspath/p:${configurations.checkerFrameworkAnnotatedJDK.asPath}"
]
}
}
First of all i must say that problem was not in Checker Framework at all. I managed to reproduce the same behavior as mentioned in question without Checker Framework. I have created a little custom Annotation Processor. Here is the code:
#SupportedSourceVersion(value = SourceVersion.RELEASE_8)
#SupportedAnnotationTypes(value = {"*"})
public class MyProcessor extends AbstractProcessor{
#Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
String sepr = System.getProperty("line.separator");
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "[error code] " + sepr + " catched!!!");
return true;
}
}
As you can see, all it does is printing a message right away from start. Note that i used a line separator provided by java.lang.System class to split message. When i registered this processor and tried to run "gradle compileJava" from gradle project it produced the following output:
:compileJava
catched!!!
1 error
:compileJava FAILED
The property "line.separator" for Windows OS returns CR+LF: "\r\n". I don't know why Messager.printMessage(Diagnostic.Kind kind, CharSequence msg) has this behaviour, because when i type System.err.print("[error code] " + sepr + " catched!!!") instead, everything works fine (note also that this problem occur only when i use Gradle, if i run manually javac with all arguments or use Maven everyting is fine).
I found that if i substitude the provided by system separator with simple "\n" symbol compiler error messages are displayed correctly.
For now i choose this solution as a workaround.

Gradle extra property does not exist - defined in sub-module

I'm migrating maven build to gradle and I'm struggling with defining basic plugin configuration in the root project. And providing specific configuration properties in sub-module.
Here is an example:
root: build.gradle
configure(filterSubprojects(['component'])) {
apply plugin: "org.flywaydb.flyway"
flyway {
url = "jdbc:oracle:thin:#${db.host}:${db.port}:${db.name}"
user = db.owner.name
password = db.owner.password
}
}
specific-subproject-component: build.gradle
ext {
db = [
host : <host>,
port : <port>,
name : <name>,
user : [name: <user-name>, password: <user-password>]
]
}
I'm getting this error:
Cannot get property 'db' on extra properties extension as it does not exist
Probably very basic question, but I can't figure out how to do this.
The problem here is, that the specifics component build.gradle file was not yet evaluated when your root build.gradle file is evaluated, so db does indeed not yet exist when the configure block runs. To fix this you should be able to declare evaluationDependsOnChildren() in your root build.gradle file.

Android Studio: How to exclude Icon\r file?

Google Drive automatically generates Icon$'\r' in each synced folder in OSX. I'd like to exclude this file Icon$'r' recursively from compilation in Android Studio.
I tried #1 (din't work):
Adding !/**/Icon$'\r' and !/**/Icon' in the following field:
File -> Other Settings -> Default Settings
Build, Execution, Deployment -> Compiler
Resource patterns:
I tried #2 (didn't work):
Adding the following in build.gradle under module:
sourceSets {
main {
java {
srcDir 'src'
exclude '**/Icon$"\r"'
// exclude '**/Icon'
}
}
}
Note:
I already excluded Icon$'\r' in .gitignore
If Icon$'\r' is both excluded at compilation AND hidden, that'd be the best solution.

How can I create a pathing jar in Gradle

When running groovyc in a Windows env, I am running into issues due to the length of the classpath, in my situation. I would like to work around this by creating a pathing jar, and then put that jar on the cp. How can I create a pathing jar w/ all of the classpath entries specified automatically in gradle and then add that jar to the cp?
Here is a tested solution:
task pathingJar(type: Jar) {
appendix = "pathing"
doFirst {
manifest {
attributes "Class-Path": configurations.compile.files.join(" ")
}
}
}
compileGroovy {
dependsOn(pathingJar)
classpath = files(pathingJar.archivePath)
}
Depending on your exact requirements, you might have to tweak this a bit. For example, if you have tests written in Groovy, you will also need a pathing Jar for the test compile class path. In this case you'll need to repeat above configuration as follows:
task testPathingJar(type: Jar) {
appendix = "testPathing"
doFirst {
manifest {
attributes "Class-Path": configurations.testCompile.files.join(" ")
}
}
}
compileTestGroovy {
dependsOn(testPathingJar)
classpath = files(testPathingJar.archivePath)
}
I finally got the "pathing jar" idea to work. I consider this to be a permanent workaround. This could be considered a solution if it is made part of gradle itself.
The original pathing jar code was provided by Peter, but it didn't work. The problem: classpath elements referenced in the pathing jar must be relative to the location of the pathing jar. So, this appears to work for me.
task pathingJar(type: Jar , dependsOn: 'cleanPathingJar') {
/**
* If the gradle_user_home env var has been set to
* C:\ on a Win7 machine, we may not have permission to write the jar to
* this directory, so we will write it to the caches subdir instead.
* This assumes a caches subdir containing the jars
* will always exist.
*/
gradleUserHome = new File(gradle.getGradleUserHomeDir(), "caches")
relativeClasspathEntries = configurations.compile.files.collect {
new File(gradleUserHome.getAbsolutePath()).toURI().
relativize(new File(it.getAbsolutePath()).toURI()).getPath()
}
appendix = "pathing"
destinationDir = gradleUserHome
doFirst {
manifest {
attributes "Class-Path": relativeClasspathEntries.join(" ")
}
}
}
compileGroovy {
dependsOn(pathingJar)
classpath = files(pathingJar.archivePath)
}
This is what helped me:
"The filename or extension is too long error" using gradle
In other words: use the com.github.ManifestClasspath plugin.
The other solutions did not work for me because the actual project main class ended up no being included in the classpath at execution time.

How do you get the path of the running script in groovy?

I'm writing a groovy script that I want to be controlled via a properties file stored in the same folder. However, I want to be able to call this script from anywhere. When I run the script it always looks for the properties file based on where it is run from, not where the script is.
How can I access the path of the script file from within the script?
You are correct that new File(".").getCanonicalPath() does not work. That returns the working directory.
To get the script directory
scriptDir = new File(getClass().protectionDomain.codeSource.location.path).parent
To get the script file path
scriptFile = getClass().protectionDomain.codeSource.location.path
As of Groovy 2.3.0 the #SourceURI annotation can be used to populate a variable with the URI of the script's location. This URI can then be used to get the path to the script:
import groovy.transform.SourceURI
import java.nio.file.Path
import java.nio.file.Paths
#SourceURI
URI sourceUri
Path scriptLocation = Paths.get(sourceUri)
Note that this will only work if the URI is a file: URI (or another URI scheme type with an installed FileSystemProvider), otherwise a FileSystemNotFoundException will be thrown by the Paths.get(URI) call. In particular, certain Groovy runtimes such as groovyshell and nextflow return a data: URI, which will not typically match an installed FileSystemProvider.
This makes sense if you are running the Groovy code as a script, otherwise the whole idea gets a little confusing, IMO. The workaround is here: https://issues.apache.org/jira/browse/GROOVY-1642
Basically this involves changing startGroovy.sh to pass in the location of the Groovy script as an environment variable.
As long as this information is not provided directly by Groovy, it's possible to modify the groovy.(sh|bat) starter script to make this property available as system property:
For unix boxes just change $GROOVY_HOME/bin/groovy (the sh script) to do
export JAVA_OPTS="$JAVA_OPTS -Dscript.name=$0"
before calling startGroovy
For Windows:
In startGroovy.bat add the following 2 lines right after the line with
the :init label (just before the parameter slurping starts):
#rem get name of script to launch with full path
set GROOVY_SCRIPT_NAME=%~f1
A bit further down in the batch file after the line that says "set
JAVA_OPTS=%JAVA_OPTS% -Dgroovy.starter.conf="%STARTER_CONF%" add the
line
set JAVA_OPTS=%JAVA_OPTS% -Dscript.name="%GROOVY_SCRIPT_NAME%"
For gradle user
I have same issue when I'm starting to work with gradle. I want to compile my thrift by remote thrift compiler (custom by my company).
Below is how I solved my issue:
task compileThrift {
doLast {
def projectLocation = projectDir.getAbsolutePath(); // HERE is what you've been looking for.
ssh.run {
session(remotes.compilerServer) {
// Delete existing thrift file.
cleanGeneratedFiles()
new File("$projectLocation/thrift/").eachFile() { f ->
def fileName=f.getName()
if(f.absolutePath.endsWith(".thrift")){
put from: f, into: "$compilerLocation/$fileName"
}
}
execute "mkdir -p $compilerLocation/gen-java"
def compileResult = execute "bash $compilerLocation/genjar $serviceName", logging: 'stdout', pty: true
assert compileResult.contains('SUCCESSFUL')
get from: "$compilerLocation/$serviceName" + '.jar', into: "$projectLocation/libs/"
}
}
}
}
One more solution. It works perfect even you run the script using GrovyConsole
File getScriptFile(){
new File(this.class.classLoader.getResourceLoader().loadGroovySource(this.class.name).toURI())
}
println getScriptFile()
workaround: for us it was running in an ANT environment and storing some location parent (knowing the subpath) in the Java environment properties (System.setProperty( "dirAncestor", "/foo" )) we could access the dir ancestor via Groovy's properties.get('dirAncestor').
maybe this will help for some scenarios mentioned here.

Resources