org.gradle.api.Task Java Examples

The following examples show how to use org.gradle.api.Task. 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
Source File: TaskManager.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Add tasks for running lint on individual variants. We've already added a
 * lint task earlier which runs on all variants.
 */
public void createLintTasks(TaskFactory tasks, final VariantScope scope) {
    final BaseVariantData<? extends BaseVariantOutputData> baseVariantData =
            scope.getVariantData();
    if (!isLintVariant(baseVariantData)) {
        return;
    }

    // wire the main lint task dependency.
    tasks.named(LINT, new Action<Task>() {
        @Override
        public void execute(Task it) {
            it.dependsOn(LINT_COMPILE);
            it.dependsOn(scope.getJavacTask().getName());
        }
    });

    AndroidTask<Lint> variantLintCheck = androidTasks.create(
            tasks, new Lint.ConfigAction(scope));
    variantLintCheck.dependsOn(tasks, LINT_COMPILE, scope.getJavacTask());
}
 
Example #2
Source File: ValidatePomsPlugin.java    From gradle-plugins with MIT License 6 votes vote down vote up
@Override
public void apply(Project project) {
    project.getTasks().withType(GenerateMavenPom.class, generateMavenPom -> {

        String checkTaskName;

        if (generateMavenPom.getName().startsWith("generate")) {
            checkTaskName = "validate" + generateMavenPom.getName().substring(8);
        } else {
            checkTaskName = "validate" + generateMavenPom.getName();
        }

        ValidateMavenPom validateMavenPom = project.getTasks().create(checkTaskName, ValidateMavenPom.class);

        project.afterEvaluate(p -> {

            Task check = project.getTasks().findByName(JavaBasePlugin.CHECK_TASK_NAME);
            if (check != null) {
                check.dependsOn(validateMavenPom);
            }

            validateMavenPom.dependsOn(generateMavenPom);
            validateMavenPom.getPomFile().set(generateMavenPom.getDestination());
        });
    });
}
 
Example #3
Source File: ExcludedTaskFilteringBuildConfigurationAction.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void configure(BuildExecutionContext context) {
    GradleInternal gradle = context.getGradle();
    Set<String> excludedTaskNames = gradle.getStartParameter().getExcludedTaskNames();
    if (!excludedTaskNames.isEmpty()) {
        TaskSelector selector = gradle.getServices().get(TaskSelector.class);
        final Set<Task> excludedTasks = new HashSet<Task>();
        for (String taskName : excludedTaskNames) {
            excludedTasks.addAll(selector.getSelection(taskName).getTasks());
        }
        gradle.getTaskGraph().useFilter(new Spec<Task>() {
            public boolean isSatisfiedBy(Task task) {
                return !excludedTasks.contains(task);
            }
        });
    }

    context.proceed();
}
 
Example #4
Source File: DefaultCacheScopeMapping.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public File getBaseDirectory(Object scope, String key, CacheBuilder.VersionStrategy versionStrategy) {
    if (key.equalsIgnoreCase("projects") || key.equalsIgnoreCase("tasks") || !key.matches("\\p{Alpha}+[-//.\\w]*")) {
        throw new IllegalArgumentException(String.format("Unsupported cache key '%s'.", key));
    }
    if (scope == null) {
        return getCacheDir(globalCacheDir, versionStrategy, key);
    }
    if (scope instanceof Gradle) {
        Gradle gradle = (Gradle) scope;
        return getCacheDir(getBuildCacheDir(gradle.getRootProject()), versionStrategy, key);
    }
    if (scope instanceof Project) {
        Project project = (Project) scope;
        return getCacheDir(getBuildCacheDir(project.getRootProject()), versionStrategy, String.format("projects/%s/%s", project.getPath().replace(':', '_'), key));
    }
    if (scope instanceof Task) {
        Task task = (Task) scope;
        return getCacheDir(getBuildCacheDir(task.getProject().getRootProject()), versionStrategy, String.format("tasks/%s/%s", task.getPath().replace(':', '_'), key));
    }
    throw new IllegalArgumentException(String.format("Don't know how to determine the cache directory for scope of type %s.", scope.getClass().getSimpleName()));
}
 
Example #5
Source File: SkipTaskWithNoActionsExecuter.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void execute(TaskInternal task, TaskStateInternal state, TaskExecutionContext context) {
    if (task.getActions().isEmpty()) {
        LOGGER.info("Skipping {} as it has no actions.", task);
        boolean upToDate = true;
        for (Task dependency : task.getTaskDependencies().getDependencies(task)) {
            if (!dependency.getState().getSkipped()) {
                upToDate = false;
                break;
            }
        }
        if (upToDate) {
            state.upToDate();
        }
        return;
    }
    executer.execute(task, state, context);
}
 
Example #6
Source File: TaskDetailsFactory.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public TaskDetails create(final Task task) {
    final String path;
    Project project = task.getProject();
    if (projects.contains(project)) {
        path = this.project.relativeProjectPath(task.getPath());
    } else {
        path = task.getPath();
    }
    return new TaskDetails() {
        public Path getPath() {
            return Path.path(path);
        }

        public String getDescription() {
            return task.getDescription();
        }

        public Set<TaskDetails> getDependencies() {
            return Collections.emptySet();
        }

        public Set<TaskDetails> getChildren() {
            return Collections.emptySet();
        }
    };
}
 
Example #7
Source File: ClasspathFile.java    From gradle-modules-plugin with MIT License 6 votes vote down vote up
/**
 * Configures appropriate action if project has task "eclipseClasspath".
 *
 * @param task
 *        responsible for generating {@code .classpath} file
 */
public void configure(final Task task) {
  // LOGGER.quiet("configure, task: {}", task.getClass());

  // --- add functionality for enhancing the content of ".classpath"-file
  // Note: For more information see the manual for the eclipse-plugin.
  final EclipseClasspath eclipseClasspath = ((GenerateEclipseClasspath) task).getClasspath();
  eclipseClasspath.file(
      xmlFileContentMerger -> {
        xmlFileContentMerger.withXml(
            xmlProvider -> {
              final Node rootNode = xmlProvider.asNode();

              // show content of .classpath file before improving
              LOGGER.debug("addAction: rootNode.before improving:{}", rootNode);

              // improve
              improveEclipseClasspathFile(rootNode);

              // show content of .classpath file after improving
              LOGGER.debug("addAction: rootNode.after  improving:{}", rootNode);
            } // end xmlProvider's lambda expression
        );
      } // end xmlFileContentMerger's lambda expression
  );
}
 
Example #8
Source File: TaskFactory.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
TaskFactory(ClassGenerator generator, ProjectInternal project, Instantiator instantiator) {
    this.generator = generator;
    this.project = project;
    this.instantiator = instantiator;


    validTaskArguments = new HashSet<String>();
    validTaskArguments.add(Task.TASK_ACTION);
    validTaskArguments.add(Task.TASK_DEPENDS_ON);
    validTaskArguments.add(Task.TASK_DESCRIPTION);
    validTaskArguments.add(Task.TASK_GROUP);
    validTaskArguments.add(Task.TASK_NAME);
    validTaskArguments.add(Task.TASK_OVERWRITE);
    validTaskArguments.add(Task.TASK_TYPE);

}
 
Example #9
Source File: TaskQueryHelper.java    From atlas with Apache License 2.0 6 votes vote down vote up
public static <T extends Task> List<T> findTask(Project project, Class<T> clazz, BaseVariantData vod) {

        Task[] androidTasks = project.getTasks().withType(clazz).toArray(new Task[0]);

        String variantName = vod.getName();

        List<Task> taskList = new ArrayList();
        for (Task task : androidTasks) {
            if (task instanceof DefaultAndroidTask) {
                if (variantName.equals(((DefaultAndroidTask)task).getVariantName())) {
                    taskList.add(task);
                }
            } else {

                String name = task.getName();
                if (name.toLowerCase().contains(variantName)) {
                    taskList.add(task);
                }
            }

        }
        return (List<T>)taskList;
    }
 
Example #10
Source File: TaskDetailPrinter.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private ListMultimap<Class, Task> groupTasksByType(List<Task> tasks) {
    final Set<Class> taskTypes = new TreeSet<Class>(new Comparator<Class>() {
        public int compare(Class o1, Class o2) {
            return o1.getSimpleName().compareTo(o2.getSimpleName());
        }
    });
    taskTypes.addAll(collect(tasks, new Transformer<Class, Task>() {
        public Class transform(Task original) {
            return getDeclaredTaskType(original);
        }
    }));

    ListMultimap<Class, Task> tasksGroupedByType = ArrayListMultimap.create();
    for (final Class taskType : taskTypes) {
        tasksGroupedByType.putAll(taskType, filter(tasks, new Spec<Task>() {
            public boolean isSatisfiedBy(Task element) {
                return getDeclaredTaskType(element).equals(taskType);
            }
        }));
    }
    return tasksGroupedByType;
}
 
Example #11
Source File: NestedBeanPropertyAnnotationHandler.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void attachActions(final PropertyActionContext context) {
    Class<?> nestedType = context.getInstanceVariableType();
    if (nestedType == null) {
        nestedType = context.getType();
    }
    context.attachActions(nestedType);
    context.setConfigureAction(new UpdateAction() {
        public void update(Task task, final Callable<Object> futureValue) {
            task.getInputs().property(context.getName() + ".class", new Callable<Object>() {
                public Object call() throws Exception {
                    Object bean = futureValue.call();
                    return bean == null ? null : bean.getClass().getName();
                }
            });
        }
    });
}
 
Example #12
Source File: TaskNameResolvingBuildConfigurationAction.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void configure(BuildExecutionContext context) {
    GradleInternal gradle = context.getGradle();
    List<String> taskNames = gradle.getStartParameter().getTaskNames();
    Multimap<String, Task> selectedTasks = commandLineTaskParser.parseTasks(taskNames, selector);

    TaskGraphExecuter executer = gradle.getTaskGraph();
    for (String name : selectedTasks.keySet()) {
        executer.addTasks(selectedTasks.get(name));
    }

    if (selectedTasks.keySet().size() == 1) {
        LOGGER.info("Selected primary task {}", GUtil.toString(selectedTasks.keySet()));
    } else {
        LOGGER.info("Selected primary tasks {}", GUtil.toString(selectedTasks.keySet()));
    }

    context.proceed();
}
 
Example #13
Source File: CpdPluginTest.java    From gradle-cpd-plugin with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource
void CpdPlugin_shouldAddCpdCheckTaskAsDependencyOfCheckLifecycleTaskIfPluginIsApplied(Class<? extends Plugin> pluginClass, Project project, TaskProvider<Cpd> cpdCheck) {
    // When:
    project.getPlugins().apply(pluginClass);

    // Then:
    Task check = project.getTasks().getByName("check");
    @SuppressWarnings("unchecked") Set<Task> dependencies = (Set<Task>) check.getTaskDependencies().getDependencies(check);

    assertThat(check.getDependsOn()).contains(cpdCheck);
    assertThat(dependencies).contains(cpdCheck.get());
}
 
Example #14
Source File: ConventionMappingHelper.java    From atlas with Apache License 2.0 5 votes vote down vote up
public static void map(@NonNull Task task, @NonNull String key, @NonNull Callable<?> value) {
    if (task instanceof ConventionTask) {
        ((ConventionTask) task).getConventionMapping().map(key, value);
    } else if (task instanceof GroovyObject) {
        ConventionMapping conventionMapping =
                (ConventionMapping) ((GroovyObject) task).getProperty("conventionMapping");
        conventionMapping.map(key, value);
    } else {
        throw new IllegalArgumentException(
                "Don't know how to apply convention mapping to task of type " + task.getClass().getName());
    }
}
 
Example #15
Source File: TaskExecutionLogger.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void beforeExecute(Task task) {
    assert !currentTasks.containsKey(task);

    ProgressLogger currentTask = progressLoggerFactory.newOperation(TaskExecutionLogger.class, parentLoggerPovider.getLogger());
    String displayName = getDisplayName(task);
    currentTask.setDescription(String.format("Execute %s", displayName));
    currentTask.setShortDescription(displayName);
    currentTask.setLoggingHeader(displayName);
    currentTask.started();
    currentTasks.put(task, currentTask);
}
 
Example #16
Source File: InputFilePropertyAnnotationHandler.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void attachActions(PropertyActionContext context) {
    context.setValidationAction(inputFileValidation);
    context.setConfigureAction(new UpdateAction() {
        public void update(Task task, Callable<Object> futureValue) {
            task.getInputs().files(futureValue);
        }
    });
}
 
Example #17
Source File: DefaultTaskOutputs.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void upToDateWhen(final Spec<? super Task> spec) {
    taskMutator.mutate("TaskOutputs.upToDateWhen(Spec)", new Runnable() {
        public void run() {
            upToDateSpec = upToDateSpec.and(spec);
        }
    });
}
 
Example #18
Source File: DefaultJavaSourceSet.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public TaskDependency getBuildDependencies() {
    return new TaskDependency() {
        public Set<? extends Task> getDependencies(Task task) {
            Set<Task> dependencies = new HashSet<Task>();
            dependencies.addAll(compileClasspath.getBuildDependencies().getDependencies(task));
            dependencies.addAll(getSource().getBuildDependencies().getDependencies(task));
            return dependencies;
        }
    };
}
 
Example #19
Source File: GitPlugin.java    From shipkit with MIT License 5 votes vote down vote up
public static void registerChangesForCommitIfApplied(final List<File> changedFiles,
                                                     final String changeDescription, final Task changingTask) {
    final Project project = changingTask.getProject();
    project.getPlugins().withType(GitPlugin.class, new Action<GitPlugin>() {
        @Override
        public void execute(GitPlugin gitPushPlugin) {
            GitCommitTask gitCommitTask = (GitCommitTask) project.getTasks().findByName(GitPlugin.GIT_COMMIT_TASK);
            gitCommitTask.addChange(changedFiles, changeDescription, changingTask);
        }
    });
}
 
Example #20
Source File: JigsawPlugin.java    From gradle-java-modules with Apache License 2.0 5 votes vote down vote up
private void configureCompileJavaTask(final Project project) {
    final JavaCompile compileJava = (JavaCompile) project.getTasks().findByName(JavaPlugin.COMPILE_JAVA_TASK_NAME);
    compileJava.doFirst(new Action<Task>() {
        @Override
        public void execute(Task task) {
            List<String> args = new ArrayList<>();
            args.add("--module-path");
            args.add(compileJava.getClasspath().getAsPath());
            compileJava.getOptions().setCompilerArgs(args);
            compileJava.setClasspath(project.files());
        }
    });
}
 
Example #21
Source File: JavaLanguagePlugin.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public SourceTransformTaskConfig getTransformTask() {
    return new SourceTransformTaskConfig() {
        public String getTaskPrefix() {
            return "compile";
        }

        public Class<? extends DefaultTask> getTaskType() {
            return PlatformJavaCompile.class;
        }

        public void configureTask(Task task, BinarySpec binarySpec, LanguageSourceSet sourceSet) {
            PlatformJavaCompile compile = (PlatformJavaCompile) task;
            JavaSourceSet javaSourceSet = (JavaSourceSet) sourceSet;
            JvmBinarySpec binary = (JvmBinarySpec) binarySpec;

            compile.setDescription(String.format("Compiles %s.", javaSourceSet));
            compile.setDestinationDir(binary.getClassesDir());
            compile.setToolChain(binary.getToolChain());
            compile.setPlatform(binary.getTargetPlatform());

            compile.setSource(javaSourceSet.getSource());
            compile.setClasspath(javaSourceSet.getCompileClasspath().getFiles());
            compile.setTargetCompatibility(binary.getTargetPlatform().getTargetCompatibility().toString());
            compile.setSourceCompatibility(binary.getTargetPlatform().getTargetCompatibility().toString());

            compile.setDependencyCacheDir(new File(compile.getProject().getBuildDir(), "jvm-dep-cache"));
            compile.dependsOn(javaSourceSet);
            binary.getTasks().getJar().dependsOn(compile);
        }
    };
}
 
Example #22
Source File: ProfileEventAdapter.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void afterExecute(Task task, TaskState state) {
    long now = timeProvider.getCurrentTime();
    Project project = task.getProject();
    ProjectProfile projectProfile = buildProfile.getProjectProfile(project.getPath());
    TaskExecution taskExecution = projectProfile.getTaskProfile(task.getPath());
    taskExecution.setFinish(now);
    taskExecution.completed(state);
}
 
Example #23
Source File: AndroidTaskRegistry.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
public synchronized <T extends Task> AndroidTask<T> create(
        TaskFactory taskFactory,
        String taskName,
        Class<T> taskClass,
        Action<T> configAction) {

    taskFactory.create(taskName, taskClass, configAction);
    final AndroidTask<T> newTask = new AndroidTask<T>(taskName, taskClass);
    tasks.put(taskName, newTask);

    return newTask;
}
 
Example #24
Source File: ResolveJavadocLinks.java    From gradle-plugins with MIT License 5 votes vote down vote up
@Override
public void execute(Task task) {
    javadoc = (Javadoc) task;
    logger = javadoc.getLogger();

    addLink(getJavaSeLink());

    findConfigurations(javadoc.getClasspath())
            .flatMap(files -> files.getResolvedConfiguration().getResolvedArtifacts().stream())
            .map(resolvedArtifact -> resolvedArtifact.getId().getComponentIdentifier())
            .filter(ModuleComponentIdentifier.class::isInstance)
            .map(ModuleComponentIdentifier.class::cast)
            .map(moduleComponentIdentifier -> {
                String group = moduleComponentIdentifier.getGroup();
                String artifact = moduleComponentIdentifier.getModule();
                String version = moduleComponentIdentifier.getVersion();

                String wellKnownLink = findWellKnownLink(group, artifact, version);
                if (wellKnownLink != null) {
                    javadoc.getLogger().info("Using well known link '{}' for '{}:{}:{}'", wellKnownLink, group, artifact, version);
                    return wellKnownLink;
                }
                else {
                    String javadocIoLink = String.format("https://static.javadoc.io/%s/%s/%s/", group, artifact, version);
                    if (checkLink(javadocIoLink)) {
                        javadoc.getLogger().info("Using javadoc.io link for '{}:{}:{}'", group, artifact, version);
                        return javadocIoLink;
                    }
                    else {
                        return null;
                    }
                }
            })
            .filter(Objects::nonNull)
            .forEach(this::addLink);
}
 
Example #25
Source File: TaskFactory.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public TaskInternal createTask(Map<String, ?> args) {
    Map<String, Object> actualArgs = new HashMap<String, Object>(args);
    checkTaskArgsAndCreateDefaultValues(actualArgs);

    String name = actualArgs.get(Task.TASK_NAME).toString();
    if (!GUtil.isTrue(name)) {
        throw new InvalidUserDataException("The task name must be provided.");
    }

    Class<? extends TaskInternal> type = (Class) actualArgs.get(Task.TASK_TYPE);
    Boolean generateSubclass = Boolean.valueOf(actualArgs.get(GENERATE_SUBCLASS).toString());
    TaskInternal task = createTaskObject(project, type, name, generateSubclass);

    Object dependsOnTasks = actualArgs.get(Task.TASK_DEPENDS_ON);
    if (dependsOnTasks != null) {
        task.dependsOn(dependsOnTasks);
    }
    Object description = actualArgs.get(Task.TASK_DESCRIPTION);
    if (description != null) {
        task.setDescription(description.toString());
    }
    Object group = actualArgs.get(Task.TASK_GROUP);
    if (group != null) {
        task.setGroup(group.toString());
    }
    Object action = actualArgs.get(Task.TASK_ACTION);
    if (action instanceof Action) {
        Action<? super Task> taskAction = (Action<? super Task>) action;
        task.doFirst(taskAction);
    } else if (action != null) {
        Closure closure = (Closure) action;
        task.doFirst(closure);
    }

    return task;
}
 
Example #26
Source File: GeneratorPlugin.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
protected void init(Project project) {
	for (GeneratorModule module : modules) {
		setupCleanTask(project, module);
		Task generateTask = setupGenerateTask(project, module);

		if (module instanceof AsciidocGeneratorModule) {
			generateTask.dependsOn(DocletPlugin.TASK_NAME);
		}
	}
}
 
Example #27
Source File: BuildConfigurationRule.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void apply(String taskName) {
    if (taskName.startsWith(PREFIX)) {
        String configurationName = StringUtils.uncapitalize(taskName.substring(PREFIX.length()));
        Configuration configuration = configurations.findByName(configurationName);

        if (configuration != null) {
            Task task = tasks.create(taskName);
            task.dependsOn(configuration.getAllArtifacts());
            task.setDescription(String.format("Builds the artifacts belonging to %s.", configuration));
        }
    }
}
 
Example #28
Source File: LifecycleBasePlugin.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private void addDeprecationWarningsAboutCustomLifecycleTasks(ProjectInternal project) {
    project.getTasks().all(new Action<Task>() {
        @Override
        public void execute(Task task) {
            if (placeholders.contains(task.getName()) && !task.getExtensions().getExtraProperties().has("placeholder")) {
                throw new InvalidUserDataException(String.format(CUSTOM_LIFECYCLE_TASK_ERROR_MSG, task.getName()));
            }
        }
    });
}
 
Example #29
Source File: TaskDetailPrinter.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Class getDeclaredTaskType(Task original) {
    Class clazz = new DslObject(original).getDeclaredType();
    if (clazz.equals(DefaultTask.class)) {
        return org.gradle.api.Task.class;
    } else {
        return clazz;
    }
}
 
Example #30
Source File: ConfigureGeneratedSourceSets.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void maybeSetSourceDir(SourceDirectorySet sourceSet, Task task, String propertyName) {
    // TODO:DAZ Handle multiple output directories
    Object value = task.property(propertyName);
    if (value != null) {
        sourceSet.srcDir(value);
    }
}