// Copyright (C) 2023 Gradle, Inc.
//
// Licensed under the Creative Commons Attribution-Noncommercial-ShareAlike 4.0 International License.;
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://creativecommons.org/licenses/by-nc-sa/4.0/
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

[[partr6_writing_tasks]]
= Part 6: Writing Tasks

Learn the basics of authoring Gradle tasks by creating a simple one in your Build script.

****
**In this section, you will:**

- Understand Tasks
- Create a custom Task for the Plugin
****

[[part6_begin]]
== Step 0. Before you Begin

1. You initialized your Java app in <<partr1_gradle_init.adoc#part1_begin,part 1>>.
2. You understand the Gradle Build Lifecycle from <<partr2_build_lifecycle.adoc#part2_begin,part 2>>.
3. You added a subproject and a separate Build in <<partr3_multi_project_builds#part3_begin, part3>>.
4. You viewed a Settings file in <<partr4_settings_file.adoc#part4_begin,part 4>>.
5. You authored a Build script in <<partr5_build_scripts.adoc#part5_begin,part 5>>.

== Step 1. Understand Tasks
A Task is an executable piece of code that contains sequences of actions.

Actions are added to a Task via the `doFirst{}` and `doLast{}` closures.

A Task can depend on other tasks.

== Step 2. Register and Configure Tasks

Early on in the tutorial, we registered and configured `task1` in the `app` build script:

.app/build.gradle.kts
[source,kotlin]
----
tasks.register("task1"){
    println("REGISTER TASK1: This is executed during the configuration phase")
}

tasks.named("task1"){
    println("NAMED TASK1: This is executed during the configuration phase")
    doFirst {
        println("NAMED TASK1 - doFirst: This is executed during the execution phase")
    }
    doLast {
        println("NAMED TASK1 - doLast: This is executed during the execution phase")
    }
}
----

You can use the link:{kotlinDslPath}/gradle/org.gradle.api.tasks/-task-container/index.html[register()] method to create new tasks.

You can use the link:{kotlinDslPath}/gradle/org.gradle.api.tasks/-task-collection/index.html[named()] method to configure existing tasks.

== Step 3. Create a custom Task

To create a custom task, you must subclass link:{kotlinDslPath}/gradle/org.gradle.api/-default-task/index.html[`DefaultTask`].

Create a custom class called `LicenseTask` in `gradle/license-plugin/plugin/src/main/kotlin/com/gradle/LicensePlugin.kt` with the code below:

.gradle/license-plugin/plugin/src/main/kotlin/com/gradle/LicensePlugin.kt
[source,kotlin]
----
package com.gradle

import org.gradle.api.Project
import org.gradle.api.Plugin
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
import java.io.File
import java.io.InputStream
import java.nio.charset.Charset

abstract class LicenseTask : DefaultTask() {
    @Input
    val fileName = project.rootDir.toString() + "/license.txt"

    @TaskAction
    fun action() {
        // Read the license text
        val licenseText = File(fileName).readText()
        // Walk the directories looking for java or kt files
        File(project.rootDir.toString()).walk().forEach {
            if (it.extension == "java") { // || it.extension == "kt") {
                // Read the source code
                var ins: InputStream = it.inputStream()
                var content = ins.readBytes().toString(Charset.defaultCharset())
                // Write the license and the source code to the file
                it.writeText(licenseText + content)
            }
        }
    }
}
----

The `LicenseTask` class encapsulates the task action logic and declares any inputs and outputs the task expects.

The task action is annotated with `@TaskAction`.
Inside, the logic first finds a file called "license.txt".
This file contains text for an Apache license:

----
/*
* Licensed under the Apache License
*/
----

The task then looks for files with the extension `.java` and `.kts` and adds a license header.

The task has a single input, the license file name, annotated with `@Input`.

Gradle uses the `@Input` annotation to determine if the task needs to run.
If the task has not run before or if the input value has changed since the previous execution, then Gradle will execute the task.

While a custom class has been created, it is not yet added to the `LicensePlugin`.
Running `LicenseTask` is not currently possible.

[.text-right]
**Next Step:** <<partr7_writing_plugins#partr7_writing_plugins,Writing Plugins>> >>
