-
Notifications
You must be signed in to change notification settings - Fork 0
/
GetOpt.java
138 lines (116 loc) · 3.51 KB
/
GetOpt.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/*
* Created on Feb 25, 2006
* Feb 25, 2006 5:25:41 PM
*/
/*
* somewhat based on bsd and the original public domain att source code.
*/
public class GetOpt
{
private String[] fArgs;
private String fOptions;
private String fPlace;
private int fIndex;
private int fOffset;
private String fOptarg;
public GetOpt(String[] args, String options)
{
fIndex = 0;
fOffset = 0;
fOptarg = null;
fPlace = null;
fArgs = args;
fOptions = options;
}
// will replace option strings with null in the data.
public int Next()
{
fOptarg = null;
if (fPlace == null || fOffset >= fPlace.length())
{
// go to the next one.
fOffset = 0;
}
if (fOffset == 0)
{
fOffset = 1;
while (true)
{
int oldi = fIndex;
if (fIndex >= fArgs.length) return -1;
fPlace = fArgs[fIndex++];
if (fPlace == null) continue;
if (fPlace.charAt(0) != '-') continue;
// option string... hurray!!
// "-" allow set fOffset=0 so that it will be
// treated as a flag or an error.
if (fPlace.length() == 1)
{
fOffset = 0;
}
// "--" end of options.
if (fPlace.compareTo("--") == 0)
{
fArgs[oldi] = null;
return -1;
}
fArgs[oldi] = null;
break;
}
}
// fPlace is the option string, fOffset is the index in it to check.
int c = fPlace.charAt(fOffset++);
// check if it's a valid value.
int loc = fOptions.indexOf(c);
if (c == ':' || loc == -1)
{
System.err.printf("Illegal option -- %1$c", c);
return '?';
}
// valid option. check for :
if ((loc + 1) < fOptions.length() && fOptions.charAt(loc + 1) == ':')
{
// if more data in this option, that's the arg.
if (fOffset < fPlace.length())
{
fOptarg = fPlace.substring(fOffset);
fOffset = 0;
}
// next argv is the option argument
else if (fArgs.length > fIndex)
{
fOptarg = fArgs[fIndex];
fArgs[fIndex] = null;
fIndex++;
}
else
{
System.err.printf("Option requires an argument -- %1$c", c);
return '?';
}
}
return c;
}
public String Argument()
{
return fOptarg;
}
// return the orginal arguments, compacted.
public String[] CommandLine()
{
int i;
int count = 0;
for (i = 0; i < fArgs.length; i++)
{
if (fArgs[i] != null) count++;
}
if (count == i) return fArgs;
String[] tmp = new String[count];
count = 0;
for (i = 0; i < fArgs.length; i++)
{
if (fArgs[i] != null) tmp[count++] = fArgs[i];
}
return tmp;
}
}