You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Getopt.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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$
  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. */
  69. public static function getopt2($args, $short_options, $long_options = null, $skip_unknown = false)
  70. {
  71. return Console_Getopt::doGetopt(2, $args, $short_options, $long_options, $skip_unknown);
  72. }
  73. /**
  74. * This function expects $args to start with the script name (POSIX-style).
  75. * Preserved for backwards compatibility.
  76. *
  77. * @param array $args an array of command-line arguments
  78. * @param string $short_options specifies the list of allowed short options
  79. * @param array $long_options specifies the list of allowed long options
  80. *
  81. * @see getopt2()
  82. * @return array two-element array containing the list of parsed options and
  83. * the non-option arguments
  84. */
  85. public static function getopt($args, $short_options, $long_options = null, $skip_unknown = false)
  86. {
  87. return Console_Getopt::doGetopt(1, $args, $short_options, $long_options, $skip_unknown);
  88. }
  89. /**
  90. * The actual implementation of the argument parsing code.
  91. *
  92. * @param int $version Version to use
  93. * @param array $args an array of command-line arguments
  94. * @param string $short_options specifies the list of allowed short options
  95. * @param array $long_options specifies the list of allowed long options
  96. * @param boolean $skip_unknown suppresses Console_Getopt: unrecognized option
  97. *
  98. * @return array
  99. */
  100. public static function doGetopt($version, $args, $short_options, $long_options = null, $skip_unknown = false)
  101. {
  102. // in case you pass directly readPHPArgv() as the first arg
  103. if (PEAR::isError($args)) {
  104. return $args;
  105. }
  106. if (empty($args)) {
  107. return array(array(), array());
  108. }
  109. $non_opts = $opts = array();
  110. settype($args, 'array');
  111. if ($long_options) {
  112. sort($long_options);
  113. }
  114. /*
  115. * Preserve backwards compatibility with callers that relied on
  116. * erroneous POSIX fix.
  117. */
  118. if ($version < 2) {
  119. if (isset($args[0]{0}) && $args[0]{0} != '-') {
  120. array_shift($args);
  121. }
  122. }
  123. reset($args);
  124. while (list($i, $arg) = each($args)) {
  125. /* The special element '--' means explicit end of
  126. options. Treat the rest of the arguments as non-options
  127. and end the loop. */
  128. if ($arg == '--') {
  129. $non_opts = array_merge($non_opts, array_slice($args, $i + 1));
  130. break;
  131. }
  132. if ($arg{0} != '-' || (strlen($arg) > 1 && $arg{1} == '-' && !$long_options)) {
  133. $non_opts = array_merge($non_opts, array_slice($args, $i));
  134. break;
  135. } elseif (strlen($arg) > 1 && $arg{1} == '-') {
  136. $error = Console_Getopt::_parseLongOption(substr($arg, 2),
  137. $long_options,
  138. $opts,
  139. $args,
  140. $skip_unknown);
  141. if (PEAR::isError($error)) {
  142. return $error;
  143. }
  144. } elseif ($arg == '-') {
  145. // - is stdin
  146. $non_opts = array_merge($non_opts, array_slice($args, $i));
  147. break;
  148. } else {
  149. $error = Console_Getopt::_parseShortOption(substr($arg, 1),
  150. $short_options,
  151. $opts,
  152. $args,
  153. $skip_unknown);
  154. if (PEAR::isError($error)) {
  155. return $error;
  156. }
  157. }
  158. }
  159. return array($opts, $non_opts);
  160. }
  161. /**
  162. * Parse short option
  163. *
  164. * @param string $arg Argument
  165. * @param string[] $short_options Available short options
  166. * @param string[][] &$opts
  167. * @param string[] &$args
  168. * @param boolean $skip_unknown suppresses Console_Getopt: unrecognized option
  169. *
  170. * @return void
  171. */
  172. protected static function _parseShortOption($arg, $short_options, &$opts, &$args, $skip_unknown)
  173. {
  174. for ($i = 0; $i < strlen($arg); $i++) {
  175. $opt = $arg{$i};
  176. $opt_arg = null;
  177. /* Try to find the short option in the specifier string. */
  178. if (($spec = strstr($short_options, $opt)) === false || $arg{$i} == ':') {
  179. if ($skip_unknown === true) {
  180. break;
  181. }
  182. $msg = "Console_Getopt: unrecognized option -- $opt";
  183. return PEAR::raiseError($msg);
  184. }
  185. if (strlen($spec) > 1 && $spec{1} == ':') {
  186. if (strlen($spec) > 2 && $spec{2} == ':') {
  187. if ($i + 1 < strlen($arg)) {
  188. /* Option takes an optional argument. Use the remainder of
  189. the arg string if there is anything left. */
  190. $opts[] = array($opt, substr($arg, $i + 1));
  191. break;
  192. }
  193. } else {
  194. /* Option requires an argument. Use the remainder of the arg
  195. string if there is anything left. */
  196. if ($i + 1 < strlen($arg)) {
  197. $opts[] = array($opt, substr($arg, $i + 1));
  198. break;
  199. } else if (list(, $opt_arg) = each($args)) {
  200. /* Else use the next argument. */;
  201. if (Console_Getopt::_isShortOpt($opt_arg)
  202. || Console_Getopt::_isLongOpt($opt_arg)) {
  203. $msg = "option requires an argument --$opt";
  204. return PEAR::raiseError("Console_Getopt: " . $msg);
  205. }
  206. } else {
  207. $msg = "option requires an argument --$opt";
  208. return PEAR::raiseError("Console_Getopt: " . $msg);
  209. }
  210. }
  211. }
  212. $opts[] = array($opt, $opt_arg);
  213. }
  214. }
  215. /**
  216. * Checks if an argument is a short option
  217. *
  218. * @param string $arg Argument to check
  219. *
  220. * @return bool
  221. */
  222. protected static function _isShortOpt($arg)
  223. {
  224. return strlen($arg) == 2 && $arg[0] == '-'
  225. && preg_match('/[a-zA-Z]/', $arg[1]);
  226. }
  227. /**
  228. * Checks if an argument is a long option
  229. *
  230. * @param string $arg Argument to check
  231. *
  232. * @return bool
  233. */
  234. protected static function _isLongOpt($arg)
  235. {
  236. return strlen($arg) > 2 && $arg[0] == '-' && $arg[1] == '-' &&
  237. preg_match('/[a-zA-Z]+$/', substr($arg, 2));
  238. }
  239. /**
  240. * Parse long option
  241. *
  242. * @param string $arg Argument
  243. * @param string[] $long_options Available long options
  244. * @param string[][] &$opts
  245. * @param string[] &$args
  246. *
  247. * @return void|PEAR_Error
  248. */
  249. protected static function _parseLongOption($arg, $long_options, &$opts, &$args, $skip_unknown)
  250. {
  251. @list($opt, $opt_arg) = explode('=', $arg, 2);
  252. $opt_len = strlen($opt);
  253. for ($i = 0; $i < count($long_options); $i++) {
  254. $long_opt = $long_options[$i];
  255. $opt_start = substr($long_opt, 0, $opt_len);
  256. $long_opt_name = str_replace('=', '', $long_opt);
  257. /* Option doesn't match. Go on to the next one. */
  258. if ($long_opt_name != $opt) {
  259. continue;
  260. }
  261. $opt_rest = substr($long_opt, $opt_len);
  262. /* Check that the options uniquely matches one of the allowed
  263. options. */
  264. if ($i + 1 < count($long_options)) {
  265. $next_option_rest = substr($long_options[$i + 1], $opt_len);
  266. } else {
  267. $next_option_rest = '';
  268. }
  269. if ($opt_rest != '' && $opt{0} != '=' &&
  270. $i + 1 < count($long_options) &&
  271. $opt == substr($long_options[$i+1], 0, $opt_len) &&
  272. $next_option_rest != '' &&
  273. $next_option_rest{0} != '=') {
  274. $msg = "Console_Getopt: option --$opt is ambiguous";
  275. return PEAR::raiseError($msg);
  276. }
  277. if (substr($long_opt, -1) == '=') {
  278. if (substr($long_opt, -2) != '==') {
  279. /* Long option requires an argument.
  280. Take the next argument if one wasn't specified. */;
  281. if (!strlen($opt_arg) && !(list(, $opt_arg) = each($args))) {
  282. $msg = "Console_Getopt: option requires an argument --$opt";
  283. return PEAR::raiseError($msg);
  284. }
  285. if (Console_Getopt::_isShortOpt($opt_arg)
  286. || Console_Getopt::_isLongOpt($opt_arg)) {
  287. $msg = "Console_Getopt: option requires an argument --$opt";
  288. return PEAR::raiseError($msg);
  289. }
  290. }
  291. } else if ($opt_arg) {
  292. $msg = "Console_Getopt: option --$opt doesn't allow an argument";
  293. return PEAR::raiseError($msg);
  294. }
  295. $opts[] = array('--' . $opt, $opt_arg);
  296. return;
  297. }
  298. if ($skip_unknown === true) {
  299. return;
  300. }
  301. return PEAR::raiseError("Console_Getopt: unrecognized option --$opt");
  302. }
  303. /**
  304. * Safely read the $argv PHP array across different PHP configurations.
  305. * Will take care on register_globals and register_argc_argv ini directives
  306. *
  307. * @return mixed the $argv PHP array or PEAR error if not registered
  308. */
  309. public static function readPHPArgv()
  310. {
  311. global $argv;
  312. if (!is_array($argv)) {
  313. if (!@is_array($_SERVER['argv'])) {
  314. if (!@is_array($GLOBALS['HTTP_SERVER_VARS']['argv'])) {
  315. $msg = "Could not read cmd args (register_argc_argv=Off?)";
  316. return PEAR::raiseError("Console_Getopt: " . $msg);
  317. }
  318. return $GLOBALS['HTTP_SERVER_VARS']['argv'];
  319. }
  320. return $_SERVER['argv'];
  321. }
  322. return $argv;
  323. }
  324. }