I'm trying to compile generated Kotlin source code in a custom location to a custom location so that I can build a jar file with those class file only.
I had no issues setting it up for Java. Unfortunately, I'm having problems with Kotlin.
So here is the Kotlin version of what worked for me in Java:
public class MyCustomPlugin implements Plugin<Project> {
private static final String GENERATED_STUB_CLASSES_DIRECTORY = "generated-stub-classes";
private static final String GENERATED_STUB_SOURCES_DIRECTORY = "generated-stub-sources";
public void apply(Project project) {
project.getPluginManager().apply(KotlinPluginWrapper.class);
createCompileStubsTask(project);
}
private void createCompileStubsTask(final Project project) {
KotlinCompile compileKotlin = (KotlinCompile) project.getRootProject().getTasksByName("compileKotlin", true).iterator().next();
TaskProvider<KotlinCompile> compileKotlinStubs = project.getTasks().register("compileStubs", KotlinCompile.class,
compileStubs -> {
File stubsClassesDir = new File(project.getBuildDir() + "/" + GENERATED_STUB_CLASSES_DIRECTORY);
stubsClassesDir.mkdirs();
compileStubs.setClasspath(compileKotlin.getClasspath());
compileStubs.source(project.getLayout().getBuildDirectory().dir(GENERATED_STUB_SOURCES_DIRECTORY));
compileStubs.getDestinationDirectory().set(stubsClassesDir);
});
compileKotlin.finalizedBy(compileKotlinStubs);
}
}
This fails with:
Unable to determine constructor argument #1: missing parameter of type KotlinJvmOptions, or no service of type KotlinJvmOptions.
I tried to do it in the build.gradle file, like this:
task compileStubs(type: org.jetbrains.kotlin.gradle.tasks.KotlinCompile) {
File stubsClassesDir = new File(project.getBuildDir().name + "/generated-stub-classes")
stubsClassesDir.mkdirs()
compileStubs.setClasspath(compileKotlin.getClasspath())
compileStubs.source(project.getLayout().getBuildDirectory().dir("generated-stub-sources"))
compileStubs.getDestinationDirectory().set(stubsClassesDir)
}
compileKotlin.finalizedBy(compileKotlinStubs)
But the result is exactly the same.
Please help...
Apparently there's no support for metarunners generation in TeamCity Kotlin DSL. The files remain in plain XML.
How do I replace it using available DSL features? Say I'd like to do this:
steps {
step {
type = "mymetarunner" // compound meta-runner step
}
}
How do I define mymetarunner using Kotlin?
At the moment (TeamCity 2017.2), there is no way to define metarunners using Kotlin DSL.
Update
If having a real metarunner is not required, the solution is a small exercise in Kotlin DSL
Define a container class for settings you need for "metarunner"
class MyConfigClass {
var name = "Default Name"
var goals = "build"
var tasks = "build test"
var someUnusedProperty = 0
}
Define an extension function for steps block
fun BuildSteps.myMetaRunner(config: MyConfigClass.() -> Unit) {
val actualConfig = MyConfigClass() // new config instance
actualConfig.config() // apply closure to fill the config
// use the config to create actual steps
maven {
name = actualConfig.name
goals = actualConfig.goals
}
ant {
name = actualConfig.tasks
}
}
Use the extension function wherever you need
object A_Build : BuildType({
uuid = ...
steps {
myMetaRunner {
name = "This name will be used by maven step"
goals = "build whatever_goal"
tasks = "more ant tasks"
}
}
})
Bingo!
I'm new to IntelliJ and working on a big project with hundreds of modules, I was just wondering how would I get the classpath for a specific module?
It might help you. Because each module has its own independent classpath. You can combine the classpaths of all modules in the project, and that's what that method did, but trying to use that classpath is unlikely to result in correct behavior in multi-module projects.
public static String getFullClassPath(Module m){
String cp = "";
cp += CompilerPaths.getModuleOutputPath(m,false);
for(VirtualFile vf : OrderEnumerator.orderEntries(m).recursively().getClassesRoots()){
String entry = new File(vf.getPath()).getAbsolutePath();
if(entry.endsWith("!/")){ //not sure why it happens in the returned paths
entry = entry.substring(0,entry.length()-2);
}
if(entry.endsWith("!")){
entry = entry.substring(0,entry.length()-1);
}
cp += File.pathSeparator + entry;
}
return cp;
}
I have a Gradle build script into which I am trying to include Eric Wendelin's CSS plugin.
It's easy enough to implement, and because I only want minification (rather than combining and gzipping), I've got the pertinent parts of the build script looking like this:
minifyCss {
source = "src/main/webapp/css/brandA/styles.css"
dest = "${buildDir}/brandA/styles.css"
yuicompressor {
lineBreakPos = -1
}
}
war {
baseName = 'ex-ren'
}
war.doFirst {
tasks.myTask.minifyCss.execute()
}
This is perfect - when I run the gradle war task, it calls the minifyCss task, takes the source css file, and creates a minified version in the buildDir
However, I have a handful of css files which need minify-ing, but not combining into one file (hence I'm not using the combineCss task)
What I'd like to be able to do is make the source and dest properties (assuming that's the correct terminology?) of the minifyCss task reference variables of some sort - either variables passed into the task in the signature, or global variables, or something ...
Something like this I guess (which doesn't work):
minifyCss(sourceFile, destFile) {
source = sourceFile
dest = destFile
yuicompressor {
lineBreakPos = -1
}
}
war {
baseName = 'ex-ren'
}
war.doFirst {
tasks.myTask.minifyCss.execute("src/main/webapp/css/brandA/styles.css", "${buildDir}/brandA/styles.css")
tasks.myTask.minifyCss.execute("src/main/webapp/css/brandB/styles.css", "${buildDir}/brandB/styles.css")
tasks.myTask.minifyCss.execute("src/main/webapp/css/brandC/styles.css", "${buildDir}/brandC/styles.css")
}
This doesn't work either:
def sourceFile = null
def destFile = null
minifyCss {
source = sourceFile
dest = destFile
yuicompressor {
lineBreakPos = -1
}
}
war {
baseName = 'ex-ren'
}
war.doFirst {
sourceFile = "src/main/webapp/css/brandA/styles.css"
destFile = "${buildDir}/brandA/styles.css"
tasks.myTask.minifyCss.execute()
}
For the life of me I cannot work out how to call a task and pass variables in :(
Any help very much appreciated;
You should consider passing the -P argument in invoking Gradle.
From Gradle Documentation :
--project-prop
Sets a project property of the root project, for example -Pmyprop=myvalue. See Section 14.2, “Gradle properties and system properties”.
Considering this build.gradle
task printProp << {
println customProp
}
Invoking Gradle -PcustomProp=myProp will give this output :
$ gradle -PcustomProp=myProp printProp
:printProp
myProp
BUILD SUCCESSFUL
Total time: 3.722 secs
This is the way I found to pass parameters.
If the task you want to pass parameters to is of type JavaExec and you are using Gradle 5, for example the application plugin's run task, then you can pass your parameters through the --args=... command line option. For example gradle run --args="foo --bar=true".
Otherwise there is no convenient builtin way to do this, but there are 3 workarounds.
1. If few values, task creation function
If the possible values are few and are known in advance, you can programmatically create a task for each of them:
void createTask(String platform) {
String taskName = "myTask_" + platform;
task (taskName) {
... do what you want
}
}
String[] platforms = ["macosx", "linux32", "linux64"];
for(String platform : platforms) {
createTask(platform);
}
You would then call your tasks the following way:
./gradlew myTask_macosx
2. Standard input hack
A convenient hack is to pass the arguments through standard input, and have your task read from it:
./gradlew myTask <<<"arg1 arg2 arg\ in\ several\ parts"
with code below:
String[] splitIntoTokens(String commandLine) {
String regex = "(([\"']).*?\\2|(?:[^\\\\ ]+\\\\\\s+)+[^\\\\ ]+|\\S+)";
Matcher matcher = Pattern.compile(regex).matcher(commandLine);
ArrayList<String> result = new ArrayList<>();
while (matcher.find()) {
result.add(matcher.group());
}
return result.toArray();
}
task taskName, {
doFirst {
String typed = new Scanner(System.in).nextLine();
String[] parsed = splitIntoTokens(typed);
println ("Arguments received: " + parsed.join(" "))
... do what you want
}
}
You will also need to add the following lines at the top of your build script:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;
3. -P parameters
The last option is to pass a -P parameter to Gradle:
./gradlew myTask -PmyArg=hello
You can then access it as myArg in your build script:
task myTask {
doFirst {
println myArg
... do what you want
}
}
Credit to #789 for his answer on splitting arguments into tokens
I would suggest the method presented on the Gradle forum:
def createMinifyCssTask(def brand, def sourceFile, def destFile) {
return tasks.create("minify${brand}Css", com.eriwen.gradle.css.tasks.MinifyCssTask) {
source = sourceFile
dest = destFile
}
}
I have used this method myself to create custom tasks, and it works very well.
task mathOnProperties << {
println Integer.parseInt(a)+Integer.parseInt(b)
println new Integer(a) * new Integer(b)
}
$ gradle -Pa=3 -Pb=4 mathOnProperties
:mathOnProperties
7
12
BUILD SUCCESSFUL
Its nothing more easy.
run command: ./gradlew clean -PjobId=9999
and
in gradle use: println(project.gradle.startParameter.projectProperties)
You will get clue.
I think you probably want to view the minification of each set of css as a separate task
task minifyBrandACss(type: com.eriwen.gradle.css.tasks.MinifyCssTask) {
source = "src/main/webapp/css/brandA/styles.css"
dest = "${buildDir}/brandA/styles.css"
}
etc etc
BTW executing your minify tasks in an action of the war task seems odd to me - wouldn't it make more sense to make them a dependency of the war task?
Here is a solution for Kotlin DSL (build.gradle.kts).
I first try to get the variable as a property and if it was null try to get it from OS environment variables (can be useful in CIs like GitHub Actions).
tasks.create("MyCustomTask") {
val songName = properties["songName"]
?: System.getenv("SONG_NAME")
?: error("""Property "songName" or environment variable "SONG_NAME" not found""")
// OR getting the property with 'by'. Did not work for me!
// For this approach, name of the variable should be the same as the property name
// val songName: String? by properties
println("The song name: $songName")
}
We can then pass a value for the property from command line:
./gradlew MyCustomTask -PsongName="Black Forest"
Or create a file named local.properties at the root of the project and set the property:
songName=Black Forest
We can also add an env variable named SONG_NAME with our desired value and then run the task:
./gradlew MyCustomTask
Can I implement Eclipse RCP UI using java code only and not plugin.xml?
While it might be possible in theory (eclipse plugins are OSGi bundle which are read by the extension registry), I don't think it is practical (unless you re-implement the extension registry lifecycle).
Eclipse Equinox precisely extends the concept of bundles with the concept of extension points, hence the mandatory presence of plugin.xml.
You can programmatically add and remove extensions. See following example methods (adapt on demand):
public void addExtension() throws UnsupportedEncodingException {
String pluginXmlAsString = "<a string with the content of plugin.xml";
InputStream pluginXmlIs = new ByteArrayInputStream(pluginXmlAsString.getBytes(StandardCharsets.UTF_8.name()));
IExtensionRegistry extensionRegistry = Platform.getExtensionRegistry();
Object token = ((ExtensionRegistry) extensionRegistry).getTemporaryUserToken();
IContributor contributor = ContributorFactoryOSGi.createContributor(Platform.getBundle("org.acme.mybundle"));
extensionRegistry.addContribution(pluginXmlIs, contributor, false, null, null, token);
}
public static void removeExtensionsContributedByMe() {
String extensionPointId = "<ID of the extension point for remove an extension of";
String extensionContributor = "org.acme.mybundle";
ExtensionRegistry extensionRegistry = (ExtensionRegistry) Platform.getExtensionRegistry();
IExtensionPoint extensionPoint = extensionRegistry.getExtensionPoint(extensionPointId);
IExtension[] extensions = extensionPoint.getExtensions();
Object token = extensionRegistry.getTemporaryUserToken();
for (IExtension extension : extensions) {
if (extensionContributor.equals(extension.getContributor().getName())) {
extensionRegistry.removeExtension(extension, token);
}
}
}
We use this for unit tests which add extensions as preparation and remove extension to clean up. This way the tests do not influence each other (which would be the case if the extensions are "hard coded" in plugin.xml or fragment.xml).