]> git.saurik.com Git - apt.git/blob - apt-pkg/contrib/cmndline.cc
generate commands array after config is loaded
[apt.git] / apt-pkg / contrib / cmndline.cc
1 // -*- mode: cpp; mode: fold -*-
2 // Description /*{{{*/
3 // $Id: cmndline.cc,v 1.15 2003/02/10 01:40:58 doogie Exp $
4 /* ######################################################################
5
6 Command Line Class - Sophisticated command line parser
7
8 This source is placed in the Public Domain, do with it what you will
9 It was originally written by Jason Gunthorpe <jgg@debian.org>.
10
11 ##################################################################### */
12 /*}}}*/
13 // Include files /*{{{*/
14 #include<config.h>
15
16 #include <apt-pkg/configuration.h>
17 #include <apt-pkg/cmndline.h>
18 #include <apt-pkg/error.h>
19 #include <apt-pkg/strutl.h>
20
21 #include <stddef.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <string>
25
26 #include <apti18n.h>
27 /*}}}*/
28 using namespace std;
29
30 // CommandLine::CommandLine - Constructor /*{{{*/
31 // ---------------------------------------------------------------------
32 /* */
33 CommandLine::CommandLine(Args *AList,Configuration *Conf) : ArgList(AList),
34 Conf(Conf), FileList(0)
35 {
36 }
37 CommandLine::CommandLine() : ArgList(NULL), Conf(NULL), FileList(0)
38 {
39 }
40 /*}}}*/
41 // CommandLine::~CommandLine - Destructor /*{{{*/
42 // ---------------------------------------------------------------------
43 /* */
44 CommandLine::~CommandLine()
45 {
46 delete [] FileList;
47 }
48 /*}}}*/
49 // CommandLine::GetCommand - return the first non-option word /*{{{*/
50 char const * CommandLine::GetCommand(Dispatch const * const Map,
51 unsigned int const argc, char const * const * const argv)
52 {
53 // if there is a -- on the line there must be the word we search for either
54 // before it (as -- marks the end of the options) or right after it (as we can't
55 // decide if the command is actually an option, given that in theory, you could
56 // have parameters named like commands)
57 for (size_t i = 1; i < argc; ++i)
58 {
59 if (strcmp(argv[i], "--") != 0)
60 continue;
61 // check if command is before --
62 for (size_t k = 1; k < i; ++k)
63 for (size_t j = 0; Map[j].Match != NULL; ++j)
64 if (strcmp(argv[k], Map[j].Match) == 0)
65 return Map[j].Match;
66 // see if the next token after -- is the command
67 ++i;
68 if (i < argc)
69 for (size_t j = 0; Map[j].Match != NULL; ++j)
70 if (strcmp(argv[i], Map[j].Match) == 0)
71 return Map[j].Match;
72 // we found a --, but not a command
73 return NULL;
74 }
75 // no --, so search for the first word matching a command
76 // FIXME: How like is it that an option parameter will be also a valid Match ?
77 for (size_t i = 1; i < argc; ++i)
78 {
79 if (*(argv[i]) == '-')
80 continue;
81 for (size_t j = 0; Map[j].Match != NULL; ++j)
82 if (strcmp(argv[i], Map[j].Match) == 0)
83 return Map[j].Match;
84 }
85 return NULL;
86 }
87 char const * CommandLine::GetCommand(DispatchWithHelp const * const Map,
88 unsigned int const argc, char const * const * const argv)
89 {
90 // if there is a -- on the line there must be the word we search for either
91 // before it (as -- marks the end of the options) or right after it (as we can't
92 // decide if the command is actually an option, given that in theory, you could
93 // have parameters named like commands)
94 for (size_t i = 1; i < argc; ++i)
95 {
96 if (strcmp(argv[i], "--") != 0)
97 continue;
98 // check if command is before --
99 for (size_t k = 1; k < i; ++k)
100 for (size_t j = 0; Map[j].Match != NULL; ++j)
101 if (strcmp(argv[k], Map[j].Match) == 0)
102 return Map[j].Match;
103 // see if the next token after -- is the command
104 ++i;
105 if (i < argc)
106 for (size_t j = 0; Map[j].Match != NULL; ++j)
107 if (strcmp(argv[i], Map[j].Match) == 0)
108 return Map[j].Match;
109 // we found a --, but not a command
110 return NULL;
111 }
112 // no --, so search for the first word matching a command
113 // FIXME: How like is it that an option parameter will be also a valid Match ?
114 for (size_t i = 1; i < argc; ++i)
115 {
116 if (*(argv[i]) == '-')
117 continue;
118 for (size_t j = 0; Map[j].Match != NULL; ++j)
119 if (strcmp(argv[i], Map[j].Match) == 0)
120 return Map[j].Match;
121 }
122 return NULL;
123 }
124 /*}}}*/
125 // CommandLine::Parse - Main action member /*{{{*/
126 // ---------------------------------------------------------------------
127 /* */
128 bool CommandLine::Parse(int argc,const char **argv)
129 {
130 delete [] FileList;
131 FileList = new const char *[argc];
132 const char **Files = FileList;
133 int I;
134 for (I = 1; I != argc; I++)
135 {
136 const char *Opt = argv[I];
137
138 // It is not an option
139 if (*Opt != '-')
140 {
141 *Files++ = Opt;
142 continue;
143 }
144
145 Opt++;
146
147 // Double dash signifies the end of option processing
148 if (*Opt == '-' && Opt[1] == 0)
149 {
150 I++;
151 break;
152 }
153
154 // Single dash is a short option
155 if (*Opt != '-')
156 {
157 // Iterate over each letter
158 while (*Opt != 0)
159 {
160 // Search for the option
161 Args *A;
162 for (A = ArgList; A->end() == false && A->ShortOpt != *Opt; A++);
163 if (A->end() == true)
164 return _error->Error(_("Command line option '%c' [from %s] is not understood in combination with the other options."),*Opt,argv[I]);
165
166 if (HandleOpt(I,argc,argv,Opt,A) == false)
167 return false;
168 if (*Opt != 0)
169 Opt++;
170 }
171 continue;
172 }
173
174 Opt++;
175
176 // Match up to a = against the list
177 Args *A;
178 const char *OptEnd = strchrnul(Opt, '=');
179 for (A = ArgList; A->end() == false &&
180 (A->LongOpt == 0 || stringcasecmp(Opt,OptEnd,A->LongOpt) != 0);
181 ++A);
182
183 // Failed, look for a word after the first - (no-foo)
184 bool PreceedMatch = false;
185 if (A->end() == true)
186 {
187 Opt = (const char*) memchr(Opt, '-', OptEnd - Opt);
188 if (Opt == NULL)
189 return _error->Error(_("Command line option %s is not understood in combination with the other options"),argv[I]);
190 Opt++;
191
192 for (A = ArgList; A->end() == false &&
193 (A->LongOpt == 0 || stringcasecmp(Opt,OptEnd,A->LongOpt) != 0);
194 ++A);
195
196 // Failed again..
197 if (A->end() == true && OptEnd - Opt != 1)
198 return _error->Error(_("Command line option %s is not understood in combination with the other options"),argv[I]);
199
200 // The option could be a single letter option prefixed by a no-..
201 if (A->end() == true)
202 {
203 for (A = ArgList; A->end() == false && A->ShortOpt != *Opt; A++);
204
205 if (A->end() == true)
206 return _error->Error(_("Command line option %s is not understood in combination with the other options"),argv[I]);
207 }
208
209 // The option is not boolean
210 if (A->IsBoolean() == false)
211 return _error->Error(_("Command line option %s is not boolean"),argv[I]);
212 PreceedMatch = true;
213 }
214
215 // Deal with it.
216 OptEnd--;
217 if (HandleOpt(I,argc,argv,OptEnd,A,PreceedMatch) == false)
218 return false;
219 }
220
221 // Copy any remaining file names over
222 for (; I != argc; I++)
223 *Files++ = argv[I];
224 *Files = 0;
225
226 SaveInConfig(argc, argv);
227
228 return true;
229 }
230 /*}}}*/
231 // CommandLine::HandleOpt - Handle a single option including all flags /*{{{*/
232 // ---------------------------------------------------------------------
233 /* This is a helper function for parser, it looks at a given argument
234 and looks for specific patterns in the string, it gets tokanized
235 -ruffly- like -*[yes|true|enable]-(o|longopt)[=][ ][argument] */
236 bool CommandLine::HandleOpt(int &I,int argc,const char *argv[],
237 const char *&Opt,Args *A,bool PreceedMatch)
238 {
239 const char *Argument = 0;
240 bool CertainArg = false;
241 int IncI = 0;
242
243 /* Determine the possible location of an option or 0 if their is
244 no option */
245 if (Opt[1] == 0 || (Opt[1] == '=' && Opt[2] == 0))
246 {
247 if (I + 1 < argc && argv[I+1][0] != '-')
248 Argument = argv[I+1];
249
250 // Equals was specified but we fell off the end!
251 if (Opt[1] == '=' && Argument == 0)
252 return _error->Error(_("Option %s requires an argument."),argv[I]);
253 if (Opt[1] == '=')
254 CertainArg = true;
255
256 IncI = 1;
257 }
258 else
259 {
260 if (Opt[1] == '=')
261 {
262 CertainArg = true;
263 Argument = Opt + 2;
264 }
265 else
266 Argument = Opt + 1;
267 }
268
269 // Option is an argument set
270 if ((A->Flags & HasArg) == HasArg)
271 {
272 if (Argument == 0)
273 return _error->Error(_("Option %s requires an argument."),argv[I]);
274 Opt += strlen(Opt);
275 I += IncI;
276
277 // Parse a configuration file
278 if ((A->Flags & ConfigFile) == ConfigFile)
279 return ReadConfigFile(*Conf,Argument);
280
281 // Arbitrary item specification
282 if ((A->Flags & ArbItem) == ArbItem)
283 {
284 const char *J = strchr(Argument, '=');
285 if (J == NULL)
286 return _error->Error(_("Option %s: Configuration item specification must have an =<val>."),argv[I]);
287
288 // = is trailing
289 if (J[1] == 0)
290 {
291 if (I+1 >= argc)
292 return _error->Error(_("Option %s: Configuration item specification must have an =<val>."),argv[I]);
293 Conf->Set(string(Argument,J-Argument),string(argv[I++ +1]));
294 }
295 else
296 Conf->Set(string(Argument,J-Argument),string(J+1));
297
298 return true;
299 }
300
301 const char *I = strchrnul(A->ConfName, ' ');
302 if (*I == ' ')
303 Conf->Set(string(A->ConfName,0,I-A->ConfName),string(I+1) + Argument);
304 else
305 Conf->Set(A->ConfName,string(I) + Argument);
306
307 return true;
308 }
309
310 // Option is an integer level
311 if ((A->Flags & IntLevel) == IntLevel)
312 {
313 // There might be an argument
314 if (Argument != 0)
315 {
316 char *EndPtr;
317 unsigned long Value = strtol(Argument,&EndPtr,10);
318
319 // Conversion failed and the argument was specified with an =s
320 if (EndPtr == Argument && CertainArg == true)
321 return _error->Error(_("Option %s requires an integer argument, not '%s'"),argv[I],Argument);
322
323 // Conversion was ok, set the value and return
324 if (EndPtr != 0 && EndPtr != Argument && *EndPtr == 0)
325 {
326 Conf->Set(A->ConfName,Value);
327 Opt += strlen(Opt);
328 I += IncI;
329 return true;
330 }
331 }
332
333 // Increase the level
334 Conf->Set(A->ConfName,Conf->FindI(A->ConfName)+1);
335 return true;
336 }
337
338 // Option is a boolean
339 int Sense = -1; // -1 is unspecified, 0 is yes 1 is no
340
341 // Look for an argument.
342 while (1)
343 {
344 // Look at preceding text
345 char Buffer[300];
346 if (Argument == 0)
347 {
348 if (PreceedMatch == false)
349 break;
350
351 if (strlen(argv[I]) >= sizeof(Buffer))
352 return _error->Error(_("Option '%s' is too long"),argv[I]);
353
354 // Skip the leading dash
355 const char *J = argv[I];
356 for (; *J != 0 && *J == '-'; J++);
357
358 const char *JEnd = strchr(J, '-');
359 if (JEnd != NULL)
360 {
361 strncpy(Buffer,J,JEnd - J);
362 Buffer[JEnd - J] = 0;
363 Argument = Buffer;
364 CertainArg = true;
365 }
366 else
367 break;
368 }
369
370 // Check for boolean
371 Sense = StringToBool(Argument);
372 if (Sense >= 0)
373 {
374 // Eat the argument
375 if (Argument != Buffer)
376 {
377 Opt += strlen(Opt);
378 I += IncI;
379 }
380 break;
381 }
382
383 if (CertainArg == true)
384 return _error->Error(_("Sense %s is not understood, try true or false."),Argument);
385
386 Argument = 0;
387 }
388
389 // Indeterminate sense depends on the flag
390 if (Sense == -1)
391 {
392 if ((A->Flags & InvBoolean) == InvBoolean)
393 Sense = 0;
394 else
395 Sense = 1;
396 }
397
398 Conf->Set(A->ConfName,Sense);
399 return true;
400 }
401 /*}}}*/
402 // CommandLine::FileSize - Count the number of filenames /*{{{*/
403 // ---------------------------------------------------------------------
404 /* */
405 unsigned int CommandLine::FileSize() const
406 {
407 unsigned int Count = 0;
408 for (const char **I = FileList; I != 0 && *I != 0; I++)
409 Count++;
410 return Count;
411 }
412 /*}}}*/
413 // CommandLine::DispatchArg - Do something with the first arg /*{{{*/
414 bool CommandLine::DispatchArg(DispatchWithHelp const * const Map,bool NoMatch)
415 {
416 int I;
417 for (I = 0; Map[I].Match != 0; I++)
418 {
419 if (strcmp(FileList[0],Map[I].Match) == 0)
420 {
421 bool Res = Map[I].Handler(*this);
422 if (Res == false && _error->PendingError() == false)
423 _error->Error("Handler silently failed");
424 return Res;
425 }
426 }
427
428 // No matching name
429 if (Map[I].Match == 0)
430 {
431 if (NoMatch == true)
432 _error->Error(_("Invalid operation %s"),FileList[0]);
433 }
434
435 return false;
436 }
437 bool CommandLine::DispatchArg(Dispatch *Map,bool NoMatch)
438 {
439 int I;
440 for (I = 0; Map[I].Match != 0; I++)
441 {
442 if (strcmp(FileList[0],Map[I].Match) == 0)
443 {
444 bool Res = Map[I].Handler(*this);
445 if (Res == false && _error->PendingError() == false)
446 _error->Error("Handler silently failed");
447 return Res;
448 }
449 }
450
451 // No matching name
452 if (Map[I].Match == 0)
453 {
454 if (NoMatch == true)
455 _error->Error(_("Invalid operation %s"),FileList[0]);
456 }
457
458 return false;
459 }
460 /*}}}*/
461 // CommandLine::SaveInConfig - for output later in a logfile or so /*{{{*/
462 // ---------------------------------------------------------------------
463 /* We save the commandline here to have it around later for e.g. logging.
464 It feels a bit like a hack here and isn't bulletproof, but it is better
465 than nothing after all. */
466 void CommandLine::SaveInConfig(unsigned int const &argc, char const * const * const argv)
467 {
468 char cmdline[100 + argc * 50];
469 memset(cmdline, 0, sizeof(cmdline));
470 unsigned int length = 0;
471 bool lastWasOption = false;
472 bool closeQuote = false;
473 for (unsigned int i = 0; i < argc && length < sizeof(cmdline); ++i, ++length)
474 {
475 for (unsigned int j = 0; argv[i][j] != '\0' && length < sizeof(cmdline)-1; ++j, ++length)
476 {
477 cmdline[length] = argv[i][j];
478 if (lastWasOption == true && argv[i][j] == '=')
479 {
480 // That is possibly an option: Quote it if it includes spaces,
481 // the benefit is that this will eliminate also most false positives
482 const char* c = strchr(&argv[i][j+1], ' ');
483 if (c == NULL) continue;
484 cmdline[++length] = '"';
485 closeQuote = true;
486 }
487 }
488 if (closeQuote == true)
489 cmdline[length++] = '"';
490 // Problem: detects also --hello
491 if (cmdline[length-1] == 'o')
492 lastWasOption = true;
493 cmdline[length] = ' ';
494 }
495 cmdline[--length] = '\0';
496 _config->Set("CommandLine::AsString", cmdline);
497 }
498 /*}}}*/
499 CommandLine::Args CommandLine::MakeArgs(char ShortOpt, char const *LongOpt, char const *ConfName, unsigned long Flags)/*{{{*/
500 {
501 /* In theory, this should be a constructor for CommandLine::Args instead,
502 but this breaks compatibility as gcc thinks this is a c++11 initializer_list */
503 CommandLine::Args arg;
504 arg.ShortOpt = ShortOpt;
505 arg.LongOpt = LongOpt;
506 arg.ConfName = ConfName;
507 arg.Flags = Flags;
508 return arg;
509 }
510 /*}}}*/