Skip to content

Instantly share code, notes, and snippets.

@darylteo
Last active August 29, 2015 14:04
Show Gist options
  • Save darylteo/9cdb9b8e32be4197e72e to your computer and use it in GitHub Desktop.
Save darylteo/9cdb9b8e32be4197e72e to your computer and use it in GitHub Desktop.
Simple Plugin in Java for Gradle
// usage
ssh {
// dsl form
options {
foo 'bar'
name project.name
flag(false) // also possible
}
// property form
options.hello = 'world'
}
println ssh.options
// { foo: "bar", name: "??", flag: false, hello: "world" }
package org.company.gradle;
import groovy.lang.Closure;
import groovy.lang.MissingMethodException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import java.util.HashMap;
import java.util.Map;
/**
* Created by dteo on 18/07/2014.
*/
class SSHPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
// this namespaces your configuration to ssh { }
project.getExtensions().create("ssh", SSHConfiguration.class);
}
}
// this will need to be an extension that you create in your plugin itself
class SSHConfiguration {
private SSHOptions options = new SSHOptions();
public SSHOptions getOptions() {
return this.options;
}
// this will accept ssh { options { } }
public void options(Closure closure) {
closure.setResolveStrategy(Closure.DELEGATE_FIRST);
closure.setDelegate(this.options);
closure.call(this.options);
}
}
class SSHOptions extends GroovyObjectSupport {
private Map<String, Object> args = new HashMap<String,Object>();
public String get(String name) {
return this.args.get(name);
}
public Map<String, String> getAll() {
return this.args;
}
public void set(String name, Object value) {
if (value != null) {
this.args.put(name, value.toString());
} else {
this.args.remove(name);
}
}
public Object invokeMethod(String name, Object values) {
Object[] args = (Object[]) values;
if (args == null || args.length != 1) {
throw new MissingMethodException(name, SSHOptions.class, args);
}
this.args.put(name, args[0]);
return null;
}
}