cmndline.cc 11 KB

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