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