Getopt.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4: */
  3. /**
  4. * PHP Version 5
  5. *
  6. * Copyright (c) 1997-2004 The PHP Group
  7. *
  8. * This source file is subject to version 3.0 of the PHP license,
  9. * that is bundled with this package in the file LICENSE, and is
  10. * available through the world-wide-web at the following url:
  11. * http://www.php.net/license/3_0.txt.
  12. * If you did not receive a copy of the PHP license and are unable to
  13. * obtain it through the world-wide-web, please send a note to
  14. * license@php.net so we can mail you a copy immediately.
  15. *
  16. * @category Console
  17. * @package Console_Getopt
  18. * @author Andrei Zmievski <andrei@php.net>
  19. * @license http://www.php.net/license/3_0.txt PHP 3.0
  20. * @version CVS: $Id: Getopt.php 306067 2010-12-08 00:13:31Z dufuz $
  21. * @link http://pear.php.net/package/Console_Getopt
  22. */
  23. require_once 'PEAR.php';
  24. /**
  25. * Command-line options parsing class.
  26. *
  27. * @category Console
  28. * @package Console_Getopt
  29. * @author Andrei Zmievski <andrei@php.net>
  30. * @license http://www.php.net/license/3_0.txt PHP 3.0
  31. * @link http://pear.php.net/package/Console_Getopt
  32. */
  33. class Console_Getopt
  34. {
  35. /**
  36. * Parses the command-line options.
  37. *
  38. * The first parameter to this function should be the list of command-line
  39. * arguments without the leading reference to the running program.
  40. *
  41. * The second parameter is a string of allowed short options. Each of the
  42. * option letters can be followed by a colon ':' to specify that the option
  43. * requires an argument, or a double colon '::' to specify that the option
  44. * takes an optional argument.
  45. *
  46. * The third argument is an optional array of allowed long options. The
  47. * leading '--' should not be included in the option name. Options that
  48. * require an argument should be followed by '=', and options that take an
  49. * option argument should be followed by '=='.
  50. *
  51. * The return value is an array of two elements: the list of parsed
  52. * options and the list of non-option command-line arguments. Each entry in
  53. * the list of parsed options is a pair of elements - the first one
  54. * specifies the option, and the second one specifies the option argument,
  55. * if there was one.
  56. *
  57. * Long and short options can be mixed.
  58. *
  59. * Most of the semantics of this function are based on GNU getopt_long().
  60. *
  61. * @param array $args an array of command-line arguments
  62. * @param string $short_options specifies the list of allowed short options
  63. * @param array $long_options specifies the list of allowed long options
  64. * @param boolean $skip_unknown suppresses Console_Getopt: unrecognized option
  65. *
  66. * @return array two-element array containing the list of parsed options and
  67. * the non-option arguments
  68. * @access public
  69. */
  70. function getopt2($args, $short_options, $long_options = null, $skip_unknown = false)
  71. {
  72. return Console_Getopt::doGetopt(2, $args, $short_options, $long_options, $skip_unknown);
  73. }
  74. /**
  75. * This function expects $args to start with the script name (POSIX-style).
  76. * Preserved for backwards compatibility.
  77. *
  78. * @param array $args an array of command-line arguments
  79. * @param string $short_options specifies the list of allowed short options
  80. * @param array $long_options specifies the list of allowed long options
  81. *
  82. * @see getopt2()
  83. * @return array two-element array containing the list of parsed options and
  84. * the non-option arguments
  85. */
  86. function getopt($args, $short_options, $long_options = null, $skip_unknown = false)
  87. {
  88. return Console_Getopt::doGetopt(1, $args, $short_options, $long_options, $skip_unknown);
  89. }
  90. /**
  91. * The actual implementation of the argument parsing code.
  92. *
  93. * @param int $version Version to use
  94. * @param array $args an array of command-line arguments
  95. * @param string $short_options specifies the list of allowed short options
  96. * @param array $long_options specifies the list of allowed long options
  97. * @param boolean $skip_unknown suppresses Console_Getopt: unrecognized option
  98. *
  99. * @return array
  100. */
  101. function doGetopt($version, $args, $short_options, $long_options = null, $skip_unknown = false)
  102. {
  103. // in case you pass directly readPHPArgv() as the first arg
  104. if (PEAR::isError($args)) {
  105. return $args;
  106. }
  107. if (empty($args)) {
  108. return array(array(), array());
  109. }
  110. $non_opts = $opts = array();
  111. settype($args, 'array');
  112. if ($long_options) {
  113. sort($long_options);
  114. }
  115. /*
  116. * Preserve backwards compatibility with callers that relied on
  117. * erroneous POSIX fix.
  118. */
  119. if ($version < 2) {
  120. if (isset($args[0]{0}) && $args[0]{0} != '-') {
  121. array_shift($args);
  122. }
  123. }
  124. reset($args);
  125. while (list($i, $arg) = each($args)) {
  126. /* The special element '--' means explicit end of
  127. options. Treat the rest of the arguments as non-options
  128. and end the loop. */
  129. if ($arg == '--') {
  130. $non_opts = array_merge($non_opts, array_slice($args, $i + 1));
  131. break;
  132. }
  133. if ($arg{0} != '-' || (strlen($arg) > 1 && $arg{1} == '-' && !$long_options)) {
  134. $non_opts = array_merge($non_opts, array_slice($args, $i));
  135. break;
  136. } elseif (strlen($arg) > 1 && $arg{1} == '-') {
  137. $error = Console_Getopt::_parseLongOption(substr($arg, 2),
  138. $long_options,
  139. $opts,
  140. $args,
  141. $skip_unknown);
  142. if (PEAR::isError($error)) {
  143. return $error;
  144. }
  145. } elseif ($arg == '-') {
  146. // - is stdin
  147. $non_opts = array_merge($non_opts, array_slice($args, $i));
  148. break;
  149. } else {
  150. $error = Console_Getopt::_parseShortOption(substr($arg, 1),
  151. $short_options,
  152. $opts,
  153. $args,
  154. $skip_unknown);
  155. if (PEAR::isError($error)) {
  156. return $error;
  157. }
  158. }
  159. }
  160. return array($opts, $non_opts);
  161. }
  162. /**
  163. * Parse short option
  164. *
  165. * @param string $arg Argument
  166. * @param string[] $short_options Available short options
  167. * @param string[][] &$opts
  168. * @param string[] &$args
  169. * @param boolean $skip_unknown suppresses Console_Getopt: unrecognized option
  170. *
  171. * @access private
  172. * @return void
  173. */
  174. function _parseShortOption($arg, $short_options, &$opts, &$args, $skip_unknown)
  175. {
  176. for ($i = 0; $i < strlen($arg); $i++) {
  177. $opt = $arg{$i};
  178. $opt_arg = null;
  179. /* Try to find the short option in the specifier string. */
  180. if (($spec = strstr($short_options, $opt)) === false || $arg{$i} == ':') {
  181. if ($skip_unknown === true) {
  182. break;
  183. }
  184. $msg = "Console_Getopt: unrecognized option -- $opt";
  185. return PEAR::raiseError($msg);
  186. }
  187. if (strlen($spec) > 1 && $spec{1} == ':') {
  188. if (strlen($spec) > 2 && $spec{2} == ':') {
  189. if ($i + 1 < strlen($arg)) {
  190. /* Option takes an optional argument. Use the remainder of
  191. the arg string if there is anything left. */
  192. $opts[] = array($opt, substr($arg, $i + 1));
  193. break;
  194. }
  195. } else {
  196. /* Option requires an argument. Use the remainder of the arg
  197. string if there is anything left. */
  198. if ($i + 1 < strlen($arg)) {
  199. $opts[] = array($opt, substr($arg, $i + 1));
  200. break;
  201. } else if (list(, $opt_arg) = each($args)) {
  202. /* Else use the next argument. */;
  203. if (Console_Getopt::_isShortOpt($opt_arg)
  204. || Console_Getopt::_isLongOpt($opt_arg)) {
  205. $msg = "option requires an argument --$opt";
  206. return PEAR::raiseError("Console_Getopt:" . $msg);
  207. }
  208. } else {
  209. $msg = "option requires an argument --$opt";
  210. return PEAR::raiseError("Console_Getopt:" . $msg);
  211. }
  212. }
  213. }
  214. $opts[] = array($opt, $opt_arg);
  215. }
  216. }
  217. /**
  218. * Checks if an argument is a short option
  219. *
  220. * @param string $arg Argument to check
  221. *
  222. * @access private
  223. * @return bool
  224. */
  225. function _isShortOpt($arg)
  226. {
  227. return strlen($arg) == 2 && $arg[0] == '-'
  228. && preg_match('/[a-zA-Z]/', $arg[1]);
  229. }
  230. /**
  231. * Checks if an argument is a long option
  232. *
  233. * @param string $arg Argument to check
  234. *
  235. * @access private
  236. * @return bool
  237. */
  238. function _isLongOpt($arg)
  239. {
  240. return strlen($arg) > 2 && $arg[0] == '-' && $arg[1] == '-' &&
  241. preg_match('/[a-zA-Z]+$/', substr($arg, 2));
  242. }
  243. /**
  244. * Parse long option
  245. *
  246. * @param string $arg Argument
  247. * @param string[] $long_options Available long options
  248. * @param string[][] &$opts
  249. * @param string[] &$args
  250. *
  251. * @access private
  252. * @return void|PEAR_Error
  253. */
  254. function _parseLongOption($arg, $long_options, &$opts, &$args, $skip_unknown)
  255. {
  256. @list($opt, $opt_arg) = explode('=', $arg, 2);
  257. $opt_len = strlen($opt);
  258. for ($i = 0; $i < count($long_options); $i++) {
  259. $long_opt = $long_options[$i];
  260. $opt_start = substr($long_opt, 0, $opt_len);
  261. $long_opt_name = str_replace('=', '', $long_opt);
  262. /* Option doesn't match. Go on to the next one. */
  263. if ($long_opt_name != $opt) {
  264. continue;
  265. }
  266. $opt_rest = substr($long_opt, $opt_len);
  267. /* Check that the options uniquely matches one of the allowed
  268. options. */
  269. if ($i + 1 < count($long_options)) {
  270. $next_option_rest = substr($long_options[$i + 1], $opt_len);
  271. } else {
  272. $next_option_rest = '';
  273. }
  274. if ($opt_rest != '' && $opt{0} != '=' &&
  275. $i + 1 < count($long_options) &&
  276. $opt == substr($long_options[$i+1], 0, $opt_len) &&
  277. $next_option_rest != '' &&
  278. $next_option_rest{0} != '=') {
  279. $msg = "Console_Getopt: option --$opt is ambiguous";
  280. return PEAR::raiseError($msg);
  281. }
  282. if (substr($long_opt, -1) == '=') {
  283. if (substr($long_opt, -2) != '==') {
  284. /* Long option requires an argument.
  285. Take the next argument if one wasn't specified. */;
  286. if (!strlen($opt_arg) && !(list(, $opt_arg) = each($args))) {
  287. $msg = "Console_Getopt: option requires an argument --$opt";
  288. return PEAR::raiseError($msg);
  289. }
  290. if (Console_Getopt::_isShortOpt($opt_arg)
  291. || Console_Getopt::_isLongOpt($opt_arg)) {
  292. $msg = "Console_Getopt: option requires an argument --$opt";
  293. return PEAR::raiseError($msg);
  294. }
  295. }
  296. } else if ($opt_arg) {
  297. $msg = "Console_Getopt: option --$opt doesn't allow an argument";
  298. return PEAR::raiseError($msg);
  299. }
  300. $opts[] = array('--' . $opt, $opt_arg);
  301. return;
  302. }
  303. if ($skip_unknown === true) {
  304. return;
  305. }
  306. return PEAR::raiseError("Console_Getopt: unrecognized option --$opt");
  307. }
  308. /**
  309. * Safely read the $argv PHP array across different PHP configurations.
  310. * Will take care on register_globals and register_argc_argv ini directives
  311. *
  312. * @access public
  313. * @return mixed the $argv PHP array or PEAR error if not registered
  314. */
  315. function readPHPArgv()
  316. {
  317. global $argv;
  318. if (!is_array($argv)) {
  319. if (!@is_array($_SERVER['argv'])) {
  320. if (!@is_array($GLOBALS['HTTP_SERVER_VARS']['argv'])) {
  321. $msg = "Could not read cmd args (register_argc_argv=Off?)";
  322. return PEAR::raiseError("Console_Getopt: " . $msg);
  323. }
  324. return $GLOBALS['HTTP_SERVER_VARS']['argv'];
  325. }
  326. return $_SERVER['argv'];
  327. }
  328. return $argv;
  329. }
  330. }