i'm kinda struggling apache commons-cli v1.3 , haven't found practical solution following problem yet:
i have command line tool - depending on specified parameters - creates string (or reads local file), possible edits inline, , optionally displays, writes said string local file or sends via http request server.
so have options "c" "create", "r" "read", "e" "edit" (via cli), "d" display, "w" "write", , "p" "push server"
obviously combinations possible. e.g. should possible create string , push without reading or writing from/to file. also, should possible create , write without pushing, , on...
so semantics of parameters are:
("c" or ("r" ["e"])) ["d" "w" "p"]
obviously, when string "c"reated, must not "r"ead. when "c"reating, i'd use interactive input cli-parser. when "r"eading, want allow user "e"dit via interactive input cli. rest of parameters kinda optional.
next: when "r"eading, filename/path needs specified. also, when "w"riting, necessary. anyhow, should possible specify file read , second file write to. there 2 arguments filenames, both optional.
the resulting syntax this:
tool -cp tool -rp "filenametoread" tool -rdwp "filenametoread" "filenametowrite" tool -cw "filenametowrite"
and on.
i'm bit lost here. how configure commons-cli have 2 arguments filenames, required based on parameters (options) specified? possible?
unfortunately, commons cli has no way of specifying interdependent options that. handle that, need own if
checks. example, this
commandlineparser parser = new posixparser(); options options = new options(); options.addoption(new option("h", "help", false, "display message")); options.addoption(new option("c", "create", true, "create file")); options.addoption(new option("r", "read", truee, "read file")); options.addoption(new option("e", "edit", false, "edit file")); options.addoption(new option("d", "display", false, "display file")); options.addoption(new option("w", "write", false, "write file")); options.addoption(new option("p", "push", false, "push file")); try { commandline commandline = parser.parse(options, args); if (commandline.hasoption("h")) { showhelp(options); system.exit(0); } // validate commandline // obviously, these can split give more helpful error messages if ((!(commandline.hasoption("c") ^ (commandline.hasoption("r") || commandline.hasoption("e")))) || !(commandline.hasoption("d") ^ commandline.hasoption("w") ^ commandline.hasoption("p"))) { throw new parseexception("invalid combination"); } if ((!commandline.hasoption("c") && !commandline.hasoption("r")) { throw new parseexception("missing required arg"); } // rest of logic } catch (parseexception pe) { throw new parseexception("bad arguments\n" + pe.getmessage()); }
Comments
Post a Comment