docopt.php 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  1. <?php
  2. /**
  3. * Command-line interface parser that will make you smile.
  4. *
  5. * - http://docopt.org
  6. * - Repository and issue-tracker: https://github.com/docopt/docopt.php
  7. * - Licensed under terms of MIT license (see LICENSE-MIT)
  8. * - Copyright (c) 2013 Vladimir Keleshev, vladimir@keleshev.com
  9. * Blake Williams, <code@shabbyrobe.org>
  10. */
  11. namespace
  12. {
  13. class Docopt
  14. {
  15. /**
  16. * API compatibility with python docopt
  17. */
  18. static function handle($doc, $params=array())
  19. {
  20. $argv = null;
  21. if (isset($params['argv'])) {
  22. $argv = $params['argv'];
  23. unset($params['argv']);
  24. }
  25. elseif (is_string($params)) {
  26. $argv = $params;
  27. $params = array();
  28. }
  29. $h = new \Docopt\Handler($params);
  30. return $h->handle($doc, $argv);
  31. }
  32. }
  33. }
  34. namespace Docopt
  35. {
  36. /**
  37. * Return true if all cased characters in the string are uppercase and there is
  38. * at least one cased character, false otherwise.
  39. * Python method with no knowrn equivalent in PHP.
  40. */
  41. function is_upper($string)
  42. {
  43. return preg_match('/[A-Z]/', $string) && !preg_match('/[a-z]/', $string);
  44. }
  45. /**
  46. * Return True if any element of the iterable is true. If the iterable is empty, return False.
  47. * Python method with no known equivalent in PHP.
  48. */
  49. function any($iterable)
  50. {
  51. foreach ($iterable as $element) {
  52. if ($element)
  53. return true;
  54. }
  55. return false;
  56. }
  57. /**
  58. * The PHP version of this doesn't support array iterators
  59. */
  60. function array_filter($input, $callback, $reKey=false)
  61. {
  62. if ($input instanceof \ArrayIterator)
  63. $input = $input->getArrayCopy();
  64. $filtered = \array_filter($input, $callback);
  65. if ($reKey) $filtered = array_values($filtered);
  66. return $filtered;
  67. }
  68. /**
  69. * The PHP version of this doesn't support array iterators
  70. */
  71. function array_merge()
  72. {
  73. $values = func_get_args();
  74. $resolved = array();
  75. foreach ($values as $v) {
  76. if ($v instanceof \ArrayIterator)
  77. $resolved[] = $v->getArrayCopy();
  78. else
  79. $resolved[] = $v;
  80. }
  81. return call_user_func_array('array_merge', $resolved);
  82. }
  83. function ends_with($str, $test)
  84. {
  85. $len = strlen($test);
  86. return substr_compare($str, $test, -$len, $len) === 0;
  87. }
  88. function get_class_name($obj)
  89. {
  90. $cls = get_class($obj);
  91. return substr($cls, strpos($cls, '\\')+1);
  92. }
  93. function dumpw($val)
  94. {
  95. echo dump($val);
  96. echo PHP_EOL;
  97. }
  98. function dump($val)
  99. {
  100. $out = "";
  101. if (is_array($val) || $val instanceof \Traversable) {
  102. $out = '[';
  103. $cur = array();
  104. foreach ($val as $i) {
  105. if (is_object($i))
  106. $cur[] = $i->dump();
  107. elseif (is_array($i))
  108. $cur[] = dump($i);
  109. else
  110. $cur[] = dump_scalar($i);
  111. }
  112. $out .= implode(', ', $cur);
  113. $out .= ']';
  114. }
  115. else
  116. $out .=$val->dump();
  117. return $out;
  118. }
  119. function dump_scalar($scalar)
  120. {
  121. if ($scalar === null)
  122. return 'None';
  123. elseif ($scalar === false)
  124. return 'False';
  125. elseif ($scalar === true)
  126. return 'True';
  127. elseif (is_int($scalar) || is_float($scalar))
  128. return $scalar;
  129. else
  130. return "'$scalar'";
  131. }
  132. /**
  133. * Error in construction of usage-message by developer
  134. */
  135. class LanguageError extends \Exception
  136. {
  137. }
  138. /**
  139. * Exit in case user invoked program with incorrect arguments.
  140. * DocoptExit equivalent.
  141. */
  142. class ExitException extends \RuntimeException
  143. {
  144. public static $usage;
  145. public $status;
  146. public function __construct($message=null, $status=1)
  147. {
  148. parent::__construct(trim($message.PHP_EOL.static::$usage));
  149. $this->status = $status;
  150. }
  151. }
  152. class Pattern
  153. {
  154. public function __toString()
  155. {
  156. return serialize($this);
  157. }
  158. public function hash()
  159. {
  160. return crc32((string)$this);
  161. }
  162. public function fix()
  163. {
  164. $this->fixIdentities();
  165. $this->fixRepeatingArguments();
  166. return $this;
  167. }
  168. /**
  169. * Make pattern-tree tips point to same object if they are equal.
  170. */
  171. public function fixIdentities($uniq=null)
  172. {
  173. if (!isset($this->children) || !$this->children)
  174. return $this;
  175. if (!$uniq) {
  176. $uniq = array_unique($this->flat());
  177. }
  178. foreach ($this->children as $i=>$child) {
  179. if (!$child instanceof BranchPattern) {
  180. if (!in_array($child, $uniq)) {
  181. // Not sure if this is a true substitute for 'assert c in uniq'
  182. throw new \UnexpectedValueException();
  183. }
  184. $this->children[$i] = $uniq[array_search($child, $uniq)];
  185. }
  186. else {
  187. $child->fixIdentities($uniq);
  188. }
  189. }
  190. }
  191. /**
  192. * Fix elements that should accumulate/increment values.
  193. */
  194. public function fixRepeatingArguments()
  195. {
  196. $either = array();
  197. foreach (transform($this)->children as $child) {
  198. $either[] = $child->children;
  199. }
  200. foreach ($either as $case) {
  201. $counts = array();
  202. foreach ($case as $child) {
  203. $ser = serialize($child);
  204. if (!isset($counts[$ser]))
  205. $counts[$ser] = array('cnt'=>0, 'items'=>array());
  206. $counts[$ser]['cnt']++;
  207. $counts[$ser]['items'][] = $child;
  208. }
  209. $repeatedCases = array();
  210. foreach ($counts as $child) {
  211. if ($child['cnt'] > 1)
  212. $repeatedCases = array_merge($repeatedCases, $child['items']);
  213. }
  214. foreach ($repeatedCases as $e) {
  215. if ($e instanceof Argument || ($e instanceof Option && $e->argcount)) {
  216. if (!$e->value)
  217. $e->value = array();
  218. elseif (!is_array($e->value) && !$e->value instanceof \Traversable)
  219. $e->value = preg_split('/\s+/', $e->value);
  220. }
  221. if ($e instanceof Command || ($e instanceof Option && $e->argcount == 0))
  222. $e->value = 0;
  223. }
  224. }
  225. return $this;
  226. }
  227. public function name()
  228. {}
  229. public function __get($name)
  230. {
  231. if ($name == 'name')
  232. return $this->name();
  233. else
  234. throw new \BadMethodCallException("Unknown property $name");
  235. }
  236. }
  237. /**
  238. * Expand pattern into an (almost) equivalent one, but with single Either.
  239. *
  240. * Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d)
  241. * Quirks: [-a] => (-a), (-a...) => (-a -a)
  242. */
  243. function transform($pattern)
  244. {
  245. $result = array();
  246. $groups = array(array($pattern));
  247. $parents = array('Required', 'Optional', 'OptionsShortcut', 'Either', 'OneOrMore');
  248. while ($groups) {
  249. $children = array_shift($groups);
  250. $types = array();
  251. foreach ($children as $c) {
  252. if (is_object($c)) {
  253. $types[get_class_name($c)] = true;
  254. }
  255. }
  256. if (array_intersect(array_keys($types), $parents)) {
  257. $child = null;
  258. foreach ($children as $currentChild) {
  259. if (in_array(get_class_name($currentChild), $parents)) {
  260. $child = $currentChild;
  261. break;
  262. }
  263. }
  264. unset($children[array_search($child, $children)]);
  265. $childClass = get_class_name($child);
  266. if ($childClass == 'Either') {
  267. foreach ($child->children as $c) {
  268. $groups[] = array_merge(array($c), $children);
  269. }
  270. }
  271. elseif ($childClass == 'OneOrMore') {
  272. $groups[] = array_merge($child->children, $child->children, $children);
  273. }
  274. else {
  275. $groups[] = array_merge($child->children, $children);
  276. }
  277. }
  278. else {
  279. $result[] = $children;
  280. }
  281. }
  282. $rs = array();
  283. foreach ($result as $e) {
  284. $rs[] = new Required($e);
  285. }
  286. return new Either($rs);
  287. }
  288. class LeafPattern extends Pattern
  289. {
  290. public function flat($types=array())
  291. {
  292. $types = is_array($types) ? $types : array($types);
  293. if (!$types || in_array(get_class_name($this), $types))
  294. return array($this);
  295. else
  296. return array();
  297. }
  298. public function match($left, $collected=null)
  299. {
  300. if (!$collected) $collected = array();
  301. list ($pos, $match) = $this->singleMatch($left);
  302. if (!$match)
  303. return array(false, $left, $collected);
  304. $left_ = $left;
  305. unset($left_[$pos]);
  306. $left_ = array_values($left_);
  307. $name = $this->name;
  308. $sameName = array_filter($collected, function ($a) use ($name) { return $name == $a->name; }, true);
  309. if (is_int($this->value) || is_array($this->value) || $this->value instanceof \Traversable) {
  310. if (is_int($this->value))
  311. $increment = 1;
  312. else
  313. $increment = is_string($match->value) ? array($match->value) : $match->value;
  314. if (!$sameName) {
  315. $match->value = $increment;
  316. return array(true, $left_, array_merge($collected, array($match)));
  317. }
  318. if (is_array($increment) || $increment instanceof \Traversable)
  319. $sameName[0]->value = array_merge($sameName[0]->value, $increment);
  320. else
  321. $sameName[0]->value += $increment;
  322. return array(true, $left_, $collected);
  323. }
  324. return array(true, $left_, array_merge($collected, array($match)));
  325. }
  326. }
  327. class BranchPattern extends Pattern
  328. {
  329. public $children = array();
  330. public function __construct($children=null)
  331. {
  332. if (!$children)
  333. $children = array();
  334. elseif ($children instanceof Pattern)
  335. $children = func_get_args();
  336. foreach ($children as $child) {
  337. $this->children[] = $child;
  338. }
  339. }
  340. public function flat($types=array())
  341. {
  342. $types = is_array($types) ? $types : array($types);
  343. if (in_array(get_class_name($this), $types))
  344. return array($this);
  345. $flat = array();
  346. foreach ($this->children as $c) {
  347. $flat = array_merge($flat, $c->flat($types));
  348. }
  349. return $flat;
  350. }
  351. public function dump()
  352. {
  353. $out = get_class_name($this).'(';
  354. $cd = array();
  355. foreach ($this->children as $c) {
  356. $cd[] = $c->dump();
  357. }
  358. $out .= implode(', ', $cd).')';
  359. return $out;
  360. }
  361. }
  362. class Argument extends LeafPattern
  363. {
  364. /* {{{ this stuff is against LeafPattern in the python version but it interferes with name() */
  365. public $name;
  366. public $value;
  367. public function __construct($name, $value=null)
  368. {
  369. $this->name = $name;
  370. $this->value = $value;
  371. }
  372. /* }}} */
  373. public function singleMatch($left)
  374. {
  375. foreach ($left as $n=>$pattern) {
  376. if ($pattern instanceof Argument) {
  377. return array($n, new Argument($this->name, $pattern->value));
  378. }
  379. }
  380. return array(null, null);
  381. }
  382. public static function parse($source)
  383. {
  384. $name = null;
  385. $value = null;
  386. if (preg_match_all('@(<\S*?'.'>)@', $source, $matches)) {
  387. $name = $matches[0][0];
  388. }
  389. if (preg_match_all('@\[default: (.*)\]@i', $source, $matches)) {
  390. $value = $matches[0][1];
  391. }
  392. return new static($name, $value);
  393. }
  394. public function dump()
  395. {
  396. return get_class_name($this)."(".dump_scalar($this->name).", ".dump_scalar($this->value).")";
  397. }
  398. }
  399. class Command extends Argument
  400. {
  401. public $name;
  402. public $value;
  403. public function __construct($name, $value=false)
  404. {
  405. $this->name = $name;
  406. $this->value = $value;
  407. }
  408. function singleMatch($left)
  409. {
  410. foreach ($left as $n=>$pattern) {
  411. if ($pattern instanceof Argument) {
  412. if ($pattern->value == $this->name)
  413. return array($n, new Command($this->name, true));
  414. else
  415. break;
  416. }
  417. }
  418. return array(null, null);
  419. }
  420. }
  421. class Option extends LeafPattern
  422. {
  423. public $short;
  424. public $long;
  425. public function __construct($short=null, $long=null, $argcount=0, $value=false)
  426. {
  427. if ($argcount != 0 && $argcount != 1)
  428. throw new \InvalidArgumentException();
  429. $this->short = $short;
  430. $this->long = $long;
  431. $this->argcount = $argcount;
  432. $this->value = $value;
  433. // Python checks "value is False". maybe we should check "$value === false"
  434. if (!$value && $argcount)
  435. $this->value = null;
  436. }
  437. public static function parse($optionDescription)
  438. {
  439. $short = null;
  440. $long = null;
  441. $argcount = 0;
  442. $value = false;
  443. $exp = explode(' ', trim($optionDescription), 2);
  444. $options = $exp[0];
  445. $description = isset($exp[1]) ? $exp[1] : '';
  446. $options = str_replace(',', ' ', str_replace('=', ' ', $options));
  447. foreach (preg_split('/\s+/', $options) as $s) {
  448. if (strpos($s, '--')===0)
  449. $long = $s;
  450. elseif ($s && $s[0] == '-')
  451. $short = $s;
  452. else
  453. $argcount = 1;
  454. }
  455. if ($argcount) {
  456. $value = null;
  457. if (preg_match('@\[default: (.*)\]@i', $description, $match)) {
  458. $value = $match[1];
  459. }
  460. }
  461. return new static($short, $long, $argcount, $value);
  462. }
  463. public function singleMatch($left)
  464. {
  465. foreach ($left as $n=>$pattern) {
  466. if ($this->name == $pattern->name) {
  467. return array($n, $pattern);
  468. }
  469. }
  470. return array(null, null);
  471. }
  472. public function name()
  473. {
  474. return $this->long ?: $this->short;
  475. }
  476. public function dump()
  477. {
  478. return "Option(".dump_scalar($this->short).", ".dump_scalar($this->long).", ".dump_scalar($this->argcount).", ".dump_scalar($this->value).")";
  479. }
  480. }
  481. class Required extends BranchPattern
  482. {
  483. public function match($left, $collected=null)
  484. {
  485. if (!$collected)
  486. $collected = array();
  487. $l = $left;
  488. $c = $collected;
  489. foreach ($this->children as $pattern) {
  490. list ($matched, $l, $c) = $pattern->match($l, $c);
  491. if (!$matched)
  492. return array(false, $left, $collected);
  493. }
  494. return array(true, $l, $c);
  495. }
  496. }
  497. class Optional extends BranchPattern
  498. {
  499. public function match($left, $collected=null)
  500. {
  501. if (!$collected)
  502. $collected = array();
  503. foreach ($this->children as $pattern) {
  504. list($m, $left, $collected) = $pattern->match($left, $collected);
  505. }
  506. return array(true, $left, $collected);
  507. }
  508. }
  509. /**
  510. * Marker/placeholder for [options] shortcut.
  511. */
  512. class OptionsShortcut extends Optional
  513. {
  514. }
  515. class OneOrMore extends BranchPattern
  516. {
  517. public function match($left, $collected=null)
  518. {
  519. if (count($this->children) != 1)
  520. throw new \UnexpectedValueException();
  521. if (!$collected)
  522. $collected = array();
  523. $l = $left;
  524. $c = $collected;
  525. $lnew = array();
  526. $matched = true;
  527. $times = 0;
  528. while ($matched) {
  529. # could it be that something didn't match but changed l or c?
  530. list ($matched, $l, $c) = $this->children[0]->match($l, $c);
  531. if ($matched) $times += 1;
  532. if ($lnew == $l)
  533. break;
  534. $lnew = $l;
  535. }
  536. if ($times >= 1)
  537. return array(true, $l, $c);
  538. else
  539. return array(false, $left, $collected);
  540. }
  541. }
  542. class Either extends BranchPattern
  543. {
  544. public function match($left, $collected=null)
  545. {
  546. if (!$collected)
  547. $collected = array();
  548. $outcomes = array();
  549. foreach ($this->children as $pattern) {
  550. list ($matched, $dump1, $dump2) = $outcome = $pattern->match($left, $collected);
  551. if ($matched)
  552. $outcomes[] = $outcome;
  553. }
  554. if ($outcomes) {
  555. // return min(outcomes, key=lambda outcome: len(outcome[1]))
  556. $min = null;
  557. $ret = null;
  558. foreach ($outcomes as $o) {
  559. $cnt = count($o[1]);
  560. if ($min === null || $cnt < $min) {
  561. $min = $cnt;
  562. $ret = $o;
  563. }
  564. }
  565. return $ret;
  566. }
  567. else
  568. return array(false, $left, $collected);
  569. }
  570. }
  571. class Tokens extends \ArrayIterator
  572. {
  573. public $error;
  574. public function __construct($source, $error='ExitException')
  575. {
  576. if (!is_array($source)) {
  577. $source = trim($source);
  578. if ($source)
  579. $source = preg_split('/\s+/', $source);
  580. else
  581. $source = array();
  582. }
  583. parent::__construct($source);
  584. $this->error = $error;
  585. }
  586. public static function fromPattern($source)
  587. {
  588. $source = preg_replace('@([\[\]\(\)\|]|\.\.\.)@', ' $1 ', $source);
  589. $source = preg_split('@\s+|(\S*<.*?>)@', $source, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  590. return new static($source, 'LanguageError');
  591. }
  592. function move()
  593. {
  594. $item = $this->current();
  595. $this->next();
  596. return $item;
  597. }
  598. function left()
  599. {
  600. $left = array();
  601. while (($token = $this->move()) !== null) {
  602. $left[] = $token;
  603. }
  604. return $left;
  605. }
  606. function raiseException($message)
  607. {
  608. $class = __NAMESPACE__.'\\'.$this->error;
  609. throw new $class($message);
  610. }
  611. }
  612. /**
  613. * long ::= '--' chars [ ( ' ' | '=' ) chars ] ;
  614. */
  615. function parse_long($tokens, \ArrayIterator $options)
  616. {
  617. $token = $tokens->move();
  618. $exploded = explode('=', $token, 2);
  619. if (count($exploded) == 2) {
  620. $long = $exploded[0];
  621. $eq = '=';
  622. $value = $exploded[1];
  623. }
  624. else {
  625. $long = $token;
  626. $eq = null;
  627. $value = null;
  628. }
  629. if (strpos($long, '--') !== 0)
  630. throw new \UnexpectedValueExeption();
  631. $value = (!$eq && !$value) ? null : $value;
  632. $similar = array_filter($options, function($o) use ($long) { return $o->long && $o->long == $long; }, true);
  633. if ('ExitException' == $tokens->error && !$similar)
  634. $similar = array_filter($options, function($o) use ($long) { return $o->long && strpos($o->long, $long)===0; }, true);
  635. if (count($similar) > 1) {
  636. // might be simply specified ambiguously 2+ times?
  637. $tokens->raiseException("$long is not a unique prefix: ".implode(', ', array_map(function($o) { return $o->long; }, $similar)));
  638. }
  639. elseif (count($similar) < 1) {
  640. $argcount = $eq == '=' ? 1 : 0;
  641. $o = new Option(null, $long, $argcount);
  642. $options[] = $o;
  643. if ($tokens->error == 'ExitException') {
  644. $o = new Option(null, $long, $argcount, $argcount ? $value : true);
  645. }
  646. }
  647. else {
  648. $o = new Option($similar[0]->short, $similar[0]->long, $similar[0]->argcount, $similar[0]->value);
  649. if ($o->argcount == 0) {
  650. if ($value !== null) {
  651. $tokens->raiseException("{$o->long} must not have an argument");
  652. }
  653. }
  654. else {
  655. if ($value === null) {
  656. if ($tokens->current() === null || $tokens->current() == "--") {
  657. $tokens->raiseException("{$o->long} requires argument");
  658. }
  659. $value = $tokens->move();
  660. }
  661. }
  662. if ($tokens->error == 'ExitException') {
  663. $o->value = $value !== null ? $value : true;
  664. }
  665. }
  666. return array($o);
  667. }
  668. /**
  669. * shorts ::= '-' ( chars )* [ [ ' ' ] chars ] ;
  670. */
  671. function parse_shorts($tokens, \ArrayIterator $options)
  672. {
  673. $token = $tokens->move();
  674. if (strpos($token, '-') !== 0 || strpos($token, '--') === 0)
  675. throw new \UnexpectedValueExeption();
  676. $left = ltrim($token, '-');
  677. $parsed = array();
  678. while ($left != '') {
  679. $short = '-'.$left[0];
  680. $left = substr($left, 1);
  681. $similar = array();
  682. foreach ($options as $o) {
  683. if ($o->short == $short)
  684. $similar[] = $o;
  685. }
  686. $similarCnt = count($similar);
  687. if ($similarCnt > 1) {
  688. $tokens->raiseException("$short is specified ambiguously $similarCnt times");
  689. }
  690. elseif ($similarCnt < 1) {
  691. $o = new Option($short, null, 0);
  692. $options[] = $o;
  693. if ($tokens->error == 'ExitException')
  694. $o = new Option($short, null, 0, true);
  695. }
  696. else {
  697. $o = new Option($short, $similar[0]->long, $similar[0]->argcount, $similar[0]->value);
  698. $value = null;
  699. if ($o->argcount != 0) {
  700. if ($left == '') {
  701. if ($tokens->current() === null || $tokens->current() == '--')
  702. $tokens->raiseException("$short requires argument");
  703. $value = $tokens->move();
  704. }
  705. else {
  706. $value = $left;
  707. $left = '';
  708. }
  709. }
  710. if ($tokens->error == 'ExitException') {
  711. $o->value = $value !== null ? $value : true;
  712. }
  713. }
  714. $parsed[] = $o;
  715. }
  716. return $parsed;
  717. }
  718. function parse_pattern($source, \ArrayIterator $options)
  719. {
  720. $tokens = Tokens::fromPattern($source);
  721. $result = parse_expr($tokens, $options);
  722. if ($tokens->current() != null) {
  723. $tokens->raiseException('unexpected ending: '.implode(' ', $tokens->left()));
  724. }
  725. return new Required($result);
  726. }
  727. /**
  728. * expr ::= seq ( '|' seq )* ;
  729. */
  730. function parse_expr($tokens, \ArrayIterator $options)
  731. {
  732. $seq = parse_seq($tokens, $options);
  733. if ($tokens->current() != '|')
  734. return $seq;
  735. $result = null;
  736. if (count($seq) > 1)
  737. $result = array(new Required($seq));
  738. else
  739. $result = $seq;
  740. while ($tokens->current() == '|') {
  741. $tokens->move();
  742. $seq = parse_seq($tokens, $options);
  743. if (count($seq) > 1)
  744. $result[] = new Required($seq);
  745. else
  746. $result = array_merge($result, $seq);
  747. }
  748. if (count($result) > 1)
  749. return new Either($result);
  750. else
  751. return $result;
  752. }
  753. /**
  754. * seq ::= ( atom [ '...' ] )* ;
  755. */
  756. function parse_seq($tokens, \ArrayIterator $options)
  757. {
  758. $result = array();
  759. $not = array(null, '', ']', ')', '|');
  760. while (!in_array($tokens->current(), $not, true)) {
  761. $atom = parse_atom($tokens, $options);
  762. if ($tokens->current() == '...') {
  763. $atom = array(new OneOrMore($atom));
  764. $tokens->move();
  765. }
  766. if ($atom instanceof \ArrayIterator)
  767. $atom = $atom->getArrayCopy();
  768. if ($atom) {
  769. $result = array_merge($result, $atom);
  770. }
  771. }
  772. return $result;
  773. }
  774. /**
  775. * atom ::= '(' expr ')' | '[' expr ']' | 'options'
  776. * | long | shorts | argument | command ;
  777. */
  778. function parse_atom($tokens, \ArrayIterator $options)
  779. {
  780. $token = $tokens->current();
  781. $result = array();
  782. if ($token == '(' || $token == '[') {
  783. $tokens->move();
  784. static $index;
  785. if (!$index) $index = array('('=>array(')', __NAMESPACE__.'\Required'), '['=>array(']', __NAMESPACE__.'\Optional'));
  786. list ($matching, $pattern) = $index[$token];
  787. $result = new $pattern(parse_expr($tokens, $options));
  788. if ($tokens->move() != $matching)
  789. $tokens->raiseException("Unmatched '$token'");
  790. return array($result);
  791. }
  792. elseif ($token == 'options') {
  793. $tokens->move();
  794. return array(new OptionsShortcut);
  795. }
  796. elseif (strpos($token, '--') === 0 && $token != '--') {
  797. return parse_long($tokens, $options);
  798. }
  799. elseif (strpos($token, '-') === 0 && $token != '-' && $token != '--') {
  800. return parse_shorts($tokens, $options);
  801. }
  802. elseif (strpos($token, '<') === 0 && ends_with($token, '>') || is_upper($token)) {
  803. return array(new Argument($tokens->move()));
  804. }
  805. else {
  806. return array(new Command($tokens->move()));
  807. }
  808. }
  809. /**
  810. * Parse command-line argument vector.
  811. *
  812. * If options_first:
  813. * argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ;
  814. * else:
  815. * argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ;
  816. */
  817. function parse_argv($tokens, \ArrayIterator $options, $optionsFirst=false)
  818. {
  819. $parsed = array();
  820. while ($tokens->current() !== null) {
  821. if ($tokens->current() == '--') {
  822. while ($tokens->current() !== null) {
  823. $parsed[] = new Argument(null, $tokens->move());
  824. }
  825. return $parsed;
  826. }
  827. elseif (strpos($tokens->current(), '--')===0) {
  828. $parsed = array_merge($parsed, parse_long($tokens, $options));
  829. }
  830. elseif (strpos($tokens->current(), '-')===0 && $tokens->current() != '-') {
  831. $parsed = array_merge($parsed, parse_shorts($tokens, $options));
  832. }
  833. elseif ($optionsFirst) {
  834. return array_merge($parsed, array_map(function($v) { return new Argument(null, $v); }, $tokens->left()));
  835. }
  836. else {
  837. $parsed[] = new Argument(null, $tokens->move());
  838. }
  839. }
  840. return $parsed;
  841. }
  842. function parse_defaults($doc)
  843. {
  844. $defaults = array();
  845. foreach (parse_section('options:', $doc) as $s) {
  846. # FIXME corner case "bla: options: --foo"
  847. list (, $s) = explode(':', $s, 2);
  848. $splitTmp = array_slice(preg_split("@\n[ \t]*(-\S+?)@", "\n".$s, null, PREG_SPLIT_DELIM_CAPTURE), 1);
  849. $split = array();
  850. for ($cnt = count($splitTmp), $i=0; $i < $cnt; $i+=2) {
  851. $split[] = $splitTmp[$i] . (isset($splitTmp[$i+1]) ? $splitTmp[$i+1] : '');
  852. }
  853. $options = array();
  854. foreach ($split as $s) {
  855. if (strpos($s, '-') === 0)
  856. $options[] = Option::parse($s);
  857. }
  858. $defaults = array_merge($defaults, $options);
  859. }
  860. return new \ArrayIterator($defaults);
  861. }
  862. function parse_section($name, $source)
  863. {
  864. $ret = array();
  865. if (preg_match_all('@^([^\n]*'.$name.'[^\n]*\n?(?:[ \t].*?(?:\n|$))*)@im', $source, $matches, PREG_SET_ORDER)) {
  866. foreach ($matches as $match) {
  867. $ret[] = trim($match[0]);
  868. }
  869. }
  870. return $ret;
  871. }
  872. function formal_usage($section)
  873. {
  874. list (, $section) = explode(':', $section, 2); # drop "usage:"
  875. $pu = preg_split('/\s+/', trim($section));
  876. $ret = array();
  877. foreach (array_slice($pu, 1) as $s) {
  878. if ($s == $pu[0])
  879. $ret[] = ') | (';
  880. else
  881. $ret[] = $s;
  882. }
  883. return '( '.implode(' ', $ret).' )';
  884. }
  885. function extras($help, $version, $options, $doc)
  886. {
  887. $ofound = false;
  888. $vfound = false;
  889. foreach ($options as $o) {
  890. if ($o->value && ($o->name == '-h' || $o->name == '--help'))
  891. $ofound = true;
  892. if ($o->value && $o->name == '--version')
  893. $vfound = true;
  894. }
  895. if ($help && $ofound) {
  896. ExitException::$usage = null;
  897. throw new ExitException($doc, 0);
  898. }
  899. if ($version && $vfound) {
  900. ExitException::$usage = null;
  901. throw new ExitException($version, 0);
  902. }
  903. }
  904. class Handler
  905. {
  906. public $exit = true;
  907. public $exitFullUsage = false;
  908. public $help = true;
  909. public $optionsFirst = false;
  910. public $version;
  911. public function __construct($options=array())
  912. {
  913. foreach ($options as $k=>$v)
  914. $this->$k = $v;
  915. }
  916. function handle($doc, $argv=null)
  917. {
  918. try {
  919. if ($argv === null && isset($_SERVER['argv']))
  920. $argv = array_slice($_SERVER['argv'], 1);
  921. $usageSections = parse_section('usage:', $doc);
  922. if (count($usageSections) == 0)
  923. throw new LanguageError('"usage:" (case-insensitive) not found.');
  924. elseif (count($usageSections) > 1)
  925. throw new LanguageError('More than one "usage:" (case-insensitive).');
  926. $usage = $usageSections[0];
  927. // temp fix until python port provides solution
  928. ExitException::$usage = !$this->exitFullUsage ? $usage : $doc;
  929. $options = parse_defaults($doc);
  930. $formalUse = formal_usage($usage);
  931. $pattern = parse_pattern($formalUse, $options);
  932. $argv = parse_argv(new Tokens($argv), $options, $this->optionsFirst);
  933. $patternOptions = $pattern->flat('Option');
  934. foreach ($pattern->flat('OptionsShortcut') as $optionsShortcut) {
  935. $docOptions = parse_defaults($doc);
  936. $optionsShortcut->children = array_diff((array)$docOptions, $patternOptions);
  937. }
  938. extras($this->help, $this->version, $argv, $doc);
  939. list($matched, $left, $collected) = $pattern->fix()->match($argv);
  940. if ($matched && !$left) {
  941. $return = array();
  942. foreach (array_merge($pattern->flat(), $collected) as $a) {
  943. $name = $a->name;
  944. if ($name)
  945. $return[$name] = $a->value;
  946. }
  947. return new Response($return);
  948. }
  949. throw new ExitException();
  950. }
  951. catch (ExitException $ex) {
  952. $this->handleExit($ex);
  953. return new Response(null, $ex->status, $ex->getMessage());
  954. }
  955. }
  956. function handleExit(ExitException $ex)
  957. {
  958. if ($this->exit) {
  959. echo $ex->getMessage().PHP_EOL;
  960. exit($ex->status);
  961. }
  962. }
  963. }
  964. class Response implements \ArrayAccess, \IteratorAggregate
  965. {
  966. public $status;
  967. public $output;
  968. public $args;
  969. public function __construct($args, $status=0, $output='')
  970. {
  971. $this->args = $args ?: array();
  972. $this->status = $status;
  973. $this->output = $output;
  974. }
  975. public function __get($name)
  976. {
  977. if ($name == 'success')
  978. return $this->status === 0;
  979. else
  980. throw new \BadMethodCallException("Unknown property $name");
  981. }
  982. public function offsetExists($offset)
  983. {
  984. return isset($this->args[$offset]);
  985. }
  986. public function offsetGet($offset)
  987. {
  988. return $this->args[$offset];
  989. }
  990. public function offsetSet($offset, $value)
  991. {
  992. $this->args[$offset] = $value;
  993. }
  994. public function offsetUnset($offset)
  995. {
  996. unset($this->args[$offset]);
  997. }
  998. public function getIterator()
  999. {
  1000. return new \ArrayIterator($this->args);
  1001. }
  1002. }
  1003. }