-
Notifications
You must be signed in to change notification settings - Fork 644
/
DDGetoptLongParser.m
344 lines (300 loc) · 10.2 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
343
/*
* Copyright (c) 2007-2013 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"
extern int
dd_getopt_long(int nargc, char * const *nargv, const char *options,
const struct option *long_options, int *idx);
extern int
dd_getopt_long_only(int nargc, char * const *nargv, const char *options,
const struct option *long_options, int *idx);
@interface DDGetoptLongParser ()
- (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;
_target = target;
// Non-single char options start after as the last ASCII character
_nextShortOption = 256;
_optionsData = [[NSMutableData alloc] initWithLength: sizeof(struct option)];
_currentOption = 0;
_utf8Data = [[NSMutableArray alloc] init];
_optionString = [[NSMutableString alloc] init];
[_optionString appendString: @":"];
_optionInfoMap = [[NSMutableDictionary alloc] init];
_getoptFunction = dd_getopt_long;
return self;
}
- (void)dealloc
{
[_optionInfoMap release];
[_optionString release];
[_optionsData release];
[_utf8Data release];
[super dealloc];
}
- (id)target;
{
return _target;
}
- (void)setTarget:(id)target;
{
_target = target;
}
- (void)setGetoptLongOnly:(BOOL)getoptLongOnly;
{
if (getoptLongOnly)
_getoptFunction = dd_getopt_long_only;
else
_getoptFunction = dd_getopt_long;
}
- (void)addOptionsFromTable:(DDGetoptOption *)optionTable;
{
DDGetoptOption * currentOption = optionTable;
while ((currentOption->longOption != nil) ||
(currentOption->shortOption != 0))
{
[self addLongOption: [NSString stringWithUTF8String:currentOption->longOption]
shortOption: currentOption->shortOption
key: [self optionToKey: [NSString stringWithUTF8String:currentOption->longOption] ]
argumentOptions: currentOption->argumentOptions];
currentOption++;
}
}
- (void)addLongOption:(NSString *)longOption
shortOption:(char)shortOption
key:(NSString *)key
argumentOptions:(DDGetoptArgumentOptions)argumentOptions;
{
if ( argumentOptions == DDGetoptNoArgumentNegatable )
{
[self addLongOption:longOption shortOption:shortOption key:key argumentOptions:DDGetoptNoArgument];
NSString* noKey = [NSString stringWithFormat:@"no-%@",longOption];
[self addLongOption:noKey shortOption:shortOption key:noKey argumentOptions:DDGetoptNoArgument];
return;
}
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;
option->flag = NULL;
int shortOptionValue;
if (shortOption != 0)
{
shortOptionValue = shortOption;
option->val = shortOption;
if (argumentOptions == DDGetoptRequiredArgument)
[_optionString appendFormat: @"%c:", shortOption];
else if (argumentOptions == DDGetoptOptionalArgument)
[_optionString appendFormat: @"%c::", shortOption];
else
[_optionString appendFormat: @"%c", shortOption];
}
else
{
shortOptionValue = _nextShortOption;
_nextShortOption++;
option->val = shortOptionValue;
}
[self addOption];
NSArray * optionInfo = [NSArray arrayWithObjects:
key, [NSNumber numberWithInt: argumentOptions], nil];
[_optionInfoMap setObject: optionInfo
forKey: [NSNumber numberWithInt: shortOptionValue]];
[_utf8Data 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 + 1 ) );
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 = [_optionString UTF8String];
struct option * options = [self firstOption];
int ch;
opterr = 1;
int longOptionIndex = -1;
/* reset the options parser because it is too stupid to be reset with just optreset */
optreset = 1;
opterr = 1;
optind = 1;
while ((ch = _getoptFunction(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 = [_optionInfoMap 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) {
BOOL boolValue = YES;
if ([key hasPrefix:@"no-"]) {
boolValue = NO;
key = [key substringFromIndex:3];
}
[_target setValue: [NSNumber numberWithBool: boolValue] forKey: key];
}
else
[_target setValue: nsoptarg forKey: key];
}
}
if ( ( argc - optind ) >= 1 )
{
NSRange range = NSMakeRange(optind, argc - optind);
return [arguments subarrayWithRange: range];
}
else
{
return [NSArray array];
}
}
- (NSString *)optionToKey:(NSString *)option
{
return [DDGetoptLongParser optionToKey:option];
}
+ (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 = [_optionsData mutableBytes];
return options;
}
- (struct option *)currentOption;
{
struct option * options = [_optionsData mutableBytes];
return &options[_currentOption];
}
- (void)addOption;
{
[_optionsData increaseLengthBy: sizeof(struct option)];
_currentOption++;
}
- (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 ([_target respondsToSelector: @selector(optionIsMissingArgument:)])
{
[_target 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 ([_target respondsToSelector: @selector(optionIsNotRecognized:)])
{
[_target optionIsNotRecognized: option];
}
else
{
ddfprintf(stderr, @"%@: unrecognized option `%@'\n",
command, option);
ddfprintf(stderr, @"Try `%@ --help` for more information.\n", command);
}
}
@end