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;
/**
* Written by Marcel M. Otte, (c) 2013
* For use under the BSD 2-clause License, or in other words:
* Do what you want with it as long as you leave all copyright notices where they are
* and don't bother me when you break your pc. :)
* Written by Marcel M. Otte, (c) 2013 For use under the BSD 2-clause License,
* or in other words: Do what you want with it as long as you leave all
* copyright notices where they are and don't bother me when you break your pc.
* :)
*/
public class CmdOptions {
private static CmdOptions instance;
private static CmdOptions instance;
private static class Option {
public String name;
public String cmdOption;
public String longCmdOption;
public String description;
public String defaultParameter;
public String[] possibleParams;
public String[] alternatives;
public boolean set;
public ArrayList<String> values;
public static class Option {
private String name;
private ArrayList<String> cmd;
private String description;
private ArrayList<String> defaultParameter;
public Option() {
values = new ArrayList<String>();
}
private ArrayList<String> possibleParams;
private boolean set;
private ArrayList<String> values;
public String toString() {
String ret = name + " (" + longCmdOption + (cmdOption != null ? "/" + cmdOption : "") + ")"
+ (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;
}
}
public ArrayList<String> getValues() {
return values;
}
private HashMap<String, Option> options;
public ArrayList<String> getDefaultParameter() {
return defaultParameter;
}
private CmdOptions() {
options = new HashMap<String, Option>();
this.setOption("help", "--help", "-h", null, "Show all possible options and their parameters.", null, new String[] { "-?" });
}
public Option() {
values = new ArrayList<String>();
cmd = new ArrayList<String>();
defaultParameter = new ArrayList<String>();
possibleParams = new ArrayList<String>();
}
public static CmdOptions i() {
if (instance == null) {
instance = new CmdOptions();
}
return instance;
}
public Option addCommand(String cmd) {
this.cmd.add(cmd);
return this;
}
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 new String[] { options.get(name).defaultParameter };
return null;
}
public Option addDefaultParameter(String d) {
this.defaultParameter.add(d);
return this;
}
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).defaultParameter != null)
return new Integer[] { Integer.parseInt(options.get(name).defaultParameter) };
return null;
}
public Option addPossibleParameter(String p) {
this.possibleParams.add(p);
return this;
}
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).defaultParameter != null)
return new Double[] { Double.parseDouble(options.get(name).defaultParameter) };
return null;
}
public Option addValue(String value) {
this.values.add(value);
return this;
}
public boolean isSet(String option) {
return options.get(option).set;
}
public String getName() {
return name;
}
public boolean isSet(String option, String parameter) {
for (String o : options.get(option).values) {
if (o.equals(parameter)) {
return true;
}
}
return false;
}
public Option setName(String name) {
this.name = name;
return this;
}
public void setOption(String name, String longcmd, String cmd, String defaultparam, String description) {
this.setOption(name, longcmd, cmd, defaultparam, description, null, null);
}
public String getDescription() {
return description;
}
public void setOption(String name, String longcmd, String cmd, String defaultparam, String description, String[] possibleParams, String[] alternatives) {
Option o = new Option();
o.cmdOption = cmd;
o.name = name;
o.longCmdOption = longcmd;
o.defaultParameter = defaultparam;
o.description = description;
o.alternatives = alternatives;
o.possibleParams = possibleParams;
options.put(name, o);
}
public Option setDescription(String description) {
this.description = description;
return this;
}
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 boolean isSet() {
return set;
}
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()) {
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);
}
public Option setSet(boolean set) {
this.set = set;
return this;
}
// 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.cmdOption + "): has no default parameter and has to be set on commandline!");
System.exit(1);
}
if (!o.set && o.defaultParameter != null)
o.values.add(o.defaultParameter);
}
System.out.println(this.toString(false));
}
public String toString() {
String ret = name + " (";
for (String s : cmd) {
ret += s + ", ";
}
ret += ")"
+ (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;
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,38 +5,52 @@ import to.mmo.cmdlineoptions.CmdOptions;
public class Example {
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
"--name", // it's always good to define a long commandline
// parameter with a describing name
"-n", // of course, programmer are always lazy so give them an
// possibility to shortcut your option
"whatever", // a default parameter is good if you need the
// option within your program, but don't care when
// it's omitted on execution
"an example option"); // And of course a description... for the
// help readers, the few among us...
CmdOptions.i().setOption(
"complex", // see above
"--complex", "-c",
null, // yes you can omit a default parameter, but you have to
// check later in your project if that option is set.
"a complex commandline parameter",
new String[] { "something", "another_something" },
addCommand("--name") // it's always good to define a long
// commandline parameter with a
// describing name
.addCommand("-n") // of course, programmer are always lazy so
// give them an possibility to shortcut your
// option
.addDefaultParameter("whatever")// a default parameter is good
// if you need the option within
// your program, but don't care
// when it's omitted on
// execution
.setDescription("an example option.");// And of course a
// description... for
// the help readers, the
// 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
// as you want, keep in mind to leave out whitespaces!
// and remember that you limit your option to exactly that
// parameters!
new String[] { "-i", "--ccp" });
// here you are able to add some more alternatives for that option, so
// here you can use "--complex", "-c", "-i" and "--ccp" to trigger this
// option.
.addPossibleParameter("another_something")
// here you are able to add some more alternatives for that
// option, so here you can use "--complex", "-c", "-i" and
// "--ccp" to trigger this option.
.addCommand("-i").addCommand("--ccp");
}
public static void main(String[] args) {
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...