EventDiscriminatorUsageFormatter.java

package client.teavm.common.parameter.usage;

import com.beust.jcommander.DefaultUsageFormatter;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.ParameterDescription;
import com.beust.jcommander.Parameters;

import java.util.List;
import java.util.Map;

/**
 * Change the usage message to represent a map for web worker event name in the JSON
 * schema. This is used to filter error messages for the relevant event schema
 * identified by the discriminator path.
 *
 * @author khaendel
 *
 */
public class EventDiscriminatorUsageFormatter extends DefaultUsageFormatter {

    private final JCommander commander;

    public EventDiscriminatorUsageFormatter(JCommander commander) {
        super(commander);
        this.commander = commander;
    }

    @Override
    public void appendMainLine(StringBuilder out, boolean hasOptions, boolean hasCommands, int indentCount,
                               String indent) {

    }

    @Override
    public void appendAllParametersDetails(StringBuilder out, int indentCount, String indent,
                                           List<ParameterDescription> sortedParameters) {
    }

    public void usage(StringBuilder out, String indent) {
        boolean hasCommands = !commander.getCommands().isEmpty();

        // Indentation constants
        final int descriptionIndent = 6;
        final int indentCount = indent.length() + descriptionIndent;

        // Append commands if they were specified
        if (hasCommands) {
            appendCommands(out, indentCount, descriptionIndent, indent);
        }
    }

    public void appendCommands(StringBuilder out, int indentCount, int descriptionIndent, String indent) {
        out.append("const discriminatorMap = {\n");
        int commandNum = 0;
        for (Map.Entry<JCommander.ProgramName, JCommander> commands : commander.getRawCommands().entrySet()) {
            Object arg = commands.getValue().getObjects().get(0);
            Parameters p = arg.getClass().getAnnotation(Parameters.class);

            if (p == null || !p.hidden()) {
                JCommander.ProgramName progName = commands.getKey();
                String dispName = progName.getDisplayName();
                out.append("  ").append(dispName).append(": \"#/oneOf/").append(commandNum++).append("/\",\n");
            }
        }
        out.append("};\n");
    }

}