Java Code Examples for org.gradle.util.GradleVersion

The following examples show how to use org.gradle.util.GradleVersion. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public boolean wrapperCanExecute(GradleVersion version) {
    if (version.equals(GradleVersion.version("0.8")) || isVersion("0.8")) {
        // There was a breaking change after 0.8
        return false;
    }
    if (isVersion("0.9.1")) {
        // 0.9.1 couldn't handle anything with a timestamp whose timezone was behind GMT
        return version.getVersion().matches(".*+\\d{4}");
    }
    if (isSameOrNewer("0.9.2") && isSameOrOlder("1.0-milestone-2")) {
        // These versions couldn't handle milestone patches
        if (version.getVersion().matches("1.0-milestone-\\d+[a-z]-.+")) {
            return false;
        }
    }
    return true;
}
 
Example 2
public Object run(String modelName, ProviderOperationParameters providerParameters) {
    List<String> tasks = providerParameters.getTasks();
    if (modelName.equals(ModelIdentifier.NULL_MODEL) && tasks == null) {
        throw new IllegalArgumentException("No model type or tasks specified.");
    }
    Parameters params = initParams(providerParameters);
    Class<?> type = new ModelMapping().getProtocolTypeFromModelName(modelName);
    if (type == InternalBuildEnvironment.class) {
        //we don't really need to launch the daemon to acquire information needed for BuildEnvironment
        if (tasks != null) {
            throw new IllegalArgumentException("Cannot run tasks and fetch the build environment model.");
        }
        return new DefaultBuildEnvironment(
                GradleVersion.current().getVersion(),
                params.daemonParams.getEffectiveJavaHome(),
                params.daemonParams.getEffectiveJvmArgs());
    }

    BuildAction<BuildActionResult> action = new BuildModelAction(modelName, tasks != null);
    return run(action, providerParameters, params.properties);
}
 
Example 3
public static String getUserAgentString() {
    String osName = System.getProperty("os.name");
    String osVersion = System.getProperty("os.version");
    String osArch = System.getProperty("os.arch");
    String javaVendor = System.getProperty("java.vendor");
    String javaVersion = SystemProperties.getJavaVersion();
    String javaVendorVersion = System.getProperty("java.vm.version");
    return String.format("Gradle/%s (%s;%s;%s) (%s;%s;%s)",
            GradleVersion.current().getVersion(),
            osName,
            osVersion,
            osArch,
            javaVendor,
            javaVersion,
            javaVendorVersion);
}
 
Example 4
@SuppressWarnings("NullableProblems")
@Override
public void apply(ExtensionAware extensionAware) {
    // abort if old Gradle version is not supported
    if (GradleVersion.current().getBaseVersion().compareTo(GradleVersion.version("5.0")) < 0) {
        throw new IllegalStateException("This version of the credentials plugin is not compatible with Gradle < 5.0");
    }

    // handle plugin application to settings file and project file
    if (extensionAware instanceof Settings) {
        Settings settings = (Settings) extensionAware;
        init(settings.getGradle(), settings, (String loc) -> settings.getSettingsDir().toPath().resolve(loc).toFile(), NOOP);
    } else if (extensionAware instanceof Project) {
        Project project = (Project) extensionAware;
        init(project.getGradle(), project, project::file, (Pair creds) -> addTasks(creds, project.getTasks()));
    } else {
        throw new IllegalStateException("The credentials plugin can only be applied to Settings and Project instances");
    }
}
 
Example 5
Source Project: Pushjet-Android   Source File: Help.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void printDefaultHelp(StyledTextOutput output, BuildClientMetaData metaData) {
    output.println();
    output.formatln("Welcome to Gradle %s.", GradleVersion.current().getVersion());
    output.println();
    output.text("To run a build, run ");
    metaData.describeCommand(output.withStyle(UserInput), "<task> ...");
    output.println();
    output.println();
    output.text("To see a list of available tasks, run ");
    metaData.describeCommand(output.withStyle(UserInput), "tasks");
    output.println();
    output.println();
    output.text("To see a list of command-line options, run ");
    metaData.describeCommand(output.withStyle(UserInput), "--help");
    output.println();
}
 
Example 6
private ProjectConnection createProjectConnection(ComparableGradleBuildExecuter executer) {
    GradleConnector connector = GradleConnector.newConnector();
    connector.forProjectDirectory(executer.getSpec().getProjectDir());
    File gradleUserHomeDir = gradle.getStartParameter().getGradleUserHomeDir();
    if (gradleUserHomeDir != null) {
        connector.useGradleUserHomeDir(gradleUserHomeDir);
    }

    GradleVersion gradleVersion = executer.getGradleVersion();
    if (gradleVersion.equals(GradleVersion.current())) {
        connector.useInstallation(gradle.getGradleHomeDir());
    } else {
        connector.useGradleVersion(gradleVersion.getVersion());
    }

    return connector.connect();
}
 
Example 7
public boolean wrapperCanExecute(GradleVersion version) {
    if (version.equals(GradleVersion.version("0.8")) || isVersion("0.8")) {
        // There was a breaking change after 0.8
        return false;
    }
    if (isVersion("0.9.1")) {
        // 0.9.1 couldn't handle anything with a timestamp whose timezone was behind GMT
        return version.getVersion().matches(".*+\\d{4}");
    }
    if (isSameOrNewer("0.9.2") && isSameOrOlder("1.0-milestone-2")) {
        // These versions couldn't handle milestone patches
        if (version.getVersion().matches("1.0-milestone-\\d+[a-z]-.+")) {
            return false;
        }
    }
    return true;
}
 
Example 8
protected CacheRepository createCacheRepository() {
    CacheFactory factory = get(CacheFactory.class);
    StartParameter startParameter = get(StartParameter.class);
    DefaultCacheScopeMapping scopeMapping = new DefaultCacheScopeMapping(startParameter.getGradleUserHomeDir(), startParameter.getProjectCacheDir(), GradleVersion.current());
    return new DefaultCacheRepository(
            scopeMapping,
            startParameter.getCacheUsage(),
            factory);
}
 
Example 9
public GradleDistribution getDistribution(final GradleVersion gradleVersion) {
    return findFirst(getAll(), new Spec<GradleDistribution>() {
        public boolean isSatisfiedBy(GradleDistribution element) {
            return element.getVersion().equals(gradleVersion);
        }
    });
}
 
Example 10
@Override
protected void starting(Description d) {
  final TargetVersions targetVersions = d.getAnnotation(TargetVersions.class);
  if (targetVersions == null) return;

  myMatcher = new CustomMatcher<String>("Gradle version '" + targetVersions.value() + "'") {
    @Override
    public boolean matches(Object item) {
      return item instanceof String && new VersionMatcher(GradleVersion.version(item.toString())).isVersionMatch(targetVersions);
    }
  };
}
 
Example 11
Source Project: gradle-modules-plugin   Source File: ModularJavaExec.java    License: MIT License 5 votes vote down vote up
@Override
public String getMain() {
    if(GradleVersion.current().compareTo(GradleVersion.version("6.4")) >= 0) {
        return stripModule(getMainClass().getOrNull());
    } else {
        return super.getMain();
    }
}
 
Example 12
public DaemonStartupInfo startDaemon() {
        DefaultModuleRegistry registry = new DefaultModuleRegistry();
        Set<File> bootstrapClasspath = new LinkedHashSet<File>();
        bootstrapClasspath.addAll(registry.getModule("gradle-launcher").getImplementationClasspath().getAsFiles());
        if (registry.getGradleHome() == null) {
            // Running from the classpath - chuck in everything we can find
            bootstrapClasspath.addAll(registry.getFullClasspath());
        }
        if (bootstrapClasspath.isEmpty()) {
            throw new IllegalStateException("Unable to construct a bootstrap classpath when starting the daemon");
        }

        new JvmVersionValidator().validate(daemonParameters);

        List<String> daemonArgs = new ArrayList<String>();
        daemonArgs.add(daemonParameters.getEffectiveJavaExecutable());

        List<String> daemonOpts = daemonParameters.getEffectiveJvmArgs();
        LOGGER.debug("Using daemon opts: {}", daemonOpts);
        daemonArgs.addAll(daemonOpts);
        //Useful for debugging purposes - simply uncomment and connect to debug
//        daemonArgs.add("-Xdebug");
//        daemonArgs.add("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5006");
        daemonArgs.add("-cp");
        daemonArgs.add(CollectionUtils.join(File.pathSeparator, bootstrapClasspath));
        daemonArgs.add(GradleDaemon.class.getName());
        daemonArgs.add(GradleVersion.current().getVersion());
        daemonArgs.add(daemonDir.getBaseDir().getAbsolutePath());
        daemonArgs.add(String.valueOf(daemonParameters.getIdleTimeout()));
        daemonArgs.add(daemonParameters.getUid());

        //all remaining arguments are daemon startup jvm opts.
        //we need to pass them as *program* arguments to avoid problems with getInputArguments().
        daemonArgs.addAll(daemonOpts);

        DaemonStartupInfo daemonInfo = startProcess(daemonArgs, daemonDir.getVersionedDir());
        listener.daemonStarted(daemonInfo);
        return daemonInfo;
    }
 
Example 13
Source Project: gradle-modules-plugin   Source File: CompileTask.java    License: MIT License 5 votes vote down vote up
private void enforceJarForCompilation() {
    Configuration config = project.getConfigurations().getByName(JavaPlugin.COMPILE_CLASSPATH_CONFIGURATION_NAME);
    config.attributes(new Action<AttributeContainer>() {
        @Override
        public void execute(AttributeContainer attributeContainer) {
            if(GradleVersion.current().compareTo(GradleVersion.version("5.6")) < 0) {
                LOGGER.warn("Cannot enforce using JARs for compilation. Please upgrade to Gradle 5.6 or newer.");
                return;
            }
            attributeContainer.attribute(
                    LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE,
                    project.getObjects().named(LibraryElements.class, LibraryElements.JAR));
        }
    });
}
 
Example 14
Source Project: gradle-modules-plugin   Source File: ModuleSystemPlugin.java    License: MIT License 5 votes vote down vote up
@Override
public void apply(Project project) {
    if(GradleVersion.current().compareTo(GradleVersion.version("5.1")) < 0) {
        LOGGER.warn("WARNING: You use " + GradleVersion.current() +
                ". The minimum version supported (with some limitations) by this plugin is 5.1." +
                "  It is strongly recommended to use at least Gradle 5.6.");
    }
    project.getPlugins().apply(JavaPlugin.class);
    new ModuleName().findModuleName(project).ifPresent(moduleName -> configureModularity(project, moduleName));
}
 
Example 15
Source Project: gradle-modules-plugin   Source File: TaskOption.java    License: MIT License 5 votes vote down vote up
public void mutateOptions(CoreJavadocOptions options) {
    String javadocFlag = getJavadocFlag();
    if(javadocFlag.equals("-module-path") && GradleVersion.current().compareTo(GradleVersion.version("6.4")) >= 0) {
        String[] paths = value.split(System.getProperty("path.separator"));
        List<File> modulePath = Arrays.stream(paths).map(File::new).collect(Collectors.toList());
        options.modulePath(modulePath);
    } else {
        options.addStringOption(javadocFlag, value);
    }
}
 
Example 16
public ProjectConnection connect() throws GradleConnectionException {
    LOGGER.debug("Connecting from tooling API consumer version {}", GradleVersion.current().getVersion());

    ConnectionParameters connectionParameters = connectionParamsBuilder.build();
    if (connectionParameters.getProjectDir() == null) {
        throw new IllegalStateException("A project directory must be specified before creating a connection.");
    }
    if (distribution == null) {
        distribution = distributionFactory.getDefaultDistribution(connectionParameters.getProjectDir(), connectionParameters.isSearchUpwards() != null ? connectionParameters.isSearchUpwards() : true);
    }
    return connectionFactory.create(distribution, connectionParameters);
}
 
Example 17
PersistentCache createCache(StartParameter startParameter) {
    return cacheRepository
            .cache(new File(startParameter.getCurrentDir(), ".gradle/noVersion/buildSrc"))
            .withCrossVersionCache()
            .withDisplayName("buildSrc state cache")
            .withLockOptions(mode(FileLockManager.LockMode.None).useCrossVersionImplementation())
            .withProperties(Collections.singletonMap("gradle.version", GradleVersion.current().getVersion()))
            .open();
}
 
Example 18
public GradleDistribution getDistribution(final GradleVersion gradleVersion) {
    return findFirst(getAll(), new Spec<GradleDistribution>() {
        public boolean isSatisfiedBy(GradleDistribution element) {
            return element.getVersion().equals(gradleVersion);
        }
    });
}
 
Example 19
private static VersionDetails getMetaData(final ConnectionVersion4 delegate) {
    GradleVersion version = GradleVersion.version(delegate.getMetaData().getVersion());
    if (version.compareTo(GradleVersion.version("1.0-milestone-5")) < 0) {
        return new R10M3VersionDetails(delegate);
    } else {
        return new R10M5VersionDetails(delegate);
    }
}
 
Example 20
public void download(URI address, File destination) throws Exception {
    ProgressLogger progressLogger = progressLoggerFactory.newOperation(DistributionFactory.class);
    progressLogger.setDescription(String.format("Download %s", address));
    progressLogger.started();
    try {
        new Download("Gradle Tooling API", GradleVersion.current().getVersion()).download(address, destination);
    } finally {
        progressLogger.completed();
    }
}
 
Example 21
public void download(URI address, File destination) throws Exception {
    ProgressLogger progressLogger = progressLoggerFactory.newOperation(DistributionFactory.class);
    progressLogger.setDescription(String.format("Download %s", address));
    progressLogger.started();
    try {
        new Download("Gradle Tooling API", GradleVersion.current().getVersion()).download(address, destination);
    } finally {
        progressLogger.completed();
    }
}
 
Example 22
private Map<String, String> loadDefaultBindings() {
    String now = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(new Date());
    Map<String, String> map = new LinkedHashMap<String, String>(3);
    map.put("genDate", now);
    map.put("genUser", System.getProperty("user.name"));
    map.put("genGradleVersion", GradleVersion.current().toString());
    return map;
}
 
Example 23
public ProjectConnection connect() throws GradleConnectionException {
    LOGGER.debug("Connecting from tooling API consumer version {}", GradleVersion.current().getVersion());

    ConnectionParameters connectionParameters = connectionParamsBuilder.build();
    if (connectionParameters.getProjectDir() == null) {
        throw new IllegalStateException("A project directory must be specified before creating a connection.");
    }
    if (distribution == null) {
        distribution = distributionFactory.getDefaultDistribution(connectionParameters.getProjectDir(), connectionParameters.isSearchUpwards() != null ? connectionParameters.isSearchUpwards() : true);
    }
    return connectionFactory.create(distribution, connectionParameters);
}
 
Example 24
public boolean isCanObtainProjectOutcomesModel() {
    GradleVersion version = getGradleVersion();
    boolean isMinimumVersionOrHigher = version.compareTo(PROJECT_OUTCOMES_MINIMUM_VERSION) >= 0;
    //noinspection SimplifiableIfStatement
    if (isMinimumVersionOrHigher) {
        return true;
    } else {
        // Special handling for snapshots/RCs of the minimum version
        return version.getBaseVersion().equals(PROJECT_OUTCOMES_MINIMUM_VERSION);
    }
}
 
Example 25
private Map<String, String> loadDefaultBindings() {
    String now = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(new Date());
    Map<String, String> map = new LinkedHashMap<String, String>(3);
    map.put("genDate", now);
    map.put("genUser", System.getProperty("user.name"));
    map.put("genGradleVersion", GradleVersion.current().toString());
    return map;
}
 
Example 26
public void download(URI address, File destination) throws Exception {
    ProgressLogger progressLogger = progressLoggerFactory.newOperation(DistributionFactory.class);
    progressLogger.setDescription(String.format("Download %s", address));
    progressLogger.started();
    try {
        new Download("Gradle Tooling API", GradleVersion.current().getVersion()).download(address, destination);
    } finally {
        progressLogger.completed();
    }
}
 
Example 27
public ProjectConnection connect() throws GradleConnectionException {
    LOGGER.debug("Connecting from tooling API consumer version {}", GradleVersion.current().getVersion());

    ConnectionParameters connectionParameters = connectionParamsBuilder.build();
    if (connectionParameters.getProjectDir() == null) {
        throw new IllegalStateException("A project directory must be specified before creating a connection.");
    }
    if (distribution == null) {
        distribution = distributionFactory.getDefaultDistribution(connectionParameters.getProjectDir(), connectionParameters.isSearchUpwards() != null ? connectionParameters.isSearchUpwards() : true);
    }
    return connectionFactory.create(distribution, connectionParameters);
}
 
Example 28
@Override
public void render(final T model, HtmlPageBuilder<SimpleHtmlWriter> builder) throws IOException {
    this.model = model;

    String baseStyleLink = builder.requireResource(getClass().getResource("/org/gradle/reporting/base-style.css"));
    String reportJsLink = builder.requireResource(getClass().getResource("/org/gradle/reporting/report.js"));
    String styleLink = builder.requireResource(getClass().getResource("style.css"));

    SimpleHtmlWriter htmlWriter = builder.getOutput();

    htmlWriter.startElement("head")
        .startElement("meta").attribute("http-equiv", "Content-Type").attribute("content", "text/html; charset=utf-8").endElement()
        .startElement("meta").attribute("http-equiv", "x-ua-compatible").attribute("content", "IE=edge").endElement()
        .startElement("title").characters(getPageTitle()).endElement()
        .startElement("link").attribute("href", baseStyleLink).attribute("rel", "stylesheet").attribute("type", "text/css").endElement()
        .startElement("link").attribute("href", styleLink).attribute("rel", "stylesheet").attribute("type", "text/css").endElement()
        .startElement("script").attribute("src", reportJsLink).attribute("type", "text/javascript").characters("").endElement() //html does not like <a name="..."/>
    .endElement();

    htmlWriter.startElement("body")
        .startElement("div").attribute("id", "content")
        .startElement("h1").characters(getTitle()).endElement();
        getHeaderRenderer().render(model, htmlWriter);
        getContentRenderer().render(model, htmlWriter);
        htmlWriter.startElement("div").attribute("id", "footer")
            .startElement("p").characters("Generated by ")
                .startElement("a").attribute("href", "http://www.gradle.org").characters(String.format("Gradle %s", GradleVersion.current().getVersion())).endElement()
                .characters(String.format(" at %s", builder.formatDate(new Date())))
            .endElement()
        .endElement()
    .endElement();
}
 
Example 29
protected CacheRepository createCacheRepository() {
    CacheFactory factory = get(CacheFactory.class);
    StartParameter startParameter = get(StartParameter.class);
    DefaultCacheScopeMapping scopeMapping = new DefaultCacheScopeMapping(startParameter.getGradleUserHomeDir(), startParameter.getProjectCacheDir(), GradleVersion.current());
    return new DefaultCacheRepository(
            scopeMapping,
            factory);
}
 
Example 30
/**
 * Returns the default distribution to use for the specified project.
 */
public Distribution getDefaultDistribution(File projectDir, boolean searchUpwards) {
    BuildLayout layout = new BuildLayoutFactory().getLayoutFor(projectDir, searchUpwards);
    WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory(layout.getRootDirectory(), System.out);
    if (wrapper.getDistribution() != null) {
        return new ZippedDistribution(wrapper.getConfiguration());
    }
    return getDownloadedDistribution(GradleVersion.current().getVersion());
}