Groovy script to apply licence headers
Feb 23, 2017
1 minute read

There are licences that ask you to copy their licence header on the start of all your source files. Nobody wants to this task manually. So I created a simple groovy script which do this task for me.

class LicenceHeader {

    static void main(String... args) {
        if (args.size() != 3) throw new IllegalArgumentException(
            "Usage: [path/to/licence/file] [path/to/project/root] " +
                "[endings separated by comma eg. java,groovy,kotlin]")

        String header = args[0]
        String project = args[1]
        String[] endings = args[2].split("[,;:.]").collect { ".$it" }

        def licence = new String(Paths.get(header).readBytes())
        applyLicence(licence, Paths.get(project), endings)

    static void applyLicence(
        String licence,
        Path projectRoot,
        String[] endings
    ) {
                .filter { Files.isRegularFile(it) }
                .filter { path -> endings.any { path.toString().endsWith(it) } }
                .forEach { path ->
            def content = new String(path.readBytes())
            if (content.startsWith("/*")) return
            def newContent = licence + "\n\n" + content
            println("Writing licence header to $path")
            Files.write(path, newContent.getBytes())

To use this script make sure you have groovy installed (easiest way throught sdkman) and write groovy LicenceHeader [path/to/licence] [path/to/project/root] [file endings].