Scan directories in groovy with ant builder file scanner - groovy

I want to use fileScanner of AntBuilder to go over directories.
My code looks like:
scanner = new AntBuilder().fileScanner {
fileset(dir:sourcedir, casesensitive:false) {
include(name:pattern)
type(type:'dir')
}
}
I want to loop with the scanner just on directories, for example:
for (file in scanner) {
assert file.directory == true
}
Any idea ?
Thanks!!!!!!!!

Here's how to do it with fileScanner
scanner = new AntBuilder().fileScanner {
fileset(dir:sourcedir, casesensitive:false) {
include(name:pattern)
}
}
// Just the directories
scanner.directories().each {
println it.name
}
You could also do it with Groovy calls:
def dirs = []
new File( sourcedir ).eachDirRecurse {
// Check the name here, obviously the Ant pattern you have probably won't work
if( it.name ==~ pattern ) dirs << it
}
dirs.each {
println it.name
}

Related

How to use an if statement with match expresion in Groovy

I have the following groovy code where /data/JarFiles/ contain many .jar files and /data/XML/Platform/ contain some xml files used to launch the jar:
Jar=[]
path = "/data/JarFiles"
new File(path).eachFileMatch(~/.*.jar/) {
Jar.add(it)
}
return Jar.sort{it.lastModified()}.collect{it.name}.reverse()
if (Jar.equals("Core2_v4.1.6.jar") && Product.equals("maximus")) {
Platform=[]
path2 = "/data/XML/Platform/"
new File(path2).eachFileMatch(~/.*K6_Platform.*/) {
Platform.add(it.getName())
}
return Platform.sort()
I want to do something like this:
...
if (Jar.Match(~/.*Core2_v4.*/) && Product.equals("maximus")) {
...
Can somebody help me with this please?
Thank you!
here is the sample that works fine
def Jar = ['sdfgsdfg', 'Core2_v4.1.jar', 'aaa', 'bbb']
def Product = "maximus"
if( Jar.find{it=~/Core2_v4/} && Product=="maximus" ){
println "OK"
}else{
println "Failed"
}
The solution that works perfectly for me is:
Jar=[]
path = "/data/JarFiles"
new File(path).eachFileMatch(~/.*.jar/) {
Jar.add(it)
}
return Jar.sort{it.lastModified()}.collect{it.name}.reverse()
if (Jar=~/Core2_v4/) && Product.equals("maximus")) {
Platform=[]
path2 = "/data/XML/Platform/"
new File(path2).eachFileMatch(~/.*K6_Platform.*/) {
Platform.add(it.getName())
}
return Platform.sort()

groovy print environments from groovy.config

how do I print available environments from a config file? What is the form of the ojbect ConfigSlurper creates?
I tried
def config2 = new ConfigSlurper().parse(new File('obieeadmincfg.groovy').toURL())
config2.config.environments.each { println ${it} }
and
println prettyPrint(toJson(config2))
and
for ( i in 0 ..config2.config.environments.size()-1)
println config2.config.environments[i]
groovy.config
//Config3.groovy
obieadmin {
//default values
serverurl = "http://default.mycompany.com"
}
environments {
pldev01 {
obieeadmin {
serverurl = 'devgdwobi03.x.com'
}
}
plsbx02 {
obieeadmin {
serverurl = 'devgdwobi03.x.com'
}
}
}
I'm afraid you can't do this out-of box.
But using a bit of Groovy Metaprogramming it's achievable.
Groovy config slurper parses proper Groovy file, and you can do the same with GroovyShell. You can catch call to environment method providing closure in binding. In that closure you have to collect all top-level method calls(with same methodMissing).
Providing base script with property and method missing handlers, you can suppress runtime errors, and execute script without much care to other properties.
Not the nicest path, but it works.
package test
import org.codehaus.groovy.control.CompilerConfiguration
class A extends Script {
def propertyMissing(String name) { null }
def propertyMissing(String name, def arg) {}
def methodMissing(String name, def args) {}
#Override Object run() { null }
}
class NameCollector {
def envs = []
def methodMissing(String name, def args) { envs << name }
}
// configure interceptors.
def configuration = new CompilerConfiguration()
configuration.scriptBaseClass = 'test.A'
def nc = new NameCollector()
def environments = { Closure it ->
it.delegate = nc;
it.resolveStrategy = Closure.DELEGATE_ONLY
it()
}
// execute config script
new GroovyShell([environments: environments] as Binding, configuration).evaluate(new File("config.groovy"))
nc.envs // Return, print them.
Not sure if this is going to work forever but currently you can do it by overriding the setting for the 'environments' conditional block, like this:
def config = """environments {
dev {
foo = "bar"
}
prod {
foo = "baz"
}
}"""
def configSlurper = new ConfigSlurper()
configSlurper.registerConditionalBlock('environments', null)
assert configSlurper.parse(config).environments.keySet() == ['dev', 'prod'].toSet()

Load property from external file into build.gradle

I have this:
def loadProperties(String sourceFileName) {
def config = new Properties()
def propFile = new File(sourceFileName)
if (propFile.canRead()) {
config.load(new FileInputStream(propFile))
for (Map.Entry property in config) {
ext[property.key] = property.value;
}
}
}
loadProperties 'gradle.properties'
How do I reference the property (ndk.dir) in build.gradle?
def ndkBuild = new File("$ndk.dir", 'ndk-build')
And is there a better way of reading ndk.dir from file gradle.properties?
And how do I use it in?
def ndkBuild = new File("$ndk.dir", 'ndk-build')
Full code:
task buildNative(type: Exec) {
loadProperties 'gradle.properties'
if (System.getenv('NDK_HOME') != null || "$ndk.dir" != null) {
if ("$ndk.dir" != null) {
def ndkBuild = new File("$ndk.dir", 'ndk-build')
} else {
def ndkBuild = new File(System.getenv('NDK_HOME'), 'ndk-build')
}
workingDir "jni"
executable ndkBuild
} else {
throw new GradleException('Reason: NDK_HOME not set or ndk.dir is missing in gradle.properties...')
}
}
def loadProperties(String sourceFileName) {
def config = new Properties()
def propFile = new File(sourceFileName)
if (propFile.canRead()) {
config.load(new FileInputStream(propFile))
for (Map.Entry property in config) {
ext[property.key] = property.value;
}
}
}
Just like ndk.dir, "$ndk.dir" first gets the ndk property, and then the dir property, which is not what you want. (This is also evident in the error message, which says "Could not find property 'ndk'".) Instead, this should work:
def ndkBuild = new File(project.property('ndk.dir'), 'ndk-build')
A safer solution is to store the whole Properties object as a single extra property:
...
ext.externalProps = config
Then you can access external properties like so:
def ndkBuild = new File(externalProps['ndk.dir'], 'ndk-build')

Gradle: Force Custom Task to always run (no cache)

I wrote up a custom Gradle task to handle some dependency resolution on the file system where the paths are configurable. I want tasks of this type to always run. It seems though they only run once, I'm guessing because the inputs never seem to change.
I am aware of using configurations { resolutionStrategy.cacheChangingModulesFor 0, 'seconds' } to effectively disable the cache, but I only want it to apply to very specific tasks. Also am aware of --rerun-tasks command line prompt, which is also similar. Neither feel like the best solution, there must be a way to set this up properly in the custom task definition.
Follows is my current implementation. I also had a version prior where the first 3 def String statements were instead #Input annotated String declarations.
class ResolveProjectArchiveDependency extends DefaultTask {
def String archiveFilename = ""
def String relativeArchivePath = ""
def String dependencyScope = ""
#OutputFile
File outputFile
#TaskAction
void resolveArtifact() {
def arcFile = project.file("dependencies/"+dependencyScope+"/"+archiveFilename)
def newArcFile = ""
if(project.hasProperty('environmentSeparated') && project.hasProperty('separatedDependencyRoot')){
println "Properties set denoting the prerelease environment is separated"
newArcFile = project.file(project.ext.separatedDependencyRoot+relativeArchivePath+archiveFilename)
} else {
newArcFile = project.file('../../'+relativeArchivePath+archiveFilename)
}
if(!newArcFile.isFile()){
println "Warn: Could not find the latest copy of " + archiveFilename + ".."
if(!arcFile.isFile()) {
println "Error: No version of " + archiveFilename + " can be found"
throw new StopExecutionException(archiveFilename +" missing")
}
}
if(!arcFile.isFile()) {
println archiveFilename + " jar not in dependencies, pulling from archives"
} else {
println archiveFilename + " jar in dependencies. Checking for staleness"
def oldHash = generateMD5(new File(arcFile.path))
def newHash = generateMD5(new File(newArcFile.path))
if(newHash.equals(oldHash)) {
println "Hashes for the jars match. Not pulling in a copy"
return
}
}
//Copy the archive
project.copy {
println "Copying " + archiveFilename
from newArcFile
into "dependencies/"+dependencyScope
}
}
def generateMD5(final file) {
MessageDigest digest = MessageDigest.getInstance("MD5")
file.withInputStream(){is->
byte[] buffer = new byte[8192]
int read = 0
while( (read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
}
}
byte[] md5sum = digest.digest()
BigInteger bigInt = new BigInteger(1, md5sum)
return bigInt.toString(16)
}
}
Here's an example of usage of the task:
task handleManagementArchive (type: com.moremagic.ResolveProjectArchiveDependency) {
archiveFilename = 'management.jar'
relativeArchivePath = 'management/dist/'
dependencyScope = 'compile/archive'
outputFile = file('dependencies/'+dependencyScope+'/'+archiveFilename)
}
You can achieve this by setting outputs.upToDateWhen { false } on the task.
This can be performed in your build.gradle file:
handleManagementArchive.outputs.upToDateWhen { false }
It can also be done in the constructor of your custom task.
ResolveProjectArchiveDependency() {
outputs.upToDateWhen { false }
}

How to use not equalto in Groovy in this case

I just want to print files which are not located in ss
def folder = "./test-data"
// println "reading files from directory '$folder'"
def basedir = new File(folder)
basedir.traverse {
if (it.isFile()) {
def rec = it
// println it
def ss = rec.toString().substring(12)
if(!allRecords contains(ss)) {
println ss
}
}
Your question isn't exactly clear, but it looks like you're just trying to do
if (!allRecords.contains(ss)) {
println ss
}
in the last part of your code segment.

Resources