]> git.saurik.com Git - apt.git/blob - apt-pkg/contrib/cmndline.cc
Fix typos in documentation (codespell)
[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 <apti18n.h>
22 /*}}}*/
23 using namespace std;
24
25 // CommandLine::CommandLine - Constructor /*{{{*/
26 // ---------------------------------------------------------------------
27 /* */
28 CommandLine::CommandLine(Args *AList,Configuration *Conf) : ArgList(AList),
29 Conf(Conf), FileList(0)
30 {
31 }
32 /*}}}*/
33 // CommandLine::~CommandLine - Destructor /*{{{*/
34 // ---------------------------------------------------------------------
35 /* */
36 CommandLine::~CommandLine()
37 {
38 delete [] FileList;
39 }
40 /*}}}*/
41 // CommandLine::GetCommand - return the first non-option word /*{{{*/
42 char 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 /*}}}*/
77 // CommandLine::Parse - Main action member /*{{{*/
78 // ---------------------------------------------------------------------
79 /* */
80 bool CommandLine::Parse(int argc,const char **argv)
81 {
82 delete [] FileList;
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)
101 {
102 I++;
103 break;
104 }
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)
116 return _error->Error(_("Command line option '%c' [from %s] is not known."),*Opt,argv[I]);
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
129 Args *A;
130 const char *OptEnd = strchrnul(Opt, '=');
131 for (A = ArgList; A->end() == false &&
132 (A->LongOpt == 0 || stringcasecmp(Opt,OptEnd,A->LongOpt) != 0);
133 ++A);
134
135 // Failed, look for a word after the first - (no-foo)
136 bool PreceedMatch = false;
137 if (A->end() == true)
138 {
139 Opt = (const char*) memchr(Opt, '-', OptEnd - Opt);
140 if (Opt == NULL)
141 return _error->Error(_("Command line option %s is not understood"),argv[I]);
142 Opt++;
143
144 for (A = ArgList; A->end() == false &&
145 (A->LongOpt == 0 || stringcasecmp(Opt,OptEnd,A->LongOpt) != 0);
146 ++A);
147
148 // Failed again..
149 if (A->end() == true && OptEnd - Opt != 1)
150 return _error->Error(_("Command line option %s is not understood"),argv[I]);
151
152 // The option could be a single letter option prefixed by a no-..
153 if (A->end() == true)
154 {
155 for (A = ArgList; A->end() == false && A->ShortOpt != *Opt; A++);
156
157 if (A->end() == true)
158 return _error->Error(_("Command line option %s is not understood"),argv[I]);
159 }
160
161 // The option is not boolean
162 if (A->IsBoolean() == false)
163 return _error->Error(_("Command line option %s is not boolean"),argv[I]);
164 PreceedMatch = true;
165 }
166
167 // Deal with it.
168 OptEnd--;
169 if (HandleOpt(I,argc,argv,OptEnd,A,PreceedMatch) == false)
170 return false;
171 }
172
173 // Copy any remaining file names over
174 for (; I != argc; I++)
175 *Files++ = argv[I];
176 *Files = 0;
177
178 SaveInConfig(argc, argv);
179
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] */
188 bool CommandLine::HandleOpt(int &I,int argc,const char *argv[],
189 const char *&Opt,Args *A,bool PreceedMatch)
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)
204 return _error->Error(_("Option %s requires an argument."),argv[I]);
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 }
220
221 // Option is an argument set
222 if ((A->Flags & HasArg) == HasArg)
223 {
224 if (Argument == 0)
225 return _error->Error(_("Option %s requires an argument."),argv[I]);
226 Opt += strlen(Opt);
227 I += IncI;
228
229 // Parse a configuration file
230 if ((A->Flags & ConfigFile) == ConfigFile)
231 return ReadConfigFile(*Conf,Argument);
232
233 // Arbitrary item specification
234 if ((A->Flags & ArbItem) == ArbItem)
235 {
236 const char *J = strchr(Argument, '=');
237 if (J == NULL)
238 return _error->Error(_("Option %s: Configuration item specification must have an =<val>."),argv[I]);
239
240 // = is trailing
241 if (J[1] == 0)
242 {
243 if (I+1 >= argc)
244 return _error->Error(_("Option %s: Configuration item specification must have an =<val>."),argv[I]);
245 Conf->Set(string(Argument,J-Argument),string(argv[I++ +1]));
246 }
247 else
248 Conf->Set(string(Argument,J-Argument),string(J+1));
249
250 return true;
251 }
252
253 const char *I = strchrnul(A->ConfName, ' ');
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
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)
273 return _error->Error(_("Option %s requires an integer argument, not '%s'"),argv[I],Argument);
274
275 // Conversion was ok, set the value and return
276 if (EndPtr != 0 && EndPtr != Argument && *EndPtr == 0)
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 {
296 // Look at preceding text
297 char Buffer[300];
298 if (Argument == 0)
299 {
300 if (PreceedMatch == false)
301 break;
302
303 if (strlen(argv[I]) >= sizeof(Buffer))
304 return _error->Error(_("Option '%s' is too long"),argv[I]);
305
306 // Skip the leading dash
307 const char *J = argv[I];
308 for (; *J != 0 && *J == '-'; J++);
309
310 const char *JEnd = strchr(J, '-');
311 if (JEnd != NULL)
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
322 // Check for boolean
323 Sense = StringToBool(Argument);
324 if (Sense >= 0)
325 {
326 // Eat the argument
327 if (Argument != Buffer)
328 {
329 Opt += strlen(Opt);
330 I += IncI;
331 }
332 break;
333 }
334
335 if (CertainArg == true)
336 return _error->Error(_("Sense %s is not understood, try true or false."),Argument);
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 /*}}}*/
354 // CommandLine::FileSize - Count the number of filenames /*{{{*/
355 // ---------------------------------------------------------------------
356 /* */
357 unsigned 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 /*}}}*/
365 // CommandLine::DispatchArg - Do something with the first arg /*{{{*/
366 // ---------------------------------------------------------------------
367 /* */
368 bool CommandLine::DispatchArg(Dispatch *Map,bool NoMatch)
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)
384 {
385 if (NoMatch == true)
386 _error->Error(_("Invalid operation %s"),FileList[0]);
387 }
388
389 return false;
390 }
391 /*}}}*/
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. */
397 void CommandLine::SaveInConfig(unsigned int const &argc, char const * const * const argv)
398 {
399 char cmdline[100 + argc * 50];
400 memset(cmdline, 0, sizeof(cmdline));
401 unsigned int length = 0;
402 bool lastWasOption = false;
403 bool closeQuote = false;
404 for (unsigned int i = 0; i < argc && length < sizeof(cmdline); ++i, ++length)
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
413 const char* c = strchr(&argv[i][j+1], ' ');
414 if (c == NULL) continue;
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 /*}}}*/
430 CommandLine::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 /*}}}*/