本文以在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的版本信息
时间: 2024-10-12 16:06:48