cmndline.cc 10 KB

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