refactored java version (untested...)

This commit is contained in:
Marcel M. Otte 2013-12-31 16:53:25 +00:00
parent 4815d6449b
commit 2a966fb9c1
2 changed files with 295 additions and 208 deletions

View File

@ -6,209 +6,282 @@ import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
/** /**
* Written by Marcel M. Otte, (c) 2013 * Written by Marcel M. Otte, (c) 2013 For use under the BSD 2-clause License,
* For use under the BSD 2-clause License, or in other words: * or in other words: Do what you want with it as long as you leave all
* Do what you want with it as long as you leave all copyright notices where they are * copyright notices where they are and don't bother me when you break your pc.
* and don't bother me when you break your pc. :) * :)
*/ */
public class CmdOptions { public class CmdOptions {
private static CmdOptions instance; private static CmdOptions instance;
private static class Option { public static class Option {
public String name; private String name;
public String cmdOption; private ArrayList<String> cmd;
public String longCmdOption; private String description;
public String description; private ArrayList<String> defaultParameter;
public String defaultParameter;
public String[] possibleParams;
public String[] alternatives;
public boolean set;
public ArrayList<String> values;
public Option() { private ArrayList<String> possibleParams;
values = new ArrayList<String>(); private boolean set;
} private ArrayList<String> values;
public String toString() { public ArrayList<String> getValues() {
String ret = name + " (" + longCmdOption + (cmdOption != null ? "/" + cmdOption : "") + ")" return values;
+ (defaultParameter != null ? ": default=" + defaultParameter : "") + (description != null ? "\n\t\t" + description : ""); }
if (possibleParams != null) {
boolean start = true;
ret += "\n\t\t(Possible parameters: ";
for (String s : possibleParams) {
ret += (start ? "" : ", ") + s;
start = false;
}
ret += ")";
}
if (set) {
ret += "\n\t\t--> current Setting: ";
if (values.size() > 0) {
boolean start = true;
for (String s : values) {
ret += (start ? "" : ",") + s;
start = false;
}
} else {
ret += "true";
}
// ret += "\n";
}
return ret;
}
}
private HashMap<String, Option> options; public ArrayList<String> getDefaultParameter() {
return defaultParameter;
}
private CmdOptions() { public Option() {
options = new HashMap<String, Option>(); values = new ArrayList<String>();
this.setOption("help", "--help", "-h", null, "Show all possible options and their parameters.", null, new String[] { "-?" }); cmd = new ArrayList<String>();
} defaultParameter = new ArrayList<String>();
possibleParams = new ArrayList<String>();
}
public static CmdOptions i() { public Option addCommand(String cmd) {
if (instance == null) { this.cmd.add(cmd);
instance = new CmdOptions(); return this;
} }
return instance;
}
public String[] getOption(String name) { public Option addDefaultParameter(String d) {
if (options.get(name).values.size() > 0) this.defaultParameter.add(d);
return options.get(name).values.toArray(new String[0]); return this;
else if (options.get(name).defaultParameter != null) }
return new String[] { options.get(name).defaultParameter };
return null;
}
public Integer[] getOptionAsInt(String name) { public Option addPossibleParameter(String p) {
if (options.get(name).values.size() > 0) { this.possibleParams.add(p);
ArrayList<Integer> list = new ArrayList<Integer>(); return this;
for (String o : options.get(name).values) { }
list.add(Integer.parseInt(o));
}
return list.toArray(new Integer[0]);
} else if (options.get(name).defaultParameter != null)
return new Integer[] { Integer.parseInt(options.get(name).defaultParameter) };
return null;
}
public Double[] getOptionAsDouble(String name) { public Option addValue(String value) {
if (options.get(name).values.size() > 0) { this.values.add(value);
ArrayList<Double> list = new ArrayList<Double>(); return this;
for (String o : options.get(name).values) { }
list.add(Double.parseDouble(o));
}
return list.toArray(new Double[0]);
} else if (options.get(name).defaultParameter != null)
return new Double[] { Double.parseDouble(options.get(name).defaultParameter) };
return null;
}
public boolean isSet(String option) { public String getName() {
return options.get(option).set; return name;
} }
public boolean isSet(String option, String parameter) { public Option setName(String name) {
for (String o : options.get(option).values) { this.name = name;
if (o.equals(parameter)) { return this;
return true; }
}
}
return false;
}
public void setOption(String name, String longcmd, String cmd, String defaultparam, String description) { public String getDescription() {
this.setOption(name, longcmd, cmd, defaultparam, description, null, null); return description;
} }
public void setOption(String name, String longcmd, String cmd, String defaultparam, String description, String[] possibleParams, String[] alternatives) { public Option setDescription(String description) {
Option o = new Option(); this.description = description;
o.cmdOption = cmd; return this;
o.name = name; }
o.longCmdOption = longcmd;
o.defaultParameter = defaultparam;
o.description = description;
o.alternatives = alternatives;
o.possibleParams = possibleParams;
options.put(name, o);
}
public String toString(boolean help) { public boolean isSet() {
StringBuilder b = new StringBuilder(); return set;
if (help) { }
b.append("Possible options:\n");
}
b.append("-options\n");
Option[] vars = options.values().toArray(new Option[0]);
Arrays.sort(vars, new Comparator<Option>() {
@Override
public int compare(Option o1, Option o2) {
return o1.name.compareTo(o2.name);
}
});
for (Option o : vars) {
b.append("\t").append(o.toString()).append("\n");
}
b.append("/options\n");
return b.toString();
}
public void parse(String[] args) { public Option setSet(boolean set) {
// now parse this.set = set;
if (args.length > 0) { return this;
int i = 0; }
String arg = null;
// iterate through all options
for (; i < args.length; ++i) {
arg = args[i];
Option o = null;
// search for correct option
for (Option op : options.values()) {
if (arg.equals(op.longCmdOption) || op.cmdOption != null && arg.equals(op.cmdOption) || op.alternatives != null
&& Arrays.asList(op.alternatives).contains(arg)) {
o = op;
break;
}
}
// if it is unknown
if (o == null) {
System.err.println("Unrecognized option '" + arg + "'");
continue;
}
o.set = true;
// now iterate through the parameters
int j = i + 1;
while (args.length > j && !args[j].startsWith("-")) {
if (o.possibleParams != null) {
if (Arrays.asList(o.possibleParams).contains(args[j]))
o.values.add(args[j]);
else
System.err.println("Parameter \"" + args[j] + "\" for Option \"" + o.name + "\" not allowed!");
} else {
o.values.add(args[j]);
}
++j;
}
i = j - 1;
}
}
if (options.get("help").set) {
System.out.println(this.toString(true));
System.exit(0);
}
// set default for that options that aren't set public String toString() {
for (Option o : options.values()) { String ret = name + " (";
if (!o.set && o.defaultParameter != null && o.defaultParameter.equals("")) { for (String s : cmd) {
System.err.println(o.name + " (" + o.cmdOption + "): has no default parameter and has to be set on commandline!"); ret += s + ", ";
System.exit(1); }
} ret += ")"
if (!o.set && o.defaultParameter != null) + (defaultParameter != null ? ": default="
o.values.add(o.defaultParameter); + defaultParameter : "")
} + (description != null ? "\n\t\t" + description : "");
System.out.println(this.toString(false)); if (possibleParams != null) {
} boolean start = true;
ret += "\n\t\t(Possible parameters: ";
for (String s : possibleParams) {
ret += (start ? "" : ", ") + s;
start = false;
}
ret += ")";
}
if (set) {
ret += "\n\t\t--> current Setting: ";
if (values.size() > 0) {
boolean start = true;
for (String s : values) {
ret += (start ? "" : ",") + s;
start = false;
}
} else {
ret += "true";
}
// ret += "\n";
}
return ret;
}
}
private HashMap<String, Option> options;
private CmdOptions() {
options = new HashMap<String, Option>();
this.createOption("help")
.setDescription(
"Show all possible options and their parameters.")
.addCommand("--help").addCommand("-h").addCommand("-?");
}
public static CmdOptions i() {
if (instance == null) {
instance = new CmdOptions();
}
return instance;
}
public Option createOption(String name) {
Option o = new Option();
o.setName(name);
this.options.put(name, o);
return o;
}
public String[] getOption(String name) {
if (options.get(name).values.size() > 0)
return options.get(name).values.toArray(new String[0]);
else if (options.get(name).defaultParameter != null)
return options.get(name).getValues().toArray(new String[0]);
return null;
}
public Integer[] getOptionAsInt(String name) {
if (options.get(name).values.size() > 0) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (String o : options.get(name).values) {
list.add(Integer.parseInt(o));
}
return list.toArray(new Integer[0]);
} else if (options.get(name).getDefaultParameter().size() > 0) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (String o : options.get(name).getDefaultParameter()) {
list.add(Integer.parseInt(o));
}
return list.toArray(new Integer[0]);
}
return null;
}
public Double[] getOptionAsDouble(String name) {
if (options.get(name).values.size() > 0) {
ArrayList<Double> list = new ArrayList<Double>();
for (String o : options.get(name).values) {
list.add(Double.parseDouble(o));
}
return list.toArray(new Double[0]);
} else if (options.get(name).getDefaultParameter().size() > 0) {
ArrayList<Double> list = new ArrayList<Double>();
for (String o : options.get(name).getDefaultParameter()) {
list.add(Double.parseDouble(o));
}
return list.toArray(new Double[0]);
}
return null;
}
public boolean isSet(String option) {
return options.get(option).set;
}
public boolean isSet(String option, String parameter) {
for (String o : options.get(option).values) {
if (o.equals(parameter)) {
return true;
}
}
return false;
}
public String toString(boolean help) {
StringBuilder b = new StringBuilder();
if (help) {
b.append("Possible options:\n");
}
b.append("-options\n");
Option[] vars = options.values().toArray(new Option[0]);
Arrays.sort(vars, new Comparator<Option>() {
@Override
public int compare(Option o1, Option o2) {
return o1.name.compareTo(o2.name);
}
});
for (Option o : vars) {
b.append("\t").append(o.toString()).append("\n");
}
b.append("/options\n");
return b.toString();
}
public void parse(String[] args) {
// now parse
if (args.length > 0) {
int i = 0;
String arg = null;
// iterate through all options
for (; i < args.length; ++i) {
arg = args[i];
Option o = null;
// search for correct option
for (Option op : options.values()) {
for (String s : op.cmd)
if (arg.equals(s)) {
o = op;
break;
}
}
// if it is unknown
if (o == null) {
System.err.println("Unrecognized option '" + arg + "'");
continue;
}
o.set = true;
// now iterate through the parameters
int j = i + 1;
while (args.length > j && !args[j].startsWith("-")) {
if (o.possibleParams.size() > 0) {
if (o.possibleParams.contains(args[j]))
o.values.add(args[j]);
else
System.err.println("Parameter \"" + args[j]
+ "\" for Option \"" + o.name
+ "\" not allowed!");
} else {
o.values.add(args[j]);
}
++j;
}
i = j - 1;
}
}
if (options.get("help").set) {
System.out.println(this.toString(true));
System.exit(0);
}
// set default for that options that aren't set
for (Option o : options.values()) {
if (!o.set && o.defaultParameter != null
&& o.defaultParameter.equals("")) {
System.err
.println(o.name
+ " ("
+ o.getName()
+ "): has no default parameter and has to be set on commandline!");
System.exit(1);
}
if (!o.set && o.defaultParameter != null)
o.values.addAll(o.defaultParameter);
}
System.out.println(this.toString(false));
}
} }

View File

@ -5,39 +5,53 @@ import to.mmo.cmdlineoptions.CmdOptions;
public class Example { public class Example {
public static void initOptions() { public static void initOptions() {
CmdOptions.i().setOption("name", // give the option a name which you can CmdOptions.i().createOption("name").// give the option a name which you
// can
// remember within your project // remember within your project
"--name", // it's always good to define a long commandline addCommand("--name") // it's always good to define a long
// parameter with a describing name // commandline parameter with a
"-n", // of course, programmer are always lazy so give them an // describing name
// possibility to shortcut your option
"whatever", // a default parameter is good if you need the .addCommand("-n") // of course, programmer are always lazy so
// option within your program, but don't care when // give them an possibility to shortcut your
// it's omitted on execution // option
"an example option"); // And of course a description... for the .addDefaultParameter("whatever")// a default parameter is good
// help readers, the few among us... // if you need the option within
CmdOptions.i().setOption( // your program, but don't care
"complex", // see above // when it's omitted on
"--complex", "-c", // execution
null, // yes you can omit a default parameter, but you have to .setDescription("an example option.");// And of course a
// check later in your project if that option is set. // description... for
"a complex commandline parameter", // the help readers, the
new String[] { "something", "another_something" }, // few among us...
CmdOptions
.i()
.createOption("name")
.addCommand("--complex")
// see above
// yes you can omit a default parameter, but you have to
// check later in your project if that option is set.
.addCommand("-c")
.setDescription("a complex commandline parameter")
.addPossibleParameter("something")
// here the fun begins, you can set as much possible parameters // here the fun begins, you can set as much possible parameters
// as you want, keep in mind to leave out whitespaces! // as you want, keep in mind to leave out whitespaces!
// and remember that you limit your option to exactly that // and remember that you limit your option to exactly that
// parameters! // parameters!
new String[] { "-i", "--ccp" }); .addPossibleParameter("another_something")
// here you are able to add some more alternatives for that option, so // here you are able to add some more alternatives for that
// here you can use "--complex", "-c", "-i" and "--ccp" to trigger this // option, so here you can use "--complex", "-c", "-i" and
// option. // "--ccp" to trigger this option.
.addCommand("-i").addCommand("--ccp");
} }
public static void main(String[] args) { public static void main(String[] args) {
initOptions(); // init the commandline options initOptions(); // init the commandline options
CmdOptions.i().parse(args); // parse them, and your done. --help is automatically set, so you can use it right away. CmdOptions.i().parse(args); // parse them, and your done. --help is
// automatically set, so you can use it
// right away.
// now your program follows, using this options... // now your program follows, using this options...
} }