All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.vtence.cli.args.Operand Maven / Gradle / Ivy

The newest version!
package com.vtence.cli.args;

import com.vtence.cli.ParsingException;
import com.vtence.cli.coercion.StringCoercer;
import com.vtence.cli.coercion.TypeCoercer;

import java.util.Map;

public class Operand extends Argument implements OperandSpec {

    private String displayName;
    private String description;

    public static Operand named(String name) {
        return new Operand(name, new StringCoercer());
    }

    protected Operand(String name, TypeCoercer type) {
        super(name, type);
    }

    public Operand as(String argument) {
        this.displayName = argument;
        return this;
    }

    public String getDisplayName() {
        return displayName != null ? displayName : name.toUpperCase();
    }

    public Operand describedAs(String message) {
        this.description = message;
        return this;
    }

    public String getDescription() {
        return description;
    }

    public boolean hasDescription() {
        return description != null;
    }

    public  Operand ofType(Class type) {
        return ofType(coercerFor(type));
    }

    @SuppressWarnings("unchecked")
    public  Operand ofType(TypeCoercer type) {
        this.typeCoercer = (TypeCoercer) type;
        return (Operand) this;
    }

    public Operand using(Map, TypeCoercer> coercers) {
        this.coercers.putAll(coercers);
        return this;
    }

    public T get(Args args) {
        return args.get(name);
    }

    public void printTo(Help help) {
        help.add(this);
    }

    public void handle(Args detected, Input args) throws ParsingException {
        if (args.empty()) throw new MissingOperandException(name);
        detected.put(name, value(args));
    }

    private T value(Input args) throws InvalidArgumentException {
        return convert(args.next());
    }
}