本文以在command窗口執行最簡單的 gradle -v 爲例子說明
從上文提到的EntryPoint.java開始,調用該類的doAction</p><p>實際調用到Main.java 的doAction
<pre name="code" class="java"> protected void doAction(String[] args, ExecutionListener listener) {
createActionFactory().convert(Arrays.asList(args)).execute(listener);
}
CommandLineActionFactory createActionFactory() {return new CommandLineActionFactory();
}
convert是一個很重要的函數,
* <p>Converts the given command-line arguments to an {@link Action} which performs the action requested by the
* command-line args.
public Action<ExecutionListener> convert(List<String> args) {
ServiceRegistry loggingServices = createLoggingServices();
LoggingConfiguration loggingConfiguration = new LoggingConfiguration();
return new ExceptionReportingAction(
new WithLogging(loggingServices, args, loggingConfiguration,
new JavaRuntimeValidationAction(
new ParseAndBuildAction(loggingServices, args))),
new BuildExceptionReporter(loggingServices.get(StyledTextOutputFactory.class), loggingConfiguration, clientMetaData()));
}
在convert函數中, 把
ExceptionReportingAction, WithLogging, ParseAndBuildAction 和 <pre name="code" class="java">JavaRuntimeValidationAction 用構造函數參數的方式‘串聯’起來,實現逐步調用的效果
代碼走到
ParseAndBuildAction.createAction
private static class BuiltInActions implements CommandLineAction {
public void configureCommandLineParser(CommandLineParser parser) {
parser.option(HELP, "?", "help").hasDescription("Shows this help message.");
parser.option(VERSION, "version").hasDescription("Print version info.");
}
public Runnable createAction(CommandLineParser parser, ParsedCommandLine commandLine) {
if (commandLine.hasOption(HELP)) {
return new ShowUsageAction(parser);
}
if (commandLine.hasOption(VERSION)) {
return new ShowVersionAction();
}
return null;
}
}
本例子中有參數v, 返回new ShowVersionAction();
進入
private static class ShowVersionAction implements Runnable {
public void run() {
GradleVersion currentVersion = GradleVersion.current();
final StringBuilder sb = new StringBuilder();
sb.append("\n------------------------------------------------------------\nGradle ");
sb.append(currentVersion.getVersion());
sb.append("\n------------------------------------------------------------\n\nBuild time: ");
sb.append(currentVersion.getBuildTime());
sb.append("\nBuild number: ");
sb.append(currentVersion.getBuildNumber());
sb.append("\nRevision: ");
sb.append(currentVersion.getRevision());
sb.append("\n\nGroovy: ");
sb.append(GroovySystem.getVersion());
sb.append("\nAnt: ");
sb.append(Main.getAntVersion());
sb.append("\nJVM: ");
sb.append(Jvm.current());
sb.append("\nOS: ");
sb.append(OperatingSystem.current());
sb.append("\n");
System.out.println(sb.toString());
}
}
這樣就打出了gradle的版本信息