cmndline.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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<config.h>
  12. #include <apt-pkg/configuration.h>
  13. #include <apt-pkg/cmndline.h>
  14. #include <apt-pkg/error.h>
  15. #include <apt-pkg/strutl.h>
  16. #include <apti18n.h>
  17. /*}}}*/
  18. using namespace std;
  19. // CommandLine::CommandLine - Constructor /*{{{*/
  20. // ---------------------------------------------------------------------
  21. /* */
  22. CommandLine::CommandLine(Args *AList,Configuration *Conf) : ArgList(AList),
  23. Conf(Conf), FileList(0)
  24. {
  25. }
  26. /*}}}*/
  27. // CommandLine::~CommandLine - Destructor /*{{{*/
  28. // ---------------------------------------------------------------------
  29. /* */
  30. CommandLine::~CommandLine()
  31. {
  32. delete [] FileList;
  33. }
  34. /*}}}*/
  35. // CommandLine::Parse - Main action member /*{{{*/
  36. // ---------------------------------------------------------------------
  37. /* */
  38. bool CommandLine::Parse(int argc,const char **argv)
  39. {
  40. delete [] FileList;
  41. FileList = new const char *[argc];
  42. const char **Files = FileList;
  43. int I;
  44. for (I = 1; I != argc; I++)
  45. {
  46. const char *Opt = argv[I];
  47. // It is not an option
  48. if (*Opt != '-')
  49. {
  50. *Files++ = Opt;
  51. continue;
  52. }
  53. Opt++;
  54. // Double dash signifies the end of option processing
  55. if (*Opt == '-' && Opt[1] == 0)
  56. {
  57. I++;
  58. break;
  59. }
  60. // Single dash is a short option
  61. if (*Opt != '-')
  62. {
  63. // Iterate over each letter
  64. while (*Opt != 0)
  65. {
  66. // Search for the option
  67. Args *A;
  68. for (A = ArgList; A->end() == false && A->ShortOpt != *Opt; A++);
  69. if (A->end() == true)
  70. return _error->Error(_("Command line option '%c' [from %s] is not known."),*Opt,argv[I]);
  71. if (HandleOpt(I,argc,argv,Opt,A) == false)
  72. return false;
  73. if (*Opt != 0)
  74. Opt++;
  75. }
  76. continue;
  77. }
  78. Opt++;
  79. // Match up to a = against the list
  80. Args *A;
  81. const char *OptEnd = strchrnul(Opt, '=');
  82. for (A = ArgList; A->end() == false &&
  83. (A->LongOpt == 0 || stringcasecmp(Opt,OptEnd,A->LongOpt) != 0);
  84. ++A);
  85. // Failed, look for a word after the first - (no-foo)
  86. bool PreceedMatch = false;
  87. if (A->end() == true)
  88. {
  89. Opt = (const char*) memchr(Opt, '-', OptEnd - Opt);
  90. if (Opt == NULL)
  91. return _error->Error(_("Command line option %s is not understood"),argv[I]);
  92. Opt++;
  93. for (A = ArgList; A->end() == false &&
  94. (A->LongOpt == 0 || stringcasecmp(Opt,OptEnd,A->LongOpt) != 0);
  95. ++A);
  96. // Failed again..
  97. if (A->end() == true && OptEnd - Opt != 1)
  98. return _error->Error(_("Command line option %s is not understood"),argv[I]);
  99. // The option could be a single letter option prefixed by a no-..
  100. if (A->end() == true)
  101. {
  102. for (A = ArgList; A->end() == false && A->ShortOpt != *Opt; A++);
  103. if (A->end() == true)
  104. return _error->Error(_("Command line option %s is not understood"),argv[I]);
  105. }
  106. // The option is not boolean
  107. if (A->IsBoolean() == false)
  108. return _error->Error(_("Command line option %s is not boolean"),argv[I]);
  109. PreceedMatch = true;
  110. }
  111. // Deal with it.
  112. OptEnd--;
  113. if (HandleOpt(I,argc,argv,OptEnd,A,PreceedMatch) == false)
  114. return false;
  115. }
  116. // Copy any remaining file names over
  117. for (; I != argc; I++)
  118. *Files++ = argv[I];
  119. *Files = 0;
  120. SaveInConfig(argc, argv);
  121. return true;
  122. }
  123. /*}}}*/
  124. // CommandLine::HandleOpt - Handle a single option including all flags /*{{{*/
  125. // ---------------------------------------------------------------------
  126. /* This is a helper function for parser, it looks at a given argument
  127. and looks for specific patterns in the string, it gets tokanized
  128. -ruffly- like -*[yes|true|enable]-(o|longopt)[=][ ][argument] */
  129. bool CommandLine::HandleOpt(int &I,int argc,const char *argv[],
  130. const char *&Opt,Args *A,bool PreceedMatch)
  131. {
  132. const char *Argument = 0;
  133. bool CertainArg = false;
  134. int IncI = 0;
  135. /* Determine the possible location of an option or 0 if their is
  136. no option */
  137. if (Opt[1] == 0 || (Opt[1] == '=' && Opt[2] == 0))
  138. {
  139. if (I + 1 < argc && argv[I+1][0] != '-')
  140. Argument = argv[I+1];
  141. // Equals was specified but we fell off the end!
  142. if (Opt[1] == '=' && Argument == 0)
  143. return _error->Error(_("Option %s requires an argument."),argv[I]);
  144. if (Opt[1] == '=')
  145. CertainArg = true;
  146. IncI = 1;
  147. }
  148. else
  149. {
  150. if (Opt[1] == '=')
  151. {
  152. CertainArg = true;
  153. Argument = Opt + 2;
  154. }
  155. else
  156. Argument = Opt + 1;
  157. }
  158. // Option is an argument set
  159. if ((A->Flags & HasArg) == HasArg)
  160. {
  161. if (Argument == 0)
  162. return _error->Error(_("Option %s requires an argument."),argv[I]);
  163. Opt += strlen(Opt);
  164. I += IncI;
  165. // Parse a configuration file
  166. if ((A->Flags & ConfigFile) == ConfigFile)
  167. return ReadConfigFile(*Conf,Argument);
  168. // Arbitrary item specification
  169. if ((A->Flags & ArbItem) == ArbItem)
  170. {
  171. const char *J = strchr(Argument, '=');
  172. if (J == NULL)
  173. return _error->Error(_("Option %s: Configuration item specification must have an =<val>."),argv[I]);
  174. // = is trailing
  175. if (J[1] == 0)
  176. {
  177. if (I+1 >= argc)
  178. return _error->Error(_("Option %s: Configuration item specification must have an =<val>."),argv[I]);
  179. Conf->Set(string(Argument,J-Argument),string(argv[I++ +1]));
  180. }
  181. else
  182. Conf->Set(string(Argument,J-Argument),string(J+1));
  183. return true;
  184. }
  185. const char *I = strchrnul(A->ConfName, ' ');
  186. if (*I == ' ')
  187. Conf->Set(string(A->ConfName,0,I-A->ConfName),string(I+1) + Argument);
  188. else
  189. Conf->Set(A->ConfName,string(I) + Argument);
  190. return true;
  191. }
  192. // Option is an integer level
  193. if ((A->Flags & IntLevel) == IntLevel)
  194. {
  195. // There might be an argument
  196. if (Argument != 0)
  197. {
  198. char *EndPtr;
  199. unsigned long Value = strtol(Argument,&EndPtr,10);
  200. // Conversion failed and the argument was specified with an =s
  201. if (EndPtr == Argument && CertainArg == true)
  202. return _error->Error(_("Option %s requires an integer argument, not '%s'"),argv[I],Argument);
  203. // Conversion was ok, set the value and return
  204. if (EndPtr != 0 && EndPtr != Argument && *EndPtr == 0)
  205. {
  206. Conf->Set(A->ConfName,Value);
  207. Opt += strlen(Opt);
  208. I += IncI;
  209. return true;
  210. }
  211. }
  212. // Increase the level
  213. Conf->Set(A->ConfName,Conf->FindI(A->ConfName)+1);
  214. return true;
  215. }
  216. // Option is a boolean
  217. int Sense = -1; // -1 is unspecified, 0 is yes 1 is no
  218. // Look for an argument.
  219. while (1)
  220. {
  221. // Look at preceeding text
  222. char Buffer[300];
  223. if (Argument == 0)
  224. {
  225. if (PreceedMatch == false)
  226. break;
  227. if (strlen(argv[I]) >= sizeof(Buffer))
  228. return _error->Error(_("Option '%s' is too long"),argv[I]);
  229. // Skip the leading dash
  230. const char *J = argv[I];
  231. for (; *J != 0 && *J == '-'; J++);
  232. const char *JEnd = strchr(J, '-');
  233. if (JEnd != NULL)
  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 = strchr(&argv[i][j+1], ' ');
  328. if (c == NULL) continue;
  329. cmdline[++length] = '"';
  330. closeQuote = true;
  331. }
  332. }
  333. if (closeQuote == true)
  334. cmdline[length++] = '"';
  335. // Problem: detects also --hello
  336. if (cmdline[length-1] == 'o')
  337. lastWasOption = true;
  338. cmdline[length] = ' ';
  339. }
  340. cmdline[--length] = '\0';
  341. _config->Set("CommandLine::AsString", cmdline);
  342. }
  343. /*}}}*/