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