명령 줄에서 Gradle로 인수를 전달하는 방법
명령 줄에서 Java 클래스로 인수를 전달하려고합니다. 이 게시물 다음 : http://gradle.1045684.n5.nabble.com/Gradle-application-plugin-question-td5539555.html을 하지만 코드는 (아마도이 JavaExec를 위해 의미되지 않는 이유는 무엇입니까?) 나를 위해 작동하지 않습니다. 내가 시도한 것은 다음과 같습니다.
task listTests(type:JavaExec){
main = "util.TestGroupScanner"
classpath = sourceSets.util.runtimeClasspath
// this works...
args 'demo'
/*
// this does not work!
if (project.hasProperty("group")){
args group
}
*/
}
위의 하드 코딩 된 args 값의 출력은 다음과 같습니다.
C:\ws\svn\sqe\sandbox\selenium2forbg\testgradle>g listTests
:compileUtilJava UP-TO-DATE
:processUtilResources UP-TO-DATE
:utilClasses UP-TO-DATE
:listTests
Received argument: demo
BUILD SUCCESSFUL
Total time: 13.422 secs
그러나 hasProperty 섹션을 사용하도록 코드를 변경하고 명령 줄에서 "demo"를 인수로 전달하면 NullPointerException이 발생합니다.
C:\ws\svn\sqe\sandbox\selenium2forbg\testgradle>g listTests -Pgroup=demo -s
FAILURE: Build failed with an exception.
* Where:
Build file 'C:\ws\svn\sqe\sandbox\selenium2forbg\testgradle\build.gradle' line:25
* What went wrong:
A problem occurred evaluating root project 'testgradle'.
> java.lang.NullPointerException (no error message)
* Try:
Run with --info or --debug option to get more log output.
* Exception is:
org.gradle.api.GradleScriptException: A problem occurred evaluating root project
'testgradle'.
at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:54)
at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:127)
at org.gradle.configuration.BuildScriptProcessor.evaluate(BuildScriptProcessor.java:38)
http://gradle.1045684.n5.nabble.com/file/n5709919/testgradle.zip 에서 문제를 설명 하는 간단한 테스트 프로젝트가 있습니다 .
이것은 Gradle 1.0-rc-3을 사용하고 있습니다. NullPointer는 다음 코드 줄에서 가져옵니다.
args group
I added the following assignment before the task definition, but it didn't change the outcome:
group = hasProperty('group') ? group : 'nosuchgroup'
Any pointers on how to pass command line arguments to gradle appreciated.
project.group
is a predefined property. With -P
, you can only set project properties that are not predefined. Alternatively, you can set Java system properties (-D
).
Building on Peter N's answer, this is an example of how to add (optional) user-specified arguments to pass to Java main for a JavaExec task (since you can't set the 'args' property manually for the reason he cites.)
Add this to the task:
task(runProgram, type: JavaExec) {
[...]
if (project.hasProperty('myargs')) {
args(myargs.split(','))
}
... and run at the command line like this
% ./gradlew runProgram '-Pmyargs=-x,7,--no-kidding,/Users/rogers/tests/file.txt'
My program with two arguments, args[0] and args[1]:
public static void main(String[] args) throws Exception {
System.out.println(args);
String host = args[0];
System.out.println(host);
int port = Integer.parseInt(args[1]);
my build.gradle
run {
if ( project.hasProperty("appArgsWhatEverIWant") ) {
args Eval.me(appArgsWhatEverIWant)
}
}
my terminal prompt:
gradle run -PappArgsWhatEverIWant="['localhost','8080']"
As of Gradle 4.9 Application plugin understands --args
option, so passing the arguments is as simple as:
build.gradle
plugins {
id 'application'
}
mainClassName = "my.App"
src/main/java/my/App.java
public class App {
public static void main(String[] args) {
System.out.println(args);
}
}
bash
./gradlew run --args='This string will be passed into my.Class arguments'
It's possible to utilize custom command line options in Gradle to end up with something like:
/.gradlew printPet --pet="puppies!"
However, custom command line options in Gradle are an incubating feature.
Java solution
To end up with something like this follow the instructions here:
import org.gradle.api.tasks.options.Option;
public class PrintPet extends DefaultTask {
private String pet;
@Option(option = "pet", description = "Name of the cute pet you would like to print out!")
public void setPet(String pet) {
this.pet = pet;
}
@Input
public String getPet() {
return pet;
}
@TaskAction
public void print() {
getLogger().quiet("'{}' are awesome!", pet);
}
}
Then register it:
task printPet(type: PrintPet)
Now you can do:
./gradlew printPet --pet="puppies"
output:
Puppies! are awesome!
Kotlin solution
open class PrintPet : DefaultTask() {
@Suppress("UnstableApiUsage")
@set:Option(option = "pet", description = "The cute pet you would like to print out")
@get:Input
var pet: String = ""
@TaskAction
fun print() {
println("$pet are awesome!")
}
}
then register the task with:
tasks.register<PrintPet>("printPet")
I have written a piece of code that puts the command line arguments in the format that gradle expects.
// this method creates a command line arguments
def setCommandLineArguments(commandLineArgs) {
// remove spaces
def arguments = commandLineArgs.tokenize()
// create a string that can be used by Eval
def cla = "["
// go through the list to get each argument
arguments.each {
cla += "'" + "${it}" + "',"
}
// remove last "," add "]" and set the args
return cla.substring(0, cla.lastIndexOf(',')) + "]"
}
my task looks like this:
task runProgram(type: JavaExec) {
if ( project.hasProperty("commandLineArgs") ) {
args Eval.me( setCommandLineArguments(commandLineArgs) )
}
}
To pass the arguments from the command line you run this:
gradle runProgram -PcommandLineArgs="arg1 arg2 arg3 arg4"
If you need to check and set one argument, your build.gradle
file would be like this:
....
def coverageThreshold = 0.15
if (project.hasProperty('threshold')) {
coverageThreshold = project.property('threshold').toString().toBigDecimal()
}
//print the value of variable
println("Coverage Threshold: $coverageThreshold")
...
And the Sample command in windows:
gradlew clean test -Pthreshold=0.25
pass a url from command line keep your url in app gradle file as follows resValue "string", "url", CommonUrl
and give a parameter in gradle.properties files as follows CommonUrl="put your url here or may be empty"
and pass a command to from command line as follows gradle assembleRelease -Pcommanurl=put your URL here
참고URL : https://stackoverflow.com/questions/11696521/how-to-pass-arguments-from-command-line-to-gradle
'developer tip' 카테고리의 다른 글
JUnit과 Hamcrest를 함께 사용하는 방법은 무엇입니까? (0) | 2020.09.14 |
---|---|
clearfix 클래스는 CSS에서 무엇을합니까? (0) | 2020.09.14 |
JSDoc에서 매개 변수 또는 반환 값으로 객체 배열을 지정하는 방법은 무엇입니까? (0) | 2020.09.14 |
void *에 대한 합법적 인 사용이 있습니까? (0) | 2020.09.14 |
자바 스크립트를 사용하여 테이블 만들기 (0) | 2020.09.13 |