cmndline.cc 10 KB

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