The Kobalt diaries: Automatic Android SDK management


The dreaded SDK Manager

Android has always had a weird dependency mechanism. On the JVM (and therefore, Android), we have this great Maven repository system which is leveraged by several tools (Gradle and Kobalt on Android) and which allows us to add dependencies with simple additions to our build files. This is extremely powerful and it has undoubtedly been instrumental in increasing the JVM’s popularity. This system works for pretty much any type of applications and dependencies.

Except for Android libraries.

The Android support libraries (and I’m using “support” loosely here to include all such libraries and not just the one that Google calls “support”) are not available on any of the Maven repositories. They are not even available on Google’s own repository. Instead, you need to use a special tool to download them, and once you do that, they land on your local drive as a local Maven repository, which you then need to declare to Gradle so you can finally add the dependencies you need.

I suspect the reason why these libraries are not available in a straight Maven repo is that you need to accept licenses before you can use them, but regardless, this separate download management makes building Android applications more painful, especially for build servers (Travis, Jenkins) which need to be configured specifically for these builds.

The graphical tool used to download this repository, called “SDK Manager”, is also a command tool called "android" that can be invoked without the GUI, and inspired by Jake Wharton’s sdk-manager-plugin, I set out to implement automatic SDK management for Kobalt.

Once I became more comfortable with the esoteric command line syntax used by the "android" tool, adding it to the Kobalt Android plug-in was trivial, and as a result, Kobalt is now able to completely install a full Android SDK from scratch.

In other words, all you need in your project is a simple Android configuration in your Build.kt file:

    android {
        compileSdkVersion = "23"
        buildToolsVersion = "23.0.1"
        // ...
    }

    dependencies {
        compile("com.android.support:appcompat-v7:aar:23.0.1")
    }

The Kobalt Android plug-in will then automatically download everything you need to create an apk from this simple build file:

  • If $ANDROID_HOME is specified, use it and make sure a valid SDK is there. If that environment variable is not specified, install the SDK in a default location (~/.android-sdk).
  • If no Build Tools are installed, install them.
  • Then go through all the Google and Android dependencies for that project and install them as needed.
  • And a few other things…

A typical run on a clean machine with nothing installed will look like this:

$ ./kobaltw assemble
...
Android SDK not found at /home/travis/.android/android-sdk-linux, downloading it
Couldn't find /home/travis/.android/android-sdk-linux/build-tools/23.0.1, downloading it
Couldn't find /home/travis/.android/android-sdk-linux/platform-tools, downloading it
Couldn't find /home/travis/.android/android-sdk-linux/platforms/android-23, downloading it
Couldn't find Maven repository for extra-android-m2repository, downloading it
Couldn't find Maven repository for extra-google-m2repository, downloading it
...
          ===========================
          | Building androidFlavors |
          ===========================
------ androidFlavors:clean
------ androidFlavors:generateR
------ androidFlavors:compile
  Java compiling 4 files
------ androidFlavors:proguard
------ androidFlavors:generateDex
------ androidFlavors:signApk
Created androidFlavors/kobaltBuild/outputs/apk/androidFlavors.apk

Obviously, these downloads will not happen again unless you modify the dependencies in your build file.

I’m hopeful that Google will eventually make these support libraries available on a real remote Maven repository so we don’t have to jump through these hoops any more, but until then, Kobalt has you covered.

This feature is available in the latest kobalt-android plug-in as follows:

val p = plugins("com.beust:kobalt-android:0.81")

The Kobalt diaries: testing

Kobalt automatically detects how to run your tests based on the test dependencies that you declared:

dependenciesTest {
    compile("org.testng:testng:6.9.9")
}

By default, Kobalt supports TestNG, JUnit and Spek. You can also configure how your tests run
with the test{} directive:

test {
    args("-excludegroups", "broken", "src/test/resources/testng.xml")
}

The full list of configuration parameters can be found in the TestConfig class.

Additionally, you can define multiple test configurations, each with a different name. Each
configuration will create an additional task named "test" followed by the name of
that configuration. For example:

test {
    args("-excludegroups", "broken", "src/test/resources/testng.xml")
}

test {
    name = "All"
    args("src/test/resources/testng.xml")
}

The first configuration has no name, so it will be launched with the task "test",
while the second one can be run with the task "testAll".

The full series of articles on Kobalt can be found here.

The Kobalt diaries: templates

The latest addition to Kobalt is templates, also known as “archetypes” in Maven.

Templates are actions performed by plug-ins that create a set of files in your project. They are typically used when uou are beginning a brand new project and you want some default files to be created. Of course, nothing stops you from invoking templates even if you already have an existing project since templates can generate pretty much any kind of files. Here is how they work in Kobalt.

You can get a list of available templates with the --listTemplates parameter:

$ kobaltw --listTemplates
Available templates
  Plug-in: Kobalt
    "java"              Generate a simple Java project
    "kotlin"            Generate a simple Kotlin project
    "kobalt-plugin"     Generate a sample Kobalt plug-in project

You invoke a template with the --init parameter. Let’s call the "kobalt-plugin" template:

$ ./kobaltw --init kobalt-plugin
Template "kobalt-plugin" installed
Build this project with `./kobaltw assemble`

$ ./kobaltw assemble
          ╔════════════════════════════╗
          ║ Building kobalt-line-count ║
          ╚════════════════════════════╝
───── kobalt-line-count:compile
───── kobalt-line-count:assemble
  Created .\kobaltBuild\libs\kobalt-line-count-0.18.jar
  Created .\kobaltBuild\libs\kobalt-line-count-0.18-sources.jar
  Wrote .\kobaltBuild\libs\kobalt-line-count-0.18.pom
BUILD SUCCESSFUL (3 seconds)

The template was correctly installed, then it provided instructions on what to do next, which we followed, and now we have a fully working project. This one is particular since it’s a Kobalt plug-in and I’ll get back to it shortly. But before that, let’s drill a bit deeper into templates.

Templates would be pretty useless if they were limited to the default Kobalt distribution, so of course, you can invoke templates on plug-ins. Even plug-ins that you haven’t downloaded yet! Kobalt can download plug-ins from any Maven repository and run them.

To illustrate this, let’s see what templates the Kobalt Android plug-in offers:

$ kobaltw --listTemplates --plugins com.beust:kobalt-android:
  Downloaded https://jcenter.bintray.com/com/beust/kobalt-android/0.40/kobalt-android-0.40.pom
  Downloaded https://jcenter.bintray.com/com/beust/kobalt-android/0.40/kobalt-android-0.40.jar
Available templates
  Plug-in: Kobalt
    "java"              Generate a simple Java project
    "kotlin"            Generate a simple Kotlin project
    "kobaltPlugin"      Generate a sample Kobalt plug-in project
  Plug-in: Android
    "androidJava"       Generate a simple Android Java project
    "androidKotlin"     Generate a simple Kotlin Java project

Several things happened here. First of all, we are invoking the same --listTemplates command as earlier but this time, there is a new --plugins parameter. You pass this parameter a list of Maven id’s representing the Kobalt plug-ins you want Kobalt to install. This is similar to declaring these plug-ins in your build file, except that typically, when you run a template, you don’t have a build file yet. So this is an easy way to install plug-ins without requiring a build file.

Finally, notice that the Maven id used above, "com.beust:kobalt-android:" doesn’t have a version number and instead, ends with a colon. This is how you ask Kobalt to locate the latest version of the plug-in for you.

Kobalt responded by determining that the latest version of the Kobalt Android plug-in is 0.40, downloading it, installing it and then asking it what templates it provides. The Kobalt Android plug-in provides two templates, both of them creating a full-blown Android application, one written in Kotlin and one in Java. Let’s install the Kotlin one:

$ kobaltw --plugins com.beust:kobalt-android: --init androidKotlin
Template "androidKotlin" installed
Build this project with `./kobaltw assemble`

$ find .
./kobalt/src/Build.kt
./src/main/AndroidManifest.xml
./src/main/kotlin/com/example/MainActivity.kt
./src/main/res/drawable-hdpi/ic_launcher.png
./src/main/res/drawable-ldpi/ic_launcher.png
./src/main/res/drawable-mdpi/ic_launcher.png
./src/main/res/drawable-xhdpi/ic_launcher.png
./src/main/res/values/strings.xml
./src/main/res/values/styles.xml

$ ./kobaltw assemble
          ╔══════════════════════╗
          ║ Building kobalt-demo ║
          ╚══════════════════════╝
───── kobalt-demo:generateR
───── kobalt-demo:compile
───── kobalt-demo:proguard
───── kobalt-demo:generateDex
───── kobalt-demo:signApk
Created kobaltBuild\outputs\apk\kobalt-demo.apk
───── kobalt-demo:assemble
BUILD SUCCESSFUL (9 seconds)

We now have a complete Android application written in Kotlin.

Let’s go back to the template we built at the beginning of this article: the Kobalt plug-in called "kobalt-line-count-0.18.jar". It’s a valid Kobalt plug-in so how do we test it? We could upload it to JCenter and then invoke it with the --plugins parameter, but Kobalt provides another handy command line parameter to test such plug-ins locally: --pluginJarFiles. This parameter is similar to --plugins in that it installs a plug-in, except that it does so from a local jar file and not a remote Maven id.

Let’s install this plug-in and see which tasks are then available to us:

$ ./kobaltw --pluginJarFiles kobaltBuild/libs/kobalt-line-count-0.18.jar --tasks

List of tasks

...

  ═════ kobalt-line-count ═════
    dynamicTask         Dynamic task
    lineCount           Count the lines

...

As you can see, Kobalt has installed the kobalt-line-count plug-in, which then added its own tasks to Kobalt’s default ones. The Kobalt plug-in template appears to work fine. From this point on, you can edit it and create your own Kobalt plug-in.

Speaking of plug-in development, how hard is it to add templates to your Kobalt plug-in? Not hard at all! All you need to do is to implement the ITemplateContributor interface:

interface ITemplateContributor {
    val templates: List<ITemplate>
}

Each template provides a name, a description and a function that actually generates the files for the current project. Feel free to browse how Kobalt’s Android plug-in implements its templates.

The full series of articles on Kobalt can be found here.

Old school Apple ][ cracking

My first steps in programming probably go back about thirty-five years on the HP-38 and HP-41 but nothing will ever top the amazing times I had cracking games on the Apple ][ in the early 80s.

The Apple ][ and its DOS were extremely fertile grounds for software protection that led to some of the most fascinatingly intricate approaches to making sure that your program could not be easily copied. I’m not going to dive very deep into technical details about the Apple ][ architecture but the short version of it is that this computer let you reimplement how bytes are stored on the diskettes that you ship your software on, so needless to say that companies selling software for a living were more than happy to go ahead and do just that in attempt (mostly futile) to curb piracy.

I did a lot of cracking back in these days, mostly for the fun of it. Actually, I enjoyed getting my hands on games more for the pleasure of cracking them than actually playing them. However, one particular game resisted my attempts: “The Blade of Blackpoole”. A pretty mediocre adventure game in the style that was very popular then.

This copy protection used a lot of tricks that I just was not able to handle at the time. Remember, this was the early 80s. There was no Internet and pretty much nobody around me with enough technical knowledge of the Apple ][ to help me out. I had to figure things out on my own.

Recently, I had the crazy idea to revisit this old skeleton of mine and see if I can do better now, given all the tools and technology that the 21st century affords me. So I grabbed an image of the protected version of the game, fired a few emulators (I did this work both on Windows and Mac OS) and went to task.

It was slow at first but I was spooked to realize how much I actually remember of the Apple ][‘s internal architecture. And what I didn’t remember, the Internet happily provided for me. As it turns out, the Apple ][ cracking scene is still quite active (shout out to my inspiration for this work: a2_4am, who’s been actively cracking hundreds of Apple ][ games this past year alone]).

I carefully documented all my work cracking the Blade of Blackpoole in this document. I decided to store it in a separate file because it’s long and gruesome and goes into excruciating details about the Apple ][ and 6502 assembly. It’s not for the faint of heart, but I think you might find it interesting to follow even if you’re not completely familiar with all the technical details because it captures pretty accurately the timeless struggle between programmers who write copy protections and programmers who defeat them.

Fast forward to 2016. Copy protection is more alive than ever and the producer side seems to have struck a very serious blow to the cracking scene with Denuvo, a system that is proving extremely hard to crack and, to everyone’s surprise, which is actually an anti-temper mechanism and not an anti-piracy technology. There is so much to say about this that I’ll probable save it for another post, but in the meantime, I hope you enjoy my old school cracking report.

The Kobalt Diaries: Incremental Tasks

One of the recent additions to Kobalt is incremental tasks. This is the ability for each build task to be able to check whether it should run or not based on whether something has changed compared to the previous run. Here are a few quick outlines of how this feature works in Kobalt.

Overview

Kobalt’s incremental task architecture is based on checksums. You implement an incremental task by giving Kobalt a way to compute an input checksum and an output checksum. When the time comes to run your task, Kobalt will ask for your input checksum and it will compare it to that of the previous run. If they are different, your task is invoked. If they are identical, Kobalt then compares the two output checksums. Again, if they are different, your task is run, otherwise it’s skipped. Finally, Kobalt updates the output checksum on successul completion of your task.

This mechanism is extremely general and straightforward to implement for plug-in developers, who remain in full control of how exhaustive their checksum should be. You could decide to stick to the default MD5 checksums of the files and directories that are of interest to your task, or if you want to be faster, only check the timestamps of your file and return a checksum reflecting whether Kobalt should run you or not. And of course, checksums don’t even have to map to files at all: if your task needs to perform a costly download, it could first check a few HTTP headers and again, return a checksum indicating whether your task should run.

Having said that, build systems tend to run tasks that have files for inputs and outputs, so it seems logical to think about an incremental resolution that would be based not on checksums (which can be expensive to compute) but on file analyses. While a checksum can tell you “One of these N files has been modified”, it can’t tell you exactly which one, and such information can open the door to further incremental work (see below for more details).

One approach for file-based tasks could be for the build system to store the list of files along with some other data (timestamp or checksum) and then pass the relevant information to the task itself. The complication here is that file change resolution implies knowing the following three pieces of information:

  • Which files were modified.
  • Which files were added.
  • Which files were removed.

The downside is obviously that there is more bookkeeping required to preserve this information around between builds but the clear benefit is that if a task ends up being invoked, it can perform its own incremental work on just the files that need to be processed, whereas the checksum approach forces the task to perform its work on the entire set of inputs.

Implementation

Incremental tasks are not very different from regular tasks. An incremental task returns an IncrementalTaskInfo instance which is defined as follows:

class IncrementalTaskInfo(
	val inputChecksum: String?,
    val outputChecksum: () -> String?,
    val task: (Project) -> TaskResult)

The last parameter is the task itself and the first two are the input and output checksums of your task. Your task simply uses the @IncrementalTask annotation instead of the regular @Task and it needs to return an instance of that class:

@IncrementalTask(name = "compile", description = "Compile the source files")
fun taskCompile(project: Project) = IncrementalTaskInfo(/* ... */)

Most of Kobalt’s own tasks are now incremental (wherever that makes sense) including the Android plug-in. Here are a few timings showing incremental builds in action:

Kobalt

Task First run Second run
kobalt-wrapper:compile 627 ms 22 ms
kobalt-wrapper:assemble 9 ms 9 ms
kobalt-plugin-api:compile 10983 ms 54 ms
kobalt-plugin-api:assemble 1763 ms 154 ms
kobalt:compile 11758 ms 11 ms
kobalt:assemble 42333 ms 2130 ms
70 seconds 2 seconds

Android (u2020)

Task First run Second run
u2020:generateRInternalDebug 32350 ms 1652 ms
u2020:compileInternalDebug 3629 ms 24 ms
u2020:retrolambdaInternalDebug 668 ms 473 ms
u2020:generateDexInternalDebug 6130 ms 55 ms
u2020:signApkInternalDebug 449 ms 404 ms
u2020:assembleInternalDebug 0 ms 0 ms
43 seconds 2 seconds

Wrapping up

At the moment, Kobalt only supports checksum-based incremental tasks since that approach subsumes all the other approaches but I’m not ruling out adding input-specific incremental tasks in the future if there’s interest. In the meantime, checksums are working very well and pretty efficiently, even on large directories and/or large files.

If you are curious to try it yourself, please download Kobalt and report back!

The full series of articles on Kobalt can be found here.

A close look at Kotlin’s “let”

let is a pretty useful function from the Kotlin standard library defined as follows:

fun <T, R> T.let(f: (T) -> R): R = f(this)

You can refer to a previous article I wrote if you want to understand how this function works, but in this post, I’d like to take a look at the pros and cons of using let.

let is basically a scoping function that lets you declare a variable for a given scope:

File("a.txt").let {
    // the file is now in the variable "it"
}

There is another subtle use of let when applied to a nullable reference. The ?. operator
lets you make sure that the code in scope is only run if the expression is not null:

findUser(id)?.let {
    // only run if findUser() returned a non null value
}

After going back and forth about whether this idiom is superior to a simple null test, I am slowly leaning to abandoning it in favor of an if for the following reasons:

  • This idiom is only useful if you want to do an if that doesn’t have an else branch. I tend to view such constructs as suspicious since if without an else can be a source of bugs.

  • This idiom introduces a renaming. Either you use the default lambda syntax, in which case the renamed variable is implicitly called it, or you explicitly name the argument:

    val user = findUser(id)
    user?.let { foundUser ->
        // ...
    }
    

    This can occasionally be useful but sometimes, I just don’t feel like being forced to rename my variable.


  • Following the previous point, if doesn’t impose a renaming but Kotlin’s smart casting guarantees that you won’t have any surprise:

    val user = findUser(id)
    if (user != null) {
        // user is now a non null reference
    }
    

    Also, the fact that no new name was introduced and the variable keeps its name user the entire time improves readability in my opinion.

So for these reasons, I tend to default to a good old if these days. None of these arguments are deal breakers, it’s mostly a stylistic preference at this point. Let’s see if I’ll change my mind over the next few months.

The Kobalt diaries: profiles

When I started thinking about how profiles should work in Kobalt, I realized that the simplest approach I’d like to see in a build tool is defining a boolean variable and having if statements in my build file. So that’s exactly how Kobalt’s profiles are implemented.

You start by defining boolean values initialized to false in your build file:

  val experimental = false
  val premium = false

Then you use this variable wherever you need it in your build file:

  val p = javaProject {
      name = if (experimental) "project-exp" else "project"
      version = "1.3"
      ...

Finally, you invoke ./kobaltw with the --profiles parameter followed by the profiles you want to activate, separated by a comma:

  ./kobaltw -profiles experimental,premium assemble

Keep in mind that since your build file is a real Kotlin source file,
you can use these profile variables pretty much anywhere, e.g.:

dependencies {
    if (experimental)
        "com.squareup.okhttp:okhttp:2.4.0"
    else
        "com.squareup.okhttp:okhttp:2.5.0",

And that’s it.

The full series of articles on Kobalt can be found here.

The Kobalt diaries: it’s the little things

When I embarked on the ridiculously ambitious goal of writing a build tool, I had plans to tackle both big problems and small problems. My previous (and probably future) blog post cover the big problems such as performance, plug-in architecture and DSL syntax, but in this post, I’m going to cover a few little things that I was quite happy to finally be able to get from my build tool.

I’ve always found it a hassle to keep up with the latest versions of the dependencies of my build, especially since it’s its job to tell me. Therefore, Kobalt has a handy --checkVersions parameter that will check to see if it can find any new version of your dependencies:

$ ./kobaltw --checkVersions
New versions found:
        org.jetbrains.kotlin:kotlin-compiler-embeddable:1.0.0-beta-2423
        org.jetbrains.kotlin:kotlin-stdlib:1.0.0-beta-2423
        com.squareup.okhttp:okhttp:2.6.0
        com.squareup.retrofit:retrofit:2.0.0-beta2

Another convenient switch is --resolve, which looks up a dependency and gives you some information about it, such as which Maven repo it is found in and its own dependency tree. You can also use an id without a version (e.g. org.testng:testng:) to ask Kobalt to find the most recent version of that artifact:

$ ./kobaltw --resolve org.testng:testng:
╔══════════════════════════════════════════════════════════════════════════════════╗
║                                     org.testng:testng:                           ║
║           http://repo1.maven.org/maven2/org/testng/testng/6.9.9/testng-6.9.9.jar ║
╚══════════════════════════════════════════════════════════════════════════════════╝
╟ junit:junit:4.10
║      ╙ org.hamcrest:hamcrest-core:1.1
╟ com.beust:jcommander:1.48
╟ org.apache.ant:ant:1.7.0
║      ╙ org.apache.ant:ant-launcher:1.7.0
╟ org.yaml:snakeyaml:1.15
╙ org.beanshell:bsh:2.0b4

Finally, I’ve always been bugged by what I consider a glaring omission of the Gradle Android plug-in: not being able to run my applications. The plug-in generates tasks for the various variants of your application (assembleDevDebug, assembleDevRelease, installDevDebug, etc…) but strikingly, no "run" task. I’m happy to report that Kobalt’s Android plug-in supports exactly that. To see it in action, clone the Kobalt example and follow the instructions at the bottom of the README:

$ ./kobaltw runFreeDebug // build, install and launch that variant
$ ./kobaltw runFreeRelease // build, install and launch that variant

I’ve made a lot of improvements to the Android plug-in lately, but that will be the topic for another post.

The full series of articles on Kobalt can be found here.

The Kobalt diaries: annotation processing

I recently added apt support to Kobalt, which is a requirement for a build system these days, and something interesting happened.

First of all, the feature itself in Kobalt: pretty straightforward. The apt plug-in adds a new dependency directive similar to compile:

dependencies {
    apt("com.google.dagger:dagger:2.0.2")
}

The processing tool can be further configured (output directory, arguments, etc…) with a separate apt directive:

apt {
    outputDir = "generated/sources/apt"
}

In order to test this new feature, I decided to implement a simple annotation processor project and I went for a Version class generator. As I wrote this processor, I realized that it was actually something I could definitely use in my other projects.

Of course, you can always simply hard code the version number of your application in a source file but that version number is typically something that’s useful outside of your code: you might need it in your build file, or when you generate your artifacts, or maybe other projects need to refer to it. Therefore, it often makes sense to isolate that version number in a property file and have every entity that needs it read it from that property file.

This is how version-processor was born. It’s pretty simple really: all you need to do is annotate one of your classes with @Version and a GeneratedVersion.java file is created, which you can then refer to. That version number can either be hardcoded or specified in a properties file. Head over to the project’s main page for the details.

And of course, it’s built with Kobalt and if you are curious, here is the processor’s build file:

val processor = javaProject {
    name = "version-processor"
    group = "com.beust"
    artifactId = name
    version = "0.2"
    directory = "processor"

    assemble {
        mavenJars {}
    }

    jcenter {
        publish = true
    }
}

Happy version generating!

The full series of articles on Kobalt can be found here.

TensorFlow’s rough exterior

Like many others, I have paid very close attention to Google’s TensorFlow announcement and I’m planning to invest a decent amount of time to dive into it and understand it but watching Jeff Dean’s video about it, I couldn’t help but take notice of one of the code samples that he shows:

graph = tf.Graph()
with graph.AsDefault():
  examples = tf.constant(train_dataset)
  labels = tf.constants(train_labels)
  W = tf.Variables(tf.truncated_normal(rows*cols, num_labels]))
  b = tf.Variables(tf.zeros([num_labels]))

  logits = tf.mat_mul(examples, W) + b
  loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, labels))

What a mess…

I realize this is just one of the two front ends (Python, the other being in C++) but the syntactic conventions of the snippet above are all over the map.

I see capitalized functions (Graph()) when most of the functions are lowercased. Capital variables (W) and lowercase ones (b), both of which the result of the same function. Functions using underscores and others using capitalized camel case. There just doesn’t seem to be any rhyme nor reason to the conventions.

The only style that’s not represented in this short snippet is straight camel case.

This hurts my eyes. Hopefully, spending some time with this fascinating tool will demystify it somewhat. Or maybe it will motivate me to write a front end I feel more comfortable with, say in Kotlin.