How to pass parameters or arguments into a gradle task

前端 未结 6 2007
独厮守ぢ
独厮守ぢ 2020-12-29 00:41

I have a gradle build script into which I am trying to include Eric Wendelin\'s css plugin - http://eriwen.github.io/gradle-css-plugin/

Its easy enough to implement,

6条回答
  •  情歌与酒
    2020-12-29 01:46

    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 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

提交回复
热议问题