Java Code Examples for org.gradle.api.Task

The following examples show how to use org.gradle.api.Task. 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
Source Project: gradle-modules-plugin   Source File: ClasspathFile.java    License: 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 2
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 3
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 Project: javaide   Source File: TaskManager.java    License: 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 5
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 6
Source Project: gradle-plugins   Source File: ValidatePomsPlugin.java    License: 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 7
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 8
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 Project: atlas   Source File: TaskQueryHelper.java    License: 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
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
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
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
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 14
@SuppressWarnings("unchecked")
private void addInstrumentActionToTask(String sourceType, Task task, CoroutinesPluginConfiguration config) {
    task.doLast(x -> {
        try {
            // Get source sets -- since we don't have access to the normal Gradle plugins API (artifact can't be found on any repo) we
            // have to use Java reflections to access the data.
            Project proj = task.getProject();

            Object sourceSets = JXPathContext.newContext(proj).getValue("properties/sourceSets");

            // can't use JXPath for this because jxpath can't read inherited properties (getAsMap is inherited??)
            Map<String, Object> sourceSetsMap = (Map<String, Object>) MethodUtils.invokeMethod(sourceSets, "getAsMap");

            if (sourceSetsMap.containsKey(sourceType)) {
                JXPathContext ctx = JXPathContext.newContext(sourceSetsMap);
                File classesDir = (File) ctx.getValue(sourceType + "/output/classesDir");
                Set<File> compileClasspath = (Set<File>) ctx.getValue(sourceType + "/compileClasspath/files");
                
                if (classesDir.isDirectory()) {
                    instrument(classesDir, compileClasspath, config);
                }
            }
        } catch (Exception e) {
            throw new IllegalStateException("Coroutines instrumentation failed", e);
        }
    });        
}
 
Example 15
public void afterExecute(Task task, TaskState state) {
    String taskPath = path(task);
    if (taskPath.startsWith(":buildSrc:")) {
        return;
    }

    if (state.getSkipped()) {
        skippedTasks.add(taskPath);
    }
}
 
Example 16
Source Project: spring-javaformat   Source File: SpringJavaFormatPlugin.java    License: Apache License 2.0 5 votes vote down vote up
private void addSourceTasks(SourceSet sourceSet, Task checkAll, Task formatAll) {
	CheckTask checkTask = addSourceTask(sourceSet, CheckTask.class, CheckTask.NAME, CheckTask.DESCRIPTION);
	checkTask.setReportLocation(
			new File(this.project.getBuildDir(), "reports/format/" + sourceSet.getName() + "/check-format.txt"));
	checkAll.dependsOn(checkTask);
	FormatTask formatSourceSet = addSourceTask(sourceSet, FormatTask.class, FormatTask.NAME,
			FormatTask.DESCRIPTION);
	formatSourceSet.conventionMapping("encoding", () -> "UTF-8");
	formatAll.dependsOn(formatSourceSet);
}
 
Example 17
private int differentDescriptions(List<Task> tasks) {
    return toSet(
            collect(tasks, new Transformer<String, Task>() {
                public String transform(Task original) {
                    return original.getDescription();
                }
            })
    ).size();
}
 
Example 18
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);
    }
}
 
Example 19
Source Project: gradle-cpd-plugin   Source File: CpdPluginTest.java    License: 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 20
@Override
public void afterExecute(Task task, TaskState taskState) {
  recordElapsed(task);
  long elapsedTime = getTotalElapsed(task);

  if (taskState.getFailure() != null) {
    metrics.measureFailure(task);
    return;
  }
  metrics.measureSuccess(task, elapsedTime);
}
 
Example 21
Source Project: gradle-git-publish   Source File: GitPublishPlugin.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void apply(Project project) {
  GitPublishExtension extension = project.getExtensions().create("gitPublish", GitPublishExtension.class, project);

  extension.getCommitMessage().set("Generated by gradle-git-publish.");

  // if using the grgit plugin, default to the repo's origin
  project.getPluginManager().withPlugin("org.ajoberstar.grgit", plugin -> {
    // TODO should this be based on tracking branch instead of assuming origin?
    Optional.ofNullable((Grgit) project.findProperty("grgit")).ifPresent(grgit -> {
      extension.getRepoUri().set(getOriginUri(grgit));
      extension.getReferenceRepoUri().set(grgit.getRepository().getRootDir().toURI().toString());
    });
  });

  extension.getRepoDir().set(project.getLayout().getBuildDirectory().dir("gitPublish"));

  GitPublishReset reset = createResetTask(project, extension);
  Task copy = createCopyTask(project, extension);
  Task commit = createCommitTask(project, extension, reset.getGrgit());
  Task push = createPushTask(project, extension, reset.getGrgit());
  push.dependsOn(commit);
  commit.dependsOn(copy);
  copy.dependsOn(reset);

  // always close the repo at the end of the build
  project.getGradle().buildFinished(result -> {
    project.getLogger().info("Closing Git publish repo: {}", extension.getRepoDir().get());
    if (reset.getGrgit().isPresent()) {
      reset.getGrgit().get().close();
    }
  });
}
 
Example 22
Source Project: joinfaces   Source File: ClasspathScanPluginTest.java    License: Apache License 2.0 5 votes vote down vote up
private void checkForGeneratedTasks() {
	Task scanClasspath = this.project.getTasks().getByName("scanJoinfacesClasspath");
	Task scanTestClasspath = this.project.getTasks().getByName("scanJoinfacesTestClasspath");

	assertThat(scanClasspath).isNotNull();
	assertThat(scanClasspath).isInstanceOf(ClasspathScan.class);
	assertThat(scanTestClasspath).isNotNull();
	assertThat(scanTestClasspath).isInstanceOf(ClasspathScan.class);
}
 
Example 23
Source Project: gradle-java-modules   Source File: JigsawPlugin.java    License: 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 24
Source Project: atlas   Source File: ConventionMappingHelper.java    License: 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 25
Source Project: javaide   Source File: AndroidTaskRegistry.java    License: 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 26
public void upToDateWhen(final Spec<? super Task> spec) {
    taskMutator.mutate("TaskOutputs.upToDateWhen(Spec)", new Runnable() {
        public void run() {
            upToDateSpec = upToDateSpec.and(spec);
        }
    });
}
 
Example 27
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 28
Source Project: shipkit   Source File: GitPlugin.java    License: 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 29
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 30
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);
}