## How to write a Kobalt plug-in

## Tutorial

If you are curious to get a quick feel for what a Kobalt plug-in looks like, I suggest you go read how to write and publish a plug-in in ten minutes and then you can come back here and keep reading.

## Setting up IDEA

### Launch configuration

The simplest way to run your plug-in in your IDE is to create a main function in the main class of your plug-in as follows:

    fun main(argv: Array<String>) {
        com.beust.kobalt.main(argv)
    }

In order for this code to compile, you will have to switch the dependency of your plug-in from `kobalt-plugin-api` to just `kobalt`, which is the actual application (and which therefore contains the `main()` entry point).

            // Normal dependency
            compile("com.beust:kobalt-plugin-api:$KOBALT_VERSION")

            // Development dependency
            compile("com.beust:kobalt:$KOBALT_VERSION")

You might find it convenient to leverage Kobalt's ability to use regular Kotlin variables to make things easier:

    val dev = false
    val kobaltDependency = if (dev) "kobalt" else "kobalt-plugin-api"

    val p = project {
        // ...

        compile("com.beust:$kobaltDependency:$KOBALT_VERSION")
    }

Then you can simply set the `dev` to `true` during development and back to `false` when you are ready to publish your plug-in.

Then resync your build file in IDEA and your `main()` function should now build and be launchable. You can right click on that class file and select "Debug <your class name>", which will launch Kobalt with your plug-in. You can set a breakpoint in one of your tasks or anywhere that gets invoked. Don't forget to invoke this launch configuration with the regular parameters passed to Kobalt (e.g. `"assemble"`).

### Local dependencies

In the process of building your plug-in, you will probably be invoking it from test projects and since you will be making changes to your plug-in and generating jar files often, you might find it more convenient to have these test projects point to your local jar file instead of the Maven one (which would require you to upload your plug-in all the time). For this, you might find the `file()` and `homeDir ()` directives convenient:

        // Regular dependency
        compile("com.example:myPlugin:0.1")

        // Development dependency
        compile(file(homeDir("kotlin/myPlugin/kobaltBuild/libs/myPlugin-0.1.jar"))

With this latter configuration, simply build your plug-in to generate the jar file with `./kobaltw assemble`, switch to your test project and invoke Kobalt on it so that your plug-in will get invoked and you should see the latest version of your code being invoked.

## Plug-in architecture

Plug-ins often produce files and data that other plug-ins need to use in order for a build to succeed. For example, the Android plug-in needs to generate a file called `R.java` and then make this file available at compile time by the Java or Kotlin (or any other language) plug-in. Since plug-ins have no idea about what other plug-ins are currently enabled and running, they can't directly talk to each other so instead of calling into Kobalt, Kobalt calls into them. This is done by declaring various "actors" that Kobalt will invoke whenever it needs the information that your plug-in produced. This is a design pattern often referred to as the "Hollywood Principle": "Don't call us, we'll call you".

These "actors" are exactly what the `kobalt-plugin.xml` file describes. This file informs Kobalt about the various ways in which your plug-in participates in the build system by specifying 1) plug-ins, 2) contributors or 3) interceptors.

### Parts

- kobalt-plugin.xml. A file that describes all the components (called "plug-in actors") of your plug-in, such as contributors.
- Directives. Kotlin functions that users of your plug-in can invoke in their build file, such as `project` or `dependencies`. These functions typically configure some data that your plug-in will later use to perform its functions.
- Tasks. These tasks are invoked from the command line and ask your plug-ins to perform certain actions.
- Properties. Plug-ins can export properties and read properties from other plug-ins.

### kobalt-plugin.xml

The `kobalt-plugin.xml` file (stored in `META-INF` in the jar file of your plug-in) is mandatory and describes all the actors of your plug-in. This file contains a list of class names, each of which is expected to implement at least one of `IPluginActor`'s interfaces:

    <plugin-actors>
      <class-name>com.beust.kobalt.plugin.java.JavaPlugin</class-name>
      <class-name>com.beust.kobalt.plugin.android.AndroidPlugin</class-name>
      <class-name>com.beust.kobalt.plugin.java.JavaBuildGenerator</class-name>
      <class-name>com.beust.kobalt.plugin.kotlin.KotlinBuildGenerator</class-name>
    </plugin-actors>

`IPluginActors` can be split in several categories:

- Plugins, which contain `@Task` annotations.
- Interceptors, which transform data that Kobalt gives them.
- Contributors, which produce additional data.

All plug-in actors are interfaces that extend `IPluginActor`. Plug-ins extend `IPlugin`, interceptors extend `IInterceptor` and contributors extend `IContributor`. When Kobalt parses your `kobalt-plugin.xml`, it instantiates all the classes found in the `<plugin-actors>` tag and then introspects them to find out which `IPluginActor` interfaces that class implements.

If we look a the declarations of these classes, we can get an idea what they do

    class JavaPlugin : ICompilerContributor, IDocContributor {

With this declaration, we know that the `JavaPlugin` contributes a compiler and a doc generator.

    class JavaBuildGenerator: ITemplateContributor {

This class is declaring that it wants to take part in the `--init` process (i.e. it can generate a template), discussed below.

## List of plug-in actors

Here is a list of actors (contributors and interceptors) that you can define in your plug-in.

Interface name | Type | Description
`IAssemblyContributor` | `IContributor` | Plug-ins that want be invoked when the `assemble` task is called.
`IBuildConfigContributor` | `IContributor` | Plug-ins that want to generate their own `BuildConfig` file.
`IBuildConfigFieldContributor` | `IInterceptor` | Plug-ins that want to add custom fields to the generated `BuildConfig` class.
`IBuildDirectoryInterceptor` | `IInterceptor` | Plug-ins that need to generate class files in a different directory than the default one should implement this interface.
`IClasspathContributor` | `IContributor` | Classpath contributors let you specify additional jar files or directories that will be used by the `"compile"` task.
`IClasspathInterceptor` | `IInterceptor` | Plug-ins that want to modify the classpath before Kobalt uses it should implement this interface.
`ICompilerContributor` | `IContributor` | Plug-ins that want be invoked when the `compile` task is called.
`ICompilerFlagContributor` | `IContributor` | Plug-ins that need to add flags to the compiler.
`IIncrementalTaskContributor` | `IContributor` | Plug-ins that implement this interface provide incremental tasks.
`ICompilerInterceptor` | `IInterceptor` | Plug-ins that implement this interface get a chance to alter the dependencies of a project (`dependencies{}`, `dependenciesTest{}`, ...) before Kobalt sees them.
`IDocContributor` | `IContributor` | Plug-ins that know how to generate documentation out of source files should implement this interface.
`IMavenIdInterceptor` | `IInterceptor` | Plug-ins that need to rewrite Maven id's should implement this interface.
`IProjectContributor` | `IContributor` | Some plug-ins produce projects (Java, Kotlin) while others don't (Packaging, Application, etc...). The ones that do need to register themselves as project contributors. This is how Kobalt collects all the projects defined after a build file was parsed.
`IRepoContributor` | `IContributor` | Some plug-ins might want to add their own repository to the list of repositories that Kobalt already supports. This is the case of the Android plug-in which, once the `ANDROID_HOME` environment variable has been defined, will automatically add the repository inside the Android distribution so that support libraries and other artifacts can be found.
`IRunnerContributor` | `IContributor` | Plug-ins that can operate when the `"run"` task gets invoked should implement that interface.
`ISourceDirectoryContributor` | `IContributor` | Plug-ins that add source directories.
`ISourceDirectoryInterceptor` | `IInterceptor` | Plug-ins that want to add, remove or alter the source directories should implement this interface.
`ITaskContributor` | `IContributor` | Plug-ins that implement this interface provide tasks.
`ITemplateContributor` | `IContributor` | When invoked with `--init` followed by template names separated by commas, Kobalt will invoke each of these contributors so they can generate their files. Templates are useful to create projects from scratch with a minimal number of files to get started. For example, the "java" template will generate a `Build.kt` file suitable for a brand new Java project.
`ITestRunnerContributor` | `IContributor` | Plug-ins that can operate when the `"test"` task gets invoked should implement that interface.
`ITestSourceDirectoryContributor` | `IContributor` | Plug-ins that add test source directories.

## Selection process

Several plug-ins might want to contribute to a specific task where only one participant should be allowed, such as running tests or generating documentation. Even the simple task of compiling should probably only ever be performed by no more than one plug-in for a given project. Therefore, when comes the time to compile a project, Kobalt needs to find which plug-in is the most suitable for that task and pick it. In order to do that, plug-ins that contribute to tasks that can only be performed by one candidate need to declare their affinity to that task for a given project.

Contributors that want to participate in a selection process need to implement the following interface:

    interface IProjectAffinity {
        /**
         * @return an integer indicating the affinity of your actor for the given project. The actor that returns
         * the highest affinity gets selected.
         */
        fun affinity(project: Project, context: KobaltContext) : Int
    }

For example, the JavaPlugin implements the `ICompilerContributor` interface and then overrides the `affinity()` method to make sure it gets run for Java projects but ignored for others:

    override fun affinity(project: Project, context: KobaltContext) =
    if (project.sourceSuffix == ".java") 1 else 0

## Directives

Directives are functions that users of your plug-in can use in their build file in order to configure your plug-in. These can be any kind of Kotlin function but in the interest of preserving a clean syntax in the build file, it's recommended to use the type safe builder pattern, as described here.

Imagine that you want to offer a boolean parameter `publish` to users of your plug-in, you start by creating a class to hold that parameter:

    class Info(val publish: Boolean)

Next, you create a directive that returns such a class and which also allows to configure it via the type safe builder pattern:

    @Directive
    public fun myConfig(init: Info.() -> Unit) = Info().apply { init() }

The `@Directive` annotation is not enforced but you should always use it in order to help future tools (e.g. an IDEA plug-in) identify Kobalt directives so they can be treated differently from regular Kotlin functions. The code above defines a `myConfig` function that accepts a closure as an argument. It creates an `Info` object, calls the `init()` function on it (which runs all the code inside that closure) and then return that `Info` object.

Users can now specify the following in their build file:

    // Build.kt
    import.com.example.plugin.myConfig
    myConfig {
        publish = true
    }

If you need access to the project being built, just declare an additional parameter of type `Project` to your directive and have the user pass that project:

    @Directive
    public fun myConfig(project: Project, init: Info.() -> Unit) : Info {
    // ...

    myConfig(project) {
        publish = true
    }

The last piece of this puzzle is how you give this data back to your plug-in so it can act on it. In order to do this, you simply look up the name of your plug-in in the `Plugins` registry and invoke whatever function you need to run:

    @Directive
    public fun myConfig(init: Info.() -> Unit) = Info().apply {
        init()
        (Kobalt.findPlugin("my-plug-in") as MyPlugin).info = info
        this
    }

Obviously, you can choose any kind of API to communicate between the directive and its plug-in. In the code above, I chose to directly override the entire `Info` field, but you could instead choose to call a function, just set one boolean instead of the whole object, etc...

## Tasks

Tasks are provided by plug-ins and can be invoked from the command line, e.g. `./kobaltw assemble`. There are two kinds of tasks: static and dynamic.

### Static tasks

Static tasks are functions declared directly in your plug-in class and annotated with the `@Task` annotation. Here is an example:

    @Task(name = "lineCount", description = "Count the lines", dependsOn = arrayOf("compile"))
    fun lineCount(project: Project): TaskResult {
        // ...
        return TaskResult()
    }

A Kobalt task needs to accept a `Project` in parameter and return a `TaskResult`, which indicates whether this task completed successfully.

The `@Task` annotation accepts the following attributes:

name
  The name of the task, which will be used to invoke it from the command line.
description
  The description of this command, which will be displayed if the user invokes the usage for the `kobaltw` command.
dependsOn
  A list of all the tasks that this task depends on.
reverseDependsOn
  Make the following tasks depend on this task.
runBefore
  A list of all the tasks that this task should run prior to.
runAfter
  A list of all the tasks that should run before this task does.

Kobalt defines two different concepts for tasks: dependencies and orderings. And for each of this concept, you can define the relation to go in one direction or the other.

If your task cannot run until another task has run, you need to declare a dependency. Dependencies cause additional tasks than those requested to be executed. For example, `"assemble"` depends on `"compile"`, which means that whenever you invoke `"assemble"`, `"compile"` will be automatically run first. This is a dependency and it is controlled by `"dependsOn"` and `"reverseDependsOn"`. You can see `"reverseDependsOn"` as a way to insert your task before an existing task.

Orderings, controlled by `"runBefore"` and `"runAfter"` merely specify an ordering but do not pull new tasks in. This is how you tell Kobalt "In case the user asks for my task to run, here is when it should be invoked", but your task will run only if it's explicitly invoked by the user.

Here are a few different scenarios to illustrate how the three attributes work for the task `example`:

Result of the command `./kobaltw --dryRun compile`

Configuration for `example` | Result | Note
dependsOn = "compile" |
    clean
    compile
    example
| Make the `"example"` task depend on `"compile"`.
reverseDependsOn = "compile" |
    clean
    example
    compile
| Insert the `"example"` task before `"compile"`.
runAfter = "compile" |
    clean
    compile
| Make `"example"` run after `"compile"` but only if it's invoked explicitly.

### Dynamic tasks

Dynamic tasks are useful when you want your plug-in to generate one or several tasks that depend on some other runtime information (therefore, you can't declare a method and put a `@Task` annotation on it). Plug-ins declare dynamic tasks by implementing the `ITaskContributor` intrface:

    interface ITaskContributor {
        fun tasksFor(project: Project, context: KobaltContext) : List<DynamicTask>
    }

For example:

    override fun tasksFor(project: Project, context: KobaltContext) = listOf(
        DynamicTask(this
            name = "dynamicTask",
            description = "Description",
            group = "other",
            project = project,
            reverseDependsOn = listOf("compile"),
            closure = { project ->
                println("Running dynamicTask")
                TaskResult()
    }))

`DynamicTask` mirrors the `@Task` attributes: `name`, `description` and dependencies. The only addition is the `closure` parameter, which specifics the code that will run if your task gets invoked. That closure needs to follow the same constraints that a `@Task` method obeys: it takes a `Project` parameter and returns a `TaskResult`.

Once you have implemented `ITaskContributor`, you can see your dynamic task in the list of tasks and run it directly:

    $ ./kobaltw --tasks
      ===== kobalt-line-count =====
        dynamicTask         Description
        lineCount           Count the lines
    $ ./kobaltw dynamicTask
    Running dynamictask

## Properties

Properties are the mechanism that plug-ins can use to export values and also read values that other plug-ins have exported. There are two kinds of properties that plug-ins can manipulate:

- Project properties: project-specific properties.
- Plug-in properties: general properties that are applicable to no project in particular.

### Project properties

`Project` instances have a property called `projectProperties` that is an instance of the `ProjectProperties` class. Plugins can put and get values on this object in order to store project specific properties.

    fun taskAssemble(project: Project) : TaskResult {
        project.projectProperties.put("packages", packages)

Another plug-in can then query this property as follows:

        val packages = project.projectProperties.put("packages")

### Plug-in properties

The `PluginProperties` instance can be found on the `KobaltContext` object that your plug-in receives in its `apply()` method. Once you have an instance of this class, you can read or write variables into it:

    override fun apply(project: Project, context: KobaltContext) {
        // Export a property for other plug-ins to use
        context.pluginProperties.put(PLUGIN_NAME, "somePluginProperty", "someValue")
        // Read a property from another plug-in
        val sourceDir = context.pluginProperties.get("pluginName", "somePluginProperty")
    }

### Documenting properties

Plug-ins that define properties should annotate them with the `@ExportedPluginProperty` or `@ExportedProjectProperty`annotation:

    companion object {
    @ExportedProjectProperty
    const val BUILD_DIR = "buildDir"