package org.couchbase.mock.util;
import java.util.ArrayList;
import java.util.List;
options = new ArrayList<CommandLineOption>();
optind = -1;
}
public Getopt
addOption(CommandLineOption option) {
options.add(option);
return this;
}
public List<Entry>
parse(String[] argv) {
optind = -1;
List<Entry> ret = new ArrayList<Entry>();
int idx = 0;
while (idx < argv.length) {
if (argv[idx].equals("--")) {
++idx;
break;
}
if (argv[idx].charAt(0) != '-') {
break;
}
if (argv[idx].startsWith("--")) {
String key = argv[idx];
int ii = key.indexOf('=');
if (ii != -1) {
key = key.substring(0, ii);
}
boolean found = false;
for (CommandLineOption o : options) {
if (key.equals(o.longopt)) {
found = true;
String value = null;
if (o.hasArgument) {
if (ii != -1) {
value = argv[idx].substring(ii + 1);
} else if (idx + 1 < argv.length) {
value = argv[idx + 1];
++idx;
} else {
throw new IllegalArgumentException("option requires an argument -- " + key);
}
}
ret.add(new Entry(key, value));
}
}
if (!found) {
throw new IllegalArgumentException("Illegal option -- " + key);
}
} else if (argv[idx].startsWith("-")) {
String keys = argv[idx].substring(1);
for (char c : keys.toCharArray()) {
String key = "-" + c;
boolean found = false;
for (CommandLineOption o : options) {
if (key.charAt(1) == o.shortopt) {
found = true;
String value = null;
if (o.hasArgument) {
if (idx + 1 < argv.length) {
value = argv[idx + 1];
++idx;
} else {
throw new IllegalArgumentException("option requires an argument -- " + key);
}
}
ret.add(new Entry(key, value));
}
}
if (!found) {
throw new IllegalArgumentException("Illegal option -- " + key);
}
}
} else {
break;
}
++idx;
}
if (idx != argv.length) {
optind = idx;
}
return ret;
}
return optind;
}
private int optind;
private List<CommandLineOption> options;
private char shortopt;
private String longopt;
private boolean hasArgument;
this.shortopt = shortopt;
this.longopt = longopt;
this.hasArgument = hasArgument;
}
}
public static class Entry {
public String key;
public String value;
public Entry(String k, String v) {
key = k;
value = v;
}
}
}