/
DDGetoptLongParser.m
343 lines (297 loc) · 10.7 KB
/
DDGetoptLongParser.m
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
/*
* Copyright (c) 2007-2008 Dave Dribin
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#import "DDGetoptLongParser.h"
#import "DDCliUtil.h"
@interface DDGetoptLongParser (Private)
- (NSString *) optionToKey: (NSString *) option;
- (struct option *) firstOption;
- (struct option *) currentOption;
- (void) addOption;
- (NSString *) errorOption: (NSString *) option;
- (void) handleMissingArgument: (NSString *) option
command: (NSString *) command;
- (void) handleArgumentNotRecognized: (NSString *) option
command: (NSString *) command;
@end
@implementation DDGetoptLongParser
+ (DDGetoptLongParser *) optionsWithTarget: (id) target
{
return [[[self alloc] initWithTarget: target] autorelease];
}
- (id) initWithTarget: (id) target
{
self = [super init];
if (self == nil)
return nil;
mTarget = target;
// Non-single char options start after as the last ASCII character
mNextShortOption = 256;
mOptionsData = [[NSMutableData alloc] initWithLength: sizeof(struct option)];
mCurrentOption = 0;
mUtf8Data = [[NSMutableArray alloc] init];
mOptionString = [[NSMutableString alloc] init];
[mOptionString appendString: @":"];
mOptionInfoMap = [[NSMutableDictionary alloc] init];
mGetoptFunction = getopt_long;
return self;
}
- (void) dealloc
{
[mOptionInfoMap release];
[mOptionString release];
[mOptionsData release];
[mUtf8Data release];
[super dealloc];
}
- (id) target
{
return mTarget;
}
- (void) setTarget: (id) target
{
mTarget = target;
}
- (void) setGetoptLongOnly: (BOOL) getoptLongOnly
{
if (getoptLongOnly)
mGetoptFunction = getopt_long_only;
else
mGetoptFunction = getopt_long;
}
- (void) addOptionsFromTable: (DDGetoptOption *) optionTable
{
DDGetoptOption * currentOption = optionTable;
while ((currentOption->longOption != nil) ||
(currentOption->shortOption != 0))
{
[self addLongOption: currentOption->longOption
shortOption: currentOption->shortOption
key: [self optionToKey: currentOption->longOption]
argumentOptions: currentOption->argumentOptions];
currentOption++;
}
}
- (void) addLongOption: (NSString *) longOption
shortOption: (char) shortOption
key: (NSString *) key
argumentOptions: (DDGetoptArgumentOptions) argumentOptions
{
const char * utf8String = [longOption UTF8String];
NSData * utf8Data = [NSData dataWithBytes: utf8String length: strlen(utf8String)];
struct option * option = [self currentOption];
option->name = utf8String;
option->has_arg = argumentOptions == DDGetoptKeyValueArgument ? DDGetoptRequiredArgument : argumentOptions;
option->flag = NULL;
int shortOptionValue;
if (shortOption != 0)
{
shortOptionValue = shortOption;
option->val = shortOption;
if (argumentOptions == DDGetoptRequiredArgument || argumentOptions == DDGetoptKeyValueArgument)
[mOptionString appendFormat: @"%c:", shortOption];
else if (argumentOptions == DDGetoptOptionalArgument)
[mOptionString appendFormat: @"%c::", shortOption];
else
[mOptionString appendFormat: @"%c", shortOption];
}
else
{
shortOptionValue = mNextShortOption;
mNextShortOption++;
option->val = shortOptionValue;
}
[self addOption];
NSArray * optionInfo = [NSArray arrayWithObjects:
key, [NSNumber numberWithInt: argumentOptions], nil];
[mOptionInfoMap setObject: optionInfo
forKey: [NSNumber numberWithInt: shortOptionValue]];
[mUtf8Data addObject: utf8Data];
}
- (void) addLongOption: (NSString *) longOption
key: (NSString *) key
argumentOptions: (DDGetoptArgumentOptions) argumentOptions
{
[self addLongOption: longOption shortOption: 0
key: key argumentOptions: argumentOptions];
}
- (NSArray *) parseOptions
{
NSProcessInfo * processInfo = [NSProcessInfo processInfo];
NSArray * arguments = [processInfo arguments];
NSString * command = [processInfo processName];
return [self parseOptionsWithArguments: arguments command: command];
}
- (NSArray *) parseOptionsWithArguments: (NSArray *) arguments
command: (NSString *) command
{
NSUInteger argc = [arguments count];
char ** argv = alloca(sizeof(char *) * argc);
NSUInteger i;
for (i = 0; i < argc; i++)
{
NSString * argument = [arguments objectAtIndex: i];
argv[i] = (char *) [argument UTF8String];
}
argv[i] = 0;
// Make sure list is NULL terminated
struct option * option = [self currentOption];
option->name = NULL;
option->has_arg = 0;
option->flag = NULL;
option->val = 0;
const char * optionString = [mOptionString UTF8String];
struct option * options = [self firstOption];
int ch;
opterr = 1;
int longOptionIndex = -1;
while ((ch = mGetoptFunction((int)argc, argv, optionString, options, &longOptionIndex)) != -1)
{
NSString * last_argv = [NSString stringWithUTF8String: argv[optind-1]];
if (ch == ':')
{
[self handleMissingArgument: last_argv command: command];
return nil;
}
else if (ch == '?')
{
[self handleArgumentNotRecognized: last_argv command: command];
return nil;
}
NSString * nsoptarg = nil;
if (optarg != NULL)
nsoptarg = [NSString stringWithUTF8String: optarg];
NSArray * optionInfo = [mOptionInfoMap objectForKey: [NSNumber numberWithInt: ch]];
NSAssert(optionInfo != nil, @"optionInfo should not be nil");
if (optionInfo != nil)
{
NSString * key = [optionInfo objectAtIndex: 0];
int argumentOptions = [[optionInfo objectAtIndex: 1] intValue];
if (argumentOptions == DDGetoptNoArgument)
[mTarget setValue: [NSNumber numberWithBool: YES] forKey: key];
else if (argumentOptions == DDGetoptKeyValueArgument)
{
// Split the arguement on the '=' sign
NSArray *pair = [nsoptarg componentsSeparatedByString:@"="];
// Build a keypath from the argument and the new key
NSString *keypath = [NSString stringWithFormat:@"%@.%@", key, [pair objectAtIndex:0]];
// If it is a number or a boolean, we'll parse that out
NSString *value = [pair objectAtIndex:1];
id parsedValue = value;
// Looks like a boolean?
if ([value isCaseInsensitiveLike:@"true"] || [value isCaseInsensitiveLike:@"false"])
{
parsedValue = [NSNumber numberWithBool:[value boolValue]];
}
else
{
// Looks like a number?
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setAllowsFloats:YES];
NSNumber *numberValue = [formatter numberFromString:value];
if (numberValue)
{
parsedValue = numberValue;
}
[formatter release];
}
[mTarget setValue:parsedValue forKeyPath:keypath];
}
else
[mTarget setValue: nsoptarg forKey: key];
}
}
NSRange range = NSMakeRange(optind, argc - optind);
return [arguments subarrayWithRange: range];
}
@end
@implementation DDGetoptLongParser (Private)
- (NSString *) optionToKey: (NSString *) option
{
NSScanner * scanner = [NSScanner scannerWithString: option];
[scanner setCharactersToBeSkipped: [NSCharacterSet characterSetWithCharactersInString: @"-"]];
NSMutableString * key = [NSMutableString string];
NSString * string = nil;
BOOL caps = NO;
while ([scanner scanUpToString: @"-" intoString: &string])
{
if (caps)
string = [string capitalizedString];
[key appendString: string];
caps = YES;
}
return key;
}
- (struct option *) firstOption
{
struct option * options = [mOptionsData mutableBytes];
return options;
}
- (struct option *) currentOption
{
struct option * options = [mOptionsData mutableBytes];
return &options[mCurrentOption];
}
- (void) addOption
{
[mOptionsData increaseLengthBy: sizeof(struct option)];
mCurrentOption++;
}
- (NSString *) errorOption: (NSString *) option
{
if (![option hasPrefix: @"-"])
return [NSString stringWithFormat: @"%c", optopt];
else
return option;
}
- (void) handleMissingArgument: (NSString *) option
command: (NSString *) command
{
option = [self errorOption: option];
if ([mTarget respondsToSelector: @selector(optionIsMissingArgument:)])
{
[mTarget optionIsMissingArgument: option];
}
else
{
ddfprintf(stderr, @"%@: option `%@' requires an argument\n",
command, option);
ddfprintf(stderr, @"Try `%@ --help` for more information.\n", command);
}
}
- (void) handleArgumentNotRecognized: (NSString *) option
command: (NSString *) command
{
option = [self errorOption: option];
if ([mTarget respondsToSelector: @selector(optionIsNotRecognized:)])
{
[mTarget optionIsNotRecognized: option];
}
else
{
ddfprintf(stderr, @"%@: unrecognized option `%@'\n",
command, option);
ddfprintf(stderr, @"Try `%@ --help` for more information.\n", command);
}
}
@end