]> git.saurik.com Git - apt.git/blame - apt-pkg/contrib/cmndline.cc
deduplicate main methods
[apt.git] / apt-pkg / contrib / cmndline.cc
CommitLineData
08e8f724
AL
1// -*- mode: cpp; mode: fold -*-
2// Description /*{{{*/
bac2e715 3// $Id: cmndline.cc,v 1.15 2003/02/10 01:40:58 doogie Exp $
08e8f724
AL
4/* ######################################################################
5
6 Command Line Class - Sophisticated command line parser
7
7da2b375
AL
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
08e8f724
AL
11 ##################################################################### */
12 /*}}}*/
13// Include files /*{{{*/
ea542140
DK
14#include<config.h>
15
472ff00e 16#include <apt-pkg/configuration.h>
08e8f724
AL
17#include <apt-pkg/cmndline.h>
18#include <apt-pkg/error.h>
cdcc6d34 19#include <apt-pkg/strutl.h>
b2e465d6 20
453b82a3
DK
21#include <stddef.h>
22#include <stdlib.h>
23#include <string.h>
24#include <string>
25
ea542140 26#include <apti18n.h>
08e8f724 27 /*}}}*/
584e4558 28using namespace std;
08e8f724
AL
29
30// CommandLine::CommandLine - Constructor /*{{{*/
31// ---------------------------------------------------------------------
32/* */
33CommandLine::CommandLine(Args *AList,Configuration *Conf) : ArgList(AList),
34 Conf(Conf), FileList(0)
35{
ad7e0941
DK
36}
37CommandLine::CommandLine() : ArgList(NULL), Conf(NULL), FileList(0)
38{
e1b74f61
AL
39}
40 /*}}}*/
41// CommandLine::~CommandLine - Destructor /*{{{*/
42// ---------------------------------------------------------------------
43/* */
44CommandLine::~CommandLine()
45{
46 delete [] FileList;
08e8f724
AL
47}
48 /*}}}*/
b9179170
MV
49// CommandLine::GetCommand - return the first non-option word /*{{{*/
50char const * CommandLine::GetCommand(Dispatch const * const Map,
51 unsigned int const argc, char const * const * const argv)
52{
c4b91cbe
DK
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)
b9179170
MV
57 for (size_t i = 1; i < argc; ++i)
58 {
59 if (strcmp(argv[i], "--") != 0)
60 continue;
c4b91cbe
DK
61 // check if command is before --
62 for (size_t k = 1; k < i; ++k)
b9179170 63 for (size_t j = 0; Map[j].Match != NULL; ++j)
c4b91cbe 64 if (strcmp(argv[k], Map[j].Match) == 0)
b9179170 65 return Map[j].Match;
c4b91cbe
DK
66 // see if the next token after -- is the command
67 ++i;
68 if (i < argc)
b9179170
MV
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;
c4b91cbe 72 // we found a --, but not a command
b9179170
MV
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;
cbbee23e
DK
86}
87char 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;
b9179170
MV
123}
124 /*}}}*/
08e8f724
AL
125// CommandLine::Parse - Main action member /*{{{*/
126// ---------------------------------------------------------------------
127/* */
128bool CommandLine::Parse(int argc,const char **argv)
129{
e1b74f61 130 delete [] FileList;
08e8f724
AL
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)
343bd48e
AL
149 {
150 I++;
08e8f724 151 break;
343bd48e 152 }
08e8f724
AL
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)
71510743 164 return _error->Error(_("Command line option '%c' [from %s] is not understood in combination with the other options."),*Opt,argv[I]);
08e8f724
AL
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
08e8f724 177 Args *A;
404528bd 178 const char *OptEnd = strchrnul(Opt, '=');
ae2be086
DH
179 for (A = ArgList; A->end() == false &&
180 (A->LongOpt == 0 || stringcasecmp(Opt,OptEnd,A->LongOpt) != 0);
181 ++A);
08e8f724
AL
182
183 // Failed, look for a word after the first - (no-foo)
0d47bd08 184 bool PreceedMatch = false;
08e8f724
AL
185 if (A->end() == true)
186 {
404528bd
DK
187 Opt = (const char*) memchr(Opt, '-', OptEnd - Opt);
188 if (Opt == NULL)
b7bbde25 189 return _error->Error(_("Command line option %s is not understood in combination with the other options"),argv[I]);
08e8f724
AL
190 Opt++;
191
192 for (A = ArgList; A->end() == false &&
7a6d9076
DK
193 (A->LongOpt == 0 || stringcasecmp(Opt,OptEnd,A->LongOpt) != 0);
194 ++A);
08e8f724
AL
195
196 // Failed again..
197 if (A->end() == true && OptEnd - Opt != 1)
b7bbde25 198 return _error->Error(_("Command line option %s is not understood in combination with the other options"),argv[I]);
0d47bd08 199
08e8f724 200 // The option could be a single letter option prefixed by a no-..
08e8f724 201 if (A->end() == true)
0d47bd08
AL
202 {
203 for (A = ArgList; A->end() == false && A->ShortOpt != *Opt; A++);
204
205 if (A->end() == true)
b7bbde25 206 return _error->Error(_("Command line option %s is not understood in combination with the other options"),argv[I]);
0d47bd08 207 }
e1b74f61
AL
208
209 // The option is not boolean
210 if (A->IsBoolean() == false)
b2e465d6 211 return _error->Error(_("Command line option %s is not boolean"),argv[I]);
0d47bd08 212 PreceedMatch = true;
08e8f724
AL
213 }
214
215 // Deal with it.
216 OptEnd--;
0d47bd08 217 if (HandleOpt(I,argc,argv,OptEnd,A,PreceedMatch) == false)
08e8f724
AL
218 return false;
219 }
220
221 // Copy any remaining file names over
222 for (; I != argc; I++)
223 *Files++ = argv[I];
224 *Files = 0;
2bb25574
DK
225
226 SaveInConfig(argc, argv);
227
08e8f724
AL
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] */
236bool CommandLine::HandleOpt(int &I,int argc,const char *argv[],
0d47bd08 237 const char *&Opt,Args *A,bool PreceedMatch)
08e8f724
AL
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)
b2e465d6 252 return _error->Error(_("Option %s requires an argument."),argv[I]);
08e8f724
AL
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 }
0d47bd08 268
08e8f724
AL
269 // Option is an argument set
270 if ((A->Flags & HasArg) == HasArg)
271 {
272 if (Argument == 0)
b2e465d6 273 return _error->Error(_("Option %s requires an argument."),argv[I]);
08e8f724
AL
274 Opt += strlen(Opt);
275 I += IncI;
276
277 // Parse a configuration file
278 if ((A->Flags & ConfigFile) == ConfigFile)
279 return ReadConfigFile(*Conf,Argument);
e1b74f61 280
0da8987a 281 // Arbitrary item specification
e1b74f61
AL
282 if ((A->Flags & ArbItem) == ArbItem)
283 {
404528bd
DK
284 const char *J = strchr(Argument, '=');
285 if (J == NULL)
bac2e715 286 return _error->Error(_("Option %s: Configuration item specification must have an =<val>."),argv[I]);
e1b74f61 287
7e798dd7
AL
288 // = is trailing
289 if (J[1] == 0)
290 {
291 if (I+1 >= argc)
bac2e715 292 return _error->Error(_("Option %s: Configuration item specification must have an =<val>."),argv[I]);
7e798dd7
AL
293 Conf->Set(string(Argument,J-Argument),string(argv[I++ +1]));
294 }
295 else
296 Conf->Set(string(Argument,J-Argument),string(J+1));
e1b74f61
AL
297
298 return true;
299 }
08e8f724 300
404528bd 301 const char *I = strchrnul(A->ConfName, ' ');
7f25bdff
AL
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
08e8f724
AL
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)
b2e465d6 321 return _error->Error(_("Option %s requires an integer argument, not '%s'"),argv[I],Argument);
08e8f724
AL
322
323 // Conversion was ok, set the value and return
9435cc9b 324 if (EndPtr != 0 && EndPtr != Argument && *EndPtr == 0)
08e8f724
AL
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 {
1e3f4083 344 // Look at preceding text
08e8f724
AL
345 char Buffer[300];
346 if (Argument == 0)
347 {
0d47bd08
AL
348 if (PreceedMatch == false)
349 break;
350
08e8f724 351 if (strlen(argv[I]) >= sizeof(Buffer))
b2e465d6 352 return _error->Error(_("Option '%s' is too long"),argv[I]);
0d47bd08
AL
353
354 // Skip the leading dash
08e8f724
AL
355 const char *J = argv[I];
356 for (; *J != 0 && *J == '-'; J++);
404528bd
DK
357
358 const char *JEnd = strchr(J, '-');
359 if (JEnd != NULL)
08e8f724
AL
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
3b5421b4
AL
370 // Check for boolean
371 Sense = StringToBool(Argument);
372 if (Sense >= 0)
08e8f724 373 {
08e8f724
AL
374 // Eat the argument
375 if (Argument != Buffer)
376 {
377 Opt += strlen(Opt);
378 I += IncI;
379 }
380 break;
381 }
382
08e8f724 383 if (CertainArg == true)
b2e465d6 384 return _error->Error(_("Sense %s is not understood, try true or false."),Argument);
08e8f724
AL
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 /*}}}*/
bc4af0b9 402// CommandLine::FileSize - Count the number of filenames /*{{{*/
e1b74f61
AL
403// ---------------------------------------------------------------------
404/* */
405unsigned 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 /*}}}*/
bc4af0b9 413// CommandLine::DispatchArg - Do something with the first arg /*{{{*/
e7e10e47 414bool CommandLine::DispatchArg(DispatchWithHelp const * const Map,bool NoMatch)
cbbee23e
DK
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}
b0b4efb9 437bool CommandLine::DispatchArg(Dispatch *Map,bool NoMatch)
bc4af0b9
AL
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)
b0b4efb9
AL
453 {
454 if (NoMatch == true)
b2e465d6 455 _error->Error(_("Invalid operation %s"),FileList[0]);
b0b4efb9
AL
456 }
457
bc4af0b9
AL
458 return false;
459}
460 /*}}}*/
2bb25574
DK
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. */
466void CommandLine::SaveInConfig(unsigned int const &argc, char const * const * const argv)
467{
093e9f5d 468 char cmdline[100 + argc * 50];
70e0c168 469 memset(cmdline, 0, sizeof(cmdline));
2bb25574
DK
470 unsigned int length = 0;
471 bool lastWasOption = false;
472 bool closeQuote = false;
093e9f5d 473 for (unsigned int i = 0; i < argc && length < sizeof(cmdline); ++i, ++length)
2bb25574
DK
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
404528bd
DK
482 const char* c = strchr(&argv[i][j+1], ' ');
483 if (c == NULL) continue;
2bb25574
DK
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 /*}}}*/
b9179170
MV
499CommandLine::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 /*}}}*/