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