* apt-pkg/contrib/configuration.cc:
[ntk/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/cmndline.h>
17 #include <apt-pkg/error.h>
18 #include <apt-pkg/strutl.h>
19
20 #include <apti18n.h>
21 /*}}}*/
22 using namespace std;
23
24 // CommandLine::CommandLine - Constructor /*{{{*/
25 // ---------------------------------------------------------------------
26 /* */
27 CommandLine::CommandLine(Args *AList,Configuration *Conf) : ArgList(AList),
28 Conf(Conf), FileList(0)
29 {
30 }
31 /*}}}*/
32 // CommandLine::~CommandLine - Destructor /*{{{*/
33 // ---------------------------------------------------------------------
34 /* */
35 CommandLine::~CommandLine()
36 {
37 delete [] FileList;
38 }
39 /*}}}*/
40 // CommandLine::Parse - Main action member /*{{{*/
41 // ---------------------------------------------------------------------
42 /* */
43 bool CommandLine::Parse(int argc,const char **argv)
44 {
45 delete [] FileList;
46 FileList = new const char *[argc];
47 const char **Files = FileList;
48 int I;
49 for (I = 1; I != argc; I++)
50 {
51 const char *Opt = argv[I];
52
53 // It is not an option
54 if (*Opt != '-')
55 {
56 *Files++ = Opt;
57 continue;
58 }
59
60 Opt++;
61
62 // Double dash signifies the end of option processing
63 if (*Opt == '-' && Opt[1] == 0)
64 {
65 I++;
66 break;
67 }
68
69 // Single dash is a short option
70 if (*Opt != '-')
71 {
72 // Iterate over each letter
73 while (*Opt != 0)
74 {
75 // Search for the option
76 Args *A;
77 for (A = ArgList; A->end() == false && A->ShortOpt != *Opt; A++);
78 if (A->end() == true)
79 return _error->Error(_("Command line option '%c' [from %s] is not known."),*Opt,argv[I]);
80
81 if (HandleOpt(I,argc,argv,Opt,A) == false)
82 return false;
83 if (*Opt != 0)
84 Opt++;
85 }
86 continue;
87 }
88
89 Opt++;
90
91 // Match up to a = against the list
92 const char *OptEnd = Opt;
93 Args *A;
94 for (; *OptEnd != 0 && *OptEnd != '='; OptEnd++);
95 for (A = ArgList; A->end() == false &&
96 stringcasecmp(Opt,OptEnd,A->LongOpt) != 0; A++);
97
98 // Failed, look for a word after the first - (no-foo)
99 bool PreceedMatch = false;
100 if (A->end() == true)
101 {
102 for (; Opt != OptEnd && *Opt != '-'; Opt++);
103
104 if (Opt == OptEnd)
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;
200 for (J = Argument; *J != 0 && *J != '='; J++);
201 if (*J == 0)
202 return _error->Error(_("Option %s: Configuration item specification must have an =<val>."),argv[I]);
203
204 // = is trailing
205 if (J[1] == 0)
206 {
207 if (I+1 >= argc)
208 return _error->Error(_("Option %s: Configuration item specification must have an =<val>."),argv[I]);
209 Conf->Set(string(Argument,J-Argument),string(argv[I++ +1]));
210 }
211 else
212 Conf->Set(string(Argument,J-Argument),string(J+1));
213
214 return true;
215 }
216
217 const char *I = A->ConfName;
218 for (; *I != 0 && *I != ' '; I++);
219 if (*I == ' ')
220 Conf->Set(string(A->ConfName,0,I-A->ConfName),string(I+1) + Argument);
221 else
222 Conf->Set(A->ConfName,string(I) + Argument);
223
224 return true;
225 }
226
227 // Option is an integer level
228 if ((A->Flags & IntLevel) == IntLevel)
229 {
230 // There might be an argument
231 if (Argument != 0)
232 {
233 char *EndPtr;
234 unsigned long Value = strtol(Argument,&EndPtr,10);
235
236 // Conversion failed and the argument was specified with an =s
237 if (EndPtr == Argument && CertainArg == true)
238 return _error->Error(_("Option %s requires an integer argument, not '%s'"),argv[I],Argument);
239
240 // Conversion was ok, set the value and return
241 if (EndPtr != 0 && EndPtr != Argument && *EndPtr == 0)
242 {
243 Conf->Set(A->ConfName,Value);
244 Opt += strlen(Opt);
245 I += IncI;
246 return true;
247 }
248 }
249
250 // Increase the level
251 Conf->Set(A->ConfName,Conf->FindI(A->ConfName)+1);
252 return true;
253 }
254
255 // Option is a boolean
256 int Sense = -1; // -1 is unspecified, 0 is yes 1 is no
257
258 // Look for an argument.
259 while (1)
260 {
261 // Look at preceeding text
262 char Buffer[300];
263 if (Argument == 0)
264 {
265 if (PreceedMatch == false)
266 break;
267
268 if (strlen(argv[I]) >= sizeof(Buffer))
269 return _error->Error(_("Option '%s' is too long"),argv[I]);
270
271 // Skip the leading dash
272 const char *J = argv[I];
273 for (; *J != 0 && *J == '-'; J++);
274
275 const char *JEnd = J;
276 for (; *JEnd != 0 && *JEnd != '-'; JEnd++);
277 if (*JEnd != 0)
278 {
279 strncpy(Buffer,J,JEnd - J);
280 Buffer[JEnd - J] = 0;
281 Argument = Buffer;
282 CertainArg = true;
283 }
284 else
285 break;
286 }
287
288 // Check for boolean
289 Sense = StringToBool(Argument);
290 if (Sense >= 0)
291 {
292 // Eat the argument
293 if (Argument != Buffer)
294 {
295 Opt += strlen(Opt);
296 I += IncI;
297 }
298 break;
299 }
300
301 if (CertainArg == true)
302 return _error->Error(_("Sense %s is not understood, try true or false."),Argument);
303
304 Argument = 0;
305 }
306
307 // Indeterminate sense depends on the flag
308 if (Sense == -1)
309 {
310 if ((A->Flags & InvBoolean) == InvBoolean)
311 Sense = 0;
312 else
313 Sense = 1;
314 }
315
316 Conf->Set(A->ConfName,Sense);
317 return true;
318 }
319 /*}}}*/
320 // CommandLine::FileSize - Count the number of filenames /*{{{*/
321 // ---------------------------------------------------------------------
322 /* */
323 unsigned int CommandLine::FileSize() const
324 {
325 unsigned int Count = 0;
326 for (const char **I = FileList; I != 0 && *I != 0; I++)
327 Count++;
328 return Count;
329 }
330 /*}}}*/
331 // CommandLine::DispatchArg - Do something with the first arg /*{{{*/
332 // ---------------------------------------------------------------------
333 /* */
334 bool CommandLine::DispatchArg(Dispatch *Map,bool NoMatch)
335 {
336 int I;
337 for (I = 0; Map[I].Match != 0; I++)
338 {
339 if (strcmp(FileList[0],Map[I].Match) == 0)
340 {
341 bool Res = Map[I].Handler(*this);
342 if (Res == false && _error->PendingError() == false)
343 _error->Error("Handler silently failed");
344 return Res;
345 }
346 }
347
348 // No matching name
349 if (Map[I].Match == 0)
350 {
351 if (NoMatch == true)
352 _error->Error(_("Invalid operation %s"),FileList[0]);
353 }
354
355 return false;
356 }
357 /*}}}*/
358 // CommandLine::SaveInConfig - for output later in a logfile or so /*{{{*/
359 // ---------------------------------------------------------------------
360 /* We save the commandline here to have it around later for e.g. logging.
361 It feels a bit like a hack here and isn't bulletproof, but it is better
362 than nothing after all. */
363 void CommandLine::SaveInConfig(unsigned int const &argc, char const * const * const argv)
364 {
365 char cmdline[100 + argc * 50];
366 unsigned int length = 0;
367 bool lastWasOption = false;
368 bool closeQuote = false;
369 for (unsigned int i = 0; i < argc && length < sizeof(cmdline); ++i, ++length)
370 {
371 for (unsigned int j = 0; argv[i][j] != '\0' && length < sizeof(cmdline)-1; ++j, ++length)
372 {
373 cmdline[length] = argv[i][j];
374 if (lastWasOption == true && argv[i][j] == '=')
375 {
376 // That is possibly an option: Quote it if it includes spaces,
377 // the benefit is that this will eliminate also most false positives
378 const char* c = &argv[i][j+1];
379 for (; *c != '\0' && *c != ' '; ++c);
380 if (*c == '\0') continue;
381 cmdline[++length] = '"';
382 closeQuote = true;
383 }
384 }
385 if (closeQuote == true)
386 cmdline[length++] = '"';
387 // Problem: detects also --hello
388 if (cmdline[length-1] == 'o')
389 lastWasOption = true;
390 cmdline[length] = ' ';
391 }
392 cmdline[--length] = '\0';
393 _config->Set("CommandLine::AsString", cmdline);
394 }
395 /*}}}*/