How to replace text in files using Gradle/Groovy functionality - groovy

I am trying to work around the problem described in GRADLE-2293 where generated files are always updated because a timestamp is written to the Eclipse files located in directory .settings by the Gradle plugin which generates the Eclipse project files.
The files contain a header like this which I would like to remove
#
#Fri Mar 27 10:26:55 CET 2015
Currently I am using an Exec task to use the external application sed to cut out lines starting with '#':
task adjustEclipseSettingsFile(type: Exec) {
executable 'sed'
args '-i','-e','s/^#.*//g','.settings/org.eclipse.jdt.core.prefs'
}
eclipseJdt.finalizedBy adjustEclipseSettingsFile
however this adds a dependency on operating system binaries that I would like to avoid.
How can I do this simple removal of lines starting with '#' in a Gradle task without calling external tools?

There are really many ways of doing it, the one with ant is probably most reliable:
task removeLines << {
ant.replaceregexp(match:'^#.*', replace:'', flags:'g', byline:true) {
fileset(dir: project.projectDir, includes: 'lol')
}
}

Related

Why is Gradle failing on :linkDebugTestLinux in my Kotlin multiplatform project?

I'm porting a C# library to Kotlin to take advantage of multiplatform. When running the build task, it fails in the subtask linkDebugTestLinux.
For context, I'm using IDEA Ultimate on Manjaro. I'm certain there's nothing wrong with my code as compileKotlinLinux finishes without error.
There are zero DDG results for "linkDebugTestLinux" and nothing helpful for "konan could not find home" or "kotlin native ...". After hours of stitching together incomplete and outdated examples from the official docs, I've given up.
My build.gradle.kts:
plugins {
kotlin("multiplatform") version "1.3.40"
}
repositories {
mavenCentral()
}
dependencies {
commonMainImplementation("org.jetbrains.kotlin:kotlin-stdlib")
commonTestImplementation("org.jetbrains.kotlin:kotlin-test-common")
commonTestImplementation("org.jetbrains.kotlin:kotlin-test-annotations-common")
}
kotlin {
// js() // wasn't the issue
linuxX64("linux")
}
Output of task build without args:
> Configure project :
Kotlin Multiplatform Projects are an experimental feature.
> Task :compileKotlinLinux
[...unused param warnings...]
> Task :compileKotlinMetadata
[...unused param warnings...]
> Task :metadataMainClasses
> Task :metadataJar
> Task :assemble
> Task :linuxProcessResources NO-SOURCE
> Task :linuxMainKlibrary
> Task :linkDebugTestLinux FAILED
e: Could not find "/home/username/" in [/home/username/path/to/the/repo, /home/username/.konan/klib, /home/username/.konan/kotlin-native-linux-1.3/klib/common, /home/username/.konan/kotlin-native-linux-1.3/klib/platform/linux_x64].
[...snip...]
BUILD FAILED in 16s
4 actionable tasks: 4 executed
Process 'command '/usr/lib/jvm/java-8-openjdk/bin/java'' finished with non-zero exit value 1
In the boilerplate I omitted it suggests to use --debug, so I've uploaded that here.
After some investigation, it was assumed that the problem is in the path. In the debug log, you got the /home/yoshi/,/ fragment. As far as this directory name was unexpected, the compiler interpreted this , as a delimiter between lib names. So, it tried to find library /home/yoshi/, that was obviously unavailable.
For now, I would recommend you to change the directory name to be something trivial.

Copy and .# in file name

I faced with one gradle issue (or may be groovy related)
When I trying to copy file with .# in its name nothing is happened.
Example:
task c(type: Copy) {
from (".#webclasspath#")
into "destdir"
}
Please, could you provide way how to process such files?
seems that there is a bug in gradle, ant works just fine
task c_ant << {
ant.copy(file : '.#webclasspath#', todir : 'destdir')
}

Unable to locate sound file (.ogg)

I have a method called setSound() which is setting up a queue and adding a track to it and then playing it. I call the method in simpleInitGame(). However no sound plays and the console in eclipse says:
Mar 13, 2012 10:15:55 PM com.jmex.audio.openal.OpenALSystem setupSourcePool
INFO: max source channels: 32
Mar 13, 2012 10:15:55 PM com.jme.util.resource.ResourceLocatorTool locateResource
WARNING: Unable to locate: src/com/preston/sounds/background.ogg
Mar 13, 2012 10:15:55 PM com.jmex.audio.openal.OpenALSystem createAudioTrack
WARNING: Could not locate audio file: src/com/preston/sounds/background.ogg
Here is the method:
protected void setSound()
{
audio = AudioSystem.getSystem();
sound1 = audio.createAudioTrack("src/com/preston/sounds/background.ogg", false);
queue = AudioSystem.getSystem().getMusicQueue();
queue.setCrossfadeinTime(0);
queue.setRepeatType(RepeatType.ONE);
queue.addTrack(sound1);
queue.play();
}
I don't think it's the directory as my textures are in the same directory (except instead of preston/sounds its preston/textures).
this is most probably a problem with your relative path. The default directory of the ResourceLocatorTool in jMonkeyEngine is not the root of your project. Try to open it with an absolute path and see if it works.
Also, the location of your file is not a wise choice. The src folder is intended for java source files, not resources. You should put them in assets/Sounds. See jME best practices
Most likely you can omit the "src/" prefix. The Eclipse compiler will compile all java files into class files and in addition copy the resources from your sources to "bin/".
I think JME then uses ClassLoader.getResourceAsStream(...) to load assets from the classpath. So, try removing "src/".

Problem on obfuscating j2me applications in Netbeans 6.8

When I'm trying to package a midlet with obfuscation, the following is displayed on the output window:
pre-init:
pre-load-properties:
exists.config.active:
exists.netbeans.user:
exists.user.properties.file:
load-properties:
exists.platform.active:
exists.platform.configuration:
exists.platform.profile:
basic-init:
cldc-pre-init:
cldc-init:
cdc-init:
ricoh-pre-init:
ricoh-init:
semc-pre-init:
semc-init:
savaje-pre-init:
savaje-init:
sjmc-pre-init:
sjmc-init:
cdc-hi-pre-init:
cdc-hi-init:
nokiaS80-pre-init:
nokiaS80-init:
nsicom-pre-init:
nsicom-init:
post-init:
init:
conditional-clean-init:
conditional-clean:
deps-jar:
pre-preprocess:
do-preprocess:
Pre-processing 0 file(s) into C:\Meljean's Files\NetBeansProjects\SampleApp\build\preprocessed directory.
post-preprocess:
preprocess:
pre-compile:
extract-libs:
Expanding: C:\Meljean's Files\LWUIT_1_4\lib\LWUIT.jar into C:\Meljean's Files\NetBeansProjects\SampleApp\build\compiled
do-compile:
post-compile:
compile:
pre-obfuscate:
proguard-init:
skip-obfuscation:
proguard:
Error: Expecting class path separator ';' before 's' in argument number 4
C:\Meljean's Files\NetBeansProjects\SampleApp\nbproject\build-impl.xml:427: Obfuscation failed with error code 1.
BUILD FAILED (total time: 0 seconds)
What am I going to do?
Problem might be in the WTK's installation dir.
Lets confirm this:
I guess you are using WIN SYSTEM
I guess your WTK is installed at the path where space comes inbetween.
like for ex : c:\program files\ [space between program & files]
I would suggest you to install WTK on non space dir like c:\WTK
Let me know if this is not the case.

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