Parse a string as if it were a command with parameters and parameters

I have this Java enumeration:

public enum Commands
{
    RESIZE_WINDOW("size -size"),
    CREATE_CHARACTER("create-char -name"),
    NEW_SCENE("scene -image"),
    DIALOG("d -who -words"),
    PLAY_SOUND("sound -file --blocking=false"),
    FADE_TO("fade-to -file"),
    WAIT("w -length=auto");
}

I want to be able to parse these lines and extract:

  • team name (e.g. create-char)
  • required parameters (e.g. -name)
  • optional parameters with a default value (for example, --blocking=false)

I looked at org.apache.commons.cli, but it seems to crash according to the first criteria (different team names) and very verbose.

Any library suggestions?

(This will be used to analyze the scripting language if this context helps.)

Edit: An example input in a scripting language will be d John "Hello World"- the text in a few words will be enclosed in quotation marks.

+3
1

, CLI, ""; a DSL. , , , (CLI, ) .

, CLI ( ) . , "", ( "" arg , ..), , , ..

, . DSL, , , , .. , .

( ) , (natural-cli - ), -

static class CommandLine {
    HashMap<String,Options> options = new HashMap<String,Options>();

    public void register(String cmd, Options opts) {
        options.put(cmd, opts);
    }

    public void parse(String line) {
        // a better parser here would handle quoted strings
        String[] split = line.split("\\s");

        String cmd = split[0];
        String[] args = new String[split.length-1];
        if (args.length > 0)
            System.arraycopy(split, 1, args, 0, args.length);

        Options opts = options.get(cmd);
        if (opts == null) 
            ; // handle unknown command
        else {
            opts.parse(args);
            // handle results...
            opts.reset(); // required?
        }
    }
}

public static void main(String[] args) throws Exception {

    CommandLine cl = new CommandLine();
    cl.register("size", new Options());        // This will vary based on library Some
    cl.register("create-char", new Options()); // require subclasses, others use builder
    //...                                         pattern, or other means.

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
        cl.parse(in.readLine());
    }
}

+6

Source: https://habr.com/ru/post/1763649/


All Articles