command.inc

  1. 8.0.x includes/command.inc
  2. 6.x includes/command.inc
  3. 7.x includes/command.inc
  4. 3.x includes/command.inc
  5. 4.x includes/command.inc
  6. 5.x includes/command.inc
  7. master includes/command.inc

The drush command engine.

Since drush can be invoked independently of a proper Drupal installation and commands may operate across sites, a distinct command engine is needed.

It mimics the Drupal module engine in order to economize on concepts and to make developing commands as familiar as possible to traditional Drupal module developers.

Functions

Namesort descending Description
drush_adjust_args_if_shebang_script Special checking for "shebang" script handling.
drush_append_negation_options
drush_command Entry point for commands into the drush_invoke() API
drush_commandfile_list Collect a list of all available drush command files.
drush_command_defaults
drush_command_default_options Conditionally include default options based on the command used.
drush_command_get_includes
drush_command_hook Determine whether a command file implements a hook.
drush_command_implements Determine which command files are implementing a hook.
drush_command_include Conditionally include files based on the command used.
drush_command_invoke_all Invoke a hook in all available command files that implement it.
drush_command_invoke_all_ref A drush_command_invoke_all() that wants the first parameter to be passed by reference.
drush_command_set_command_specific
drush_command_translate Translates description and other keys of a command definition.
drush_dispatch Given a command record, dispatch it as if it were the original command. Executes in the currently bootstrapped site using the current option contexts. Note that drush_dispatch will not bootstrap any further than the current command has already…
drush_enforce_requirement_bootstrap_phase Check that a command is valid for the current bootstrap phase.
drush_enforce_requirement_core Check that a command is valid for the current major version of core. Handles explicit version numbers and 'plus' numbers like 7+ (compatible with 7,8 ...).
drush_enforce_requirement_drupal_dependencies Check that a command has its declared dependencies available or have no dependencies.
drush_enforce_requirement_drush_dependencies Check that a command has its declared drush dependencies available or have no dependencies. Drush dependencies are helpful when a command is invoking another command, or implementing its API.
drush_filename_blacklist Substrings to ignore during commandfile searching.
drush_get_commandfile_for_command Get the short commandfile name that matches the command.
drush_get_commands Get a list of all implemented commands. This invokes hook_drush_command().
drush_get_original_cli_args_and_options Return the original cli args and options, exactly as they appeared on the command line, and in the same order. Any command-specific options that were set will also appear in this list, appended at the very end.
drush_invoke Invokes a Drush API call, including all hooks.
drush_invoke_process Invoke a command in a new process, targeting the site specified by the provided site alias record.
drush_is_command
drush_parse_args Parse console arguments.
drush_parse_command Matches a commands array, as returned by drush_get_arguments, with the current command table.
drush_process_bootstrap_to_first_arg Process the --bootstrap-to-first-arg option, if it is present.
drush_redispatch_get_options Get the options that were passed to the current command.
drush_shell_alias_replace
drush_shift Pop an argument off of drush's argument list
drush_sitealias_command_default_options
_drush_add_commandfiles
_drush_command_set_default_options
_drush_command_translate Helper function for drush_command_translate().
_drush_find_commandfiles
_drush_flatten_options Return the array keys of $options, plus any 'short-form' representations that may appear in the option's value.
_drush_get_command_options Return the list of all of the options for the given command record by merging the 'options' and 'sub-options' records.
_drush_invoke_hooks Invoke Drush API calls, including all hooks.
_drush_load_command_engines Include, instantiate and validate command engines.
_drush_merge_engine_data Add command structure info from each engine back into the command.
_drush_prepare_command
_drush_verify_cli_arguments
_drush_verify_cli_options Fail with an error if the user specified options on the command line that are not documented in the current command record.

File

includes/command.inc
View source
  1. <?php
  2. /**
  3. * @defgroup dispatching Command dispatching functions.
  4. * @{
  5. *
  6. * These functions handle command dispatching, and can
  7. * be used to programatically invoke drush commands in
  8. * different ways.
  9. */
  10. /**
  11. * Invokes a Drush API call, including all hooks.
  12. *
  13. * Executes the specified command with the specified arguments on the currently
  14. * bootstrapped site using the current option contexts. Note that it will not
  15. * bootstrap any further than the current command has already bootstrapped;
  16. * therefore, you should only invoke commands that have the same (or lower)
  17. * bootstrap requirements.
  18. *
  19. * Commands execute with the same options that the user provided on the
  20. * commandline. If you need to invoke another Drush command with options you
  21. * specify, use drush_invoke_process() instead.
  22. *
  23. * @param string $command
  24. * The command to invoke.
  25. * @param array $arguments
  26. * An array of argument to pass into the command.
  27. *
  28. * @return mixed|false
  29. * The return value from drush_dispatch() or FALSE on error.
  30. *
  31. * @see drush_invoke_process()
  32. */
  33. function drush_invoke($command, $arguments = array()) {
  34. // Convert a standalone argument to a single-element array.
  35. if (!is_array($arguments)) {
  36. $arguments = array($arguments);
  37. }
  38. $commands = drush_get_commands();
  39. if (array_key_exists($command, $commands)) {
  40. $command = $commands[$command];
  41. // Drush overloads the 'arguments' element, which contains the help string
  42. // for the allowed arguments for the command when fetched, and is fixed up
  43. // by _drush_prepare_command() to contain the actual commandline arguments
  44. // during dispatching.
  45. $command['arguments'] = array();
  46. return drush_dispatch($command, $arguments);
  47. }
  48. else {
  49. return drush_set_error('DRUSH_COMMAND_NOT_FOUND', dt("The drush command '!command' could not be found.", array('!command' => $command)));
  50. }
  51. }
  52. /**
  53. * Invoke a command in a new process, targeting the site specified by
  54. * the provided site alias record.
  55. *
  56. * Use this function instead of drush_backend_invoke_sitealias,
  57. * drush_backend_invoke_args, or drush_backend_invoke_command
  58. * (all obsolete in drush 5).
  59. *
  60. * @param array $site_alias_record
  61. * The site record to execute the command on. Use '@self' to run on the current site.
  62. * @param string $command_name
  63. * The command to invoke.
  64. * @param array $commandline_args
  65. * The arguments to pass to the command.
  66. * @param array $commandline_options
  67. * The options (e.g. --select) to provide to the command.
  68. * @param $backend_options
  69. * TRUE - integrate errors
  70. * FALSE - do not integrate errors
  71. * array - @see drush_backend_invoke_concurrent
  72. * There are also several options that _only_ work when set in
  73. * this parameter. They include:
  74. * 'invoke-multiple'
  75. * If $site_alias_record represents a single site, then 'invoke-multiple'
  76. * will cause the _same_ command with the _same_ arguments and options
  77. * to be invoked concurrently (e.g. for running concurrent batch processes).
  78. * 'concurrency'
  79. * Limits the number of concurrent processes that will run at the same time.
  80. * Defaults to '4'.
  81. * 'override-simulated'
  82. * Forces the command to run, even in 'simulated' mode. Useful for
  83. * commands that do not change any state on the machine, e.g. to fetch
  84. * database information for sql-sync via sql-conf.
  85. * 'interactive'
  86. * Overrides the backend invoke process to run commands interactively.
  87. * 'fork'
  88. * Overrides the backend invoke process to run non blocking commands in
  89. * the background. Forks a new process by adding a '&' at the end of the
  90. * command. The calling process does not receive any output from the child
  91. * process. The fork option is used to spawn a process that outlives its
  92. * parent.
  93. *
  94. * @return
  95. * If the command could not be completed successfully, FALSE.
  96. * If the command was completed, this will return an associative
  97. * array containing the results of the API call.
  98. * @see drush_backend_get_result()
  99. *
  100. * Do not change the signature of this function! drush_invoke_process
  101. * is one of the key Drush APIs. See http://drupal.org/node/1152908
  102. */
  103. function drush_invoke_process($site_alias_record, $command_name, $commandline_args = array(), $commandline_options = array(), $backend_options = TRUE) {
  104. if (is_array($site_alias_record) && array_key_exists('site-list', $site_alias_record)) {
  105. $site_alias_records = drush_sitealias_resolve_sitespecs($site_alias_record['site-list']);
  106. $site_alias_records = drush_sitealias_simplify_names($site_alias_records);
  107. foreach ($site_alias_records as $alias_name => $alias_record) {
  108. $invocations[] = array(
  109. 'site' => $alias_record,
  110. 'command' => $command_name,
  111. 'args' => $commandline_args,
  112. );
  113. }
  114. }
  115. else {
  116. $invocations[] = array(
  117. 'site' => $site_alias_record,
  118. 'command' => $command_name,
  119. 'args' => $commandline_args);
  120. $invoke_multiple = drush_get_option_override($backend_options, 'invoke-multiple', 0);
  121. if ($invoke_multiple) {
  122. $invocations = array_fill(0, $invoke_multiple, $invocations[0]);
  123. }
  124. }
  125. return drush_backend_invoke_concurrent($invocations, $commandline_options, $backend_options);
  126. }
  127. /**
  128. * Given a command record, dispatch it as if it were
  129. * the original command. Executes in the currently
  130. * bootstrapped site using the current option contexts.
  131. * Note that drush_dispatch will not bootstrap any further than the
  132. * current command has already bootstrapped; therefore, you should only invoke
  133. * commands that have the same (or lower) bootstrap requirements.
  134. *
  135. * @param command
  136. * A full $command such as returned by drush_get_commands(),
  137. * or a string containing the name of the command record from
  138. * drush_get_commands() to call.
  139. * @param arguments
  140. * An array of argument values.
  141. *
  142. * @see drush_topic_docs_topic().
  143. */
  144. function drush_dispatch($command, $arguments = array()) {
  145. drush_set_command($command);
  146. $return = FALSE;
  147. if ($command) {
  148. // Add arguments, if this has not already been done.
  149. // (If the command was fetched from drush_parse_command,
  150. // then you cannot provide arguments to drush_dispatch.)
  151. if (empty($command['arguments'])) {
  152. _drush_prepare_command($command, $arguments);
  153. }
  154. // Add command-specific options, if applicable.
  155. drush_command_default_options($command);
  156. // Test to see if any of the options in the 'cli' context
  157. // are not represented in the command structure.
  158. if ((_drush_verify_cli_options($command) === FALSE) || (_drush_verify_cli_arguments($command) === FALSE)) {
  159. return FALSE;
  160. }
  161. // Include and validate command engines.
  162. if (_drush_load_command_engines($command) === FALSE) {
  163. return FALSE;
  164. }
  165. // Call the callback function of the active command.
  166. $return = call_user_func_array($command['callback'], $command['arguments']);
  167. }
  168. // Add a final log entry, just so a timestamp appears.
  169. drush_log(dt('Command dispatch complete'), 'notice');
  170. return $return;
  171. }
  172. /**
  173. * Entry point for commands into the drush_invoke() API
  174. *
  175. * If a command does not have a callback specified, this function will be called.
  176. *
  177. * This function will trigger $hook_drush_init, then if no errors occur,
  178. * it will call drush_invoke() with the command that was dispatch.
  179. *
  180. * If no errors have occured, it will run $hook_drush_exit.
  181. */
  182. function drush_command() {
  183. $args = func_get_args();
  184. $command = drush_get_command();
  185. foreach (drush_command_implements("drush_init") as $name) {
  186. $func = $name . '_drush_init';
  187. if (drush_get_option('show-invoke')) {
  188. drush_log(dt("Calling global init hook: !func", array('!name' => $name, '!func' => $func . '()')), 'bootstrap');
  189. }
  190. call_user_func_array($func, $args);
  191. _drush_log_drupal_messages();
  192. }
  193. if (!drush_get_error()) {
  194. _drush_invoke_hooks($command['command-hook'], $args, $command['commandfile']);
  195. }
  196. if (!drush_get_error()) {
  197. foreach (drush_command_implements('drush_exit') as $name) {
  198. $func = $name . '_drush_exit';
  199. if (drush_get_option('show-invoke')) {
  200. drush_log(dt("Calling global exit hook: !func", array('!name' => $name, '!func' => $func . '()')), 'bootstrap');
  201. }
  202. call_user_func_array($func, $args);
  203. _drush_log_drupal_messages();
  204. }
  205. }
  206. }
  207. /**
  208. * Invoke Drush API calls, including all hooks.
  209. *
  210. * This is an internal function; it is called from drush_dispatch via
  211. * drush_command, but only if the command does not specify a 'callback'
  212. * function. If a callback function is specified, it will be called
  213. * instead of drush_command + _drush_invoke_hooks.
  214. *
  215. * Executes the specified command with the specified arguments on the
  216. * currently bootstrapped site using the current option contexts.
  217. * Note that _drush_invoke_hooks will not bootstrap any further than the
  218. * current command has already bootstrapped; therefore, you should only invoke
  219. * commands that have the same (or lower) bootstrap requirements.
  220. *
  221. * Call the correct hook for all the modules that implement it.
  222. * Additionally, the ability to rollback when an error has been encountered is also provided.
  223. * If at any point during execution, the drush_get_error() function returns anything but 0,
  224. * drush_invoke() will trigger $hook_rollback for each of the hooks that implement it,
  225. * in reverse order from how they were executed. Rollbacks are also triggered any
  226. * time a hook function returns FALSE.
  227. *
  228. * This function will also trigger pre_$hook and post_$hook variants of the hook
  229. * and its rollbacks automatically.
  230. *
  231. * HOW DRUSH HOOK FUNCTIONS ARE NAMED:
  232. *
  233. * The name of the hook is composed from the name of the command and the name of
  234. * the command file that the command definition is declared in. The general
  235. * form for the hook filename is:
  236. *
  237. * drush_COMMANDFILE_COMMANDNAME
  238. *
  239. * In many cases, drush commands that are functionally part of a common collection
  240. * of similar commands will all be declared in the same file, and every command
  241. * defined in that file will start with the same command prefix. For example, the
  242. * command file "pm.drush.inc" defines commands such as "pm-enable" and "pm-disable".
  243. * In the case of "pm-enable", the command file is "pm", and and command name is
  244. * "pm-enable". When the command name starts with the same sequence of characters
  245. * as the command file, then the repeated sequence is dropped; thus, the command
  246. * hook for "pm-enable" is "drush_pm_enable", not "drush_pm_pm_enable".
  247. *
  248. * @param command
  249. * The drush command to execute.
  250. * @param args
  251. * An array of arguments to the command OR a single non-array argument.
  252. * @param defined_in_commandfile
  253. * The name of the commandfile that this command exists in. Will be looked up
  254. * if not provided.
  255. * @return
  256. * The return value will be passed along to the caller if --backend option is
  257. * present. A boolean FALSE indicates failure and rollback will be intitated.
  258. *
  259. * This function should not be called directly.
  260. * @see drush_invoke() and @see drush_invoke_process()
  261. */
  262. function _drush_invoke_hooks($command, $args, $defined_in_commandfile = NULL) {
  263. if ($defined_in_commandfile == NULL) {
  264. $defined_in_commandfile = drush_get_commandfile_for_command($command);
  265. }
  266. // If someone passed a standalone arg, convert it to a single-element array
  267. if (!is_array($args)) {
  268. $args = array($args);
  269. }
  270. // Include the external command file used by this command, if there is one.
  271. drush_command_include($command);
  272. // Generate the base name for the hook by converting all
  273. // dashes in the command name to underscores.
  274. $hook = str_replace("-", "_", $command);
  275. // Call the hook init function, if it exists.
  276. // If a command needs to bootstrap, it is advisable
  277. // to do so in _init; otherwise, new commandfiles
  278. // will miss out on participating in any stage that
  279. // has passed or started at the time it was discovered.
  280. $func = 'drush_' . $hook . '_init';
  281. if (function_exists($func)) {
  282. drush_log(dt("Calling drush command init function: !func", array('!func' => $func)), 'bootstrap');
  283. call_user_func_array($func, $args);
  284. _drush_log_drupal_messages();
  285. if (drush_get_error()) {
  286. drush_log(dt('The command @command could not be initialized.', array('@command' => $command)), 'error');
  287. return FALSE;
  288. }
  289. }
  290. $rollback = FALSE;
  291. $completed = array();
  292. $available_rollbacks = array();
  293. $all_available_hooks = array();
  294. // Iterate through the different hook variations
  295. $variations = array($hook . "_pre_validate", $hook . "_validate", "pre_$hook", $hook, "post_$hook");
  296. foreach ($variations as $var_hook) {
  297. // Get the list of command files.
  298. // We re-fetch the list every time through
  299. // the loop in case one of the hook function
  300. // does something that will add additional
  301. // commandfiles to the list (i.e. bootstrapping
  302. // to a higher phase will do this).
  303. $list = drush_commandfile_list();
  304. // Run all of the functions available for this variation
  305. foreach ($list as $commandfile => $filename) {
  306. $func = sprintf("drush_%s_%s", $commandfile, $var_hook);
  307. if (($defined_in_commandfile == $commandfile) && ($commandfile . "_" == substr($var_hook . "_",0,strlen($commandfile)+ 1))) {
  308. $func = sprintf("drush_%s", $var_hook);
  309. }
  310. if (function_exists($func)) {
  311. $all_available_hooks[] = $func . ' [* Defined in ' . $filename . ']';
  312. $available_rollbacks[] = $func . '_rollback';
  313. $completed[] = $func;
  314. $result = call_user_func_array($func, $args);
  315. // Only the 'main' callback can send data to backend.
  316. if ($var_hook == $hook) {
  317. // If the hook already called drush_backend_set_result,
  318. // then return that value. If it did not, then the return
  319. // value from the hook will be the value returned from
  320. // this routine.
  321. $return = drush_backend_get_result();
  322. if (empty($return)) {
  323. drush_backend_set_result($result);
  324. $return = $result;
  325. }
  326. }
  327. _drush_log_drupal_messages();
  328. if (drush_get_error() || ($result === FALSE)) {
  329. $rollback = TRUE;
  330. // break out of the foreach variations and foreach list
  331. break 2;
  332. }
  333. }
  334. else {
  335. $all_available_hooks[] = $func;
  336. }
  337. }
  338. }
  339. // If no hook functions were found, print a warning.
  340. if (empty($completed)) {
  341. $default_command_hook = sprintf("drush_%s_%s", $defined_in_commandfile, $hook);
  342. if (($defined_in_commandfile . "_" == substr($hook . "_",0,strlen($defined_in_commandfile)+ 1))) {
  343. $default_command_hook = sprintf("drush_%s", $hook);
  344. }
  345. $dt_args = array(
  346. '!command' => $command,
  347. '!default_func' => $default_command_hook,
  348. );
  349. $message = "No hook functions were found for !command. The primary hook function is !default_func(). Please implement this function. Run with --show-invoke to see all available hooks.";
  350. $return = drush_set_error('DRUSH_FUNCTION_NOT_FOUND', dt($message, $dt_args));
  351. }
  352. if (drush_get_option('show-invoke')) {
  353. // We show all available hooks up to and including the one that failed (or all, if there were no failures)
  354. drush_log(dt("Available drush_invoke() hooks for !command: !available", array('!command' => $command, '!available' => "\n" . implode("\n", $all_available_hooks))), 'ok');
  355. }
  356. if (drush_get_option('show-invoke') && !empty($available_rollbacks)) {
  357. drush_log(dt("Available rollback hooks for !command: !rollback", array('!command' => $command, '!rollback' => "\n" . implode("\n", $available_rollbacks))), 'ok');
  358. }
  359. // Something went wrong, we need to undo.
  360. if ($rollback) {
  361. if (drush_get_option('confirm-rollback', FALSE)) {
  362. // Optionally ask for confirmation, --yes and --no are ignored from here on as we are about to finish this process.
  363. drush_set_context('DRUSH_AFFIRMATIVE', FALSE);
  364. drush_set_context('DRUSH_NEGATIVE', FALSE);
  365. $rollback = drush_confirm(dt('Do you want to rollback? (manual cleanup might be required otherwise)'));
  366. }
  367. if ($rollback) {
  368. foreach (array_reverse($completed) as $func) {
  369. $rb_func = $func . '_rollback';
  370. if (function_exists($rb_func)) {
  371. call_user_func_array($rb_func, $args);
  372. _drush_log_drupal_messages();
  373. drush_log(dt("Changes made in !func have been rolled back.", array('!func' => $func)), 'rollback');
  374. }
  375. }
  376. }
  377. $return = FALSE;
  378. }
  379. if (isset($return)) {
  380. return $return;
  381. }
  382. }
  383. /**
  384. * Include, instantiate and validate command engines.
  385. *
  386. * @return FALSE if a engine doesn't validate.
  387. */
  388. function _drush_load_command_engines($command) {
  389. foreach ($command['engines'] as $engine_type => $config) {
  390. drush_log(dt("Loading !engine engine.", array('!engine' => $engine_type), 'bootstrap'));
  391. $engine_info = drush_get_engines($engine_type);
  392. $engines = array_keys($engine_info['engines']);
  393. $default = isset($config['default'])?$config['default']:current($engines);
  394. // If the engine provides a command line option to choose between engine
  395. // implementations, get the user selection, if any.
  396. if (!empty($config['option'])) {
  397. $engine = drush_get_option($config['option'], $default);
  398. }
  399. // Otherwise the default engine is the only option.
  400. else {
  401. $engine = $default;
  402. }
  403. if (!in_array($engine, $engines)) {
  404. return drush_set_error('DRUSH_UNKNOWN_ENGINE_TYPE', dt('Unknown !engine_type engine !engine', array('!engine' => $engine, '!engine_type' => $engine_type)));
  405. }
  406. $result = drush_include_engine($engine_type, $engine);
  407. if ($result === FALSE) {
  408. return FALSE;
  409. }
  410. elseif (is_object($result) && method_exists($result, 'validate')) {
  411. $result = $result->validate();
  412. }
  413. else {
  414. $function = strtr($engine_type, '-', '_') . '_validate';
  415. if (function_exists($function)) {
  416. $result = call_user_func($function);
  417. }
  418. }
  419. if (!$result) {
  420. return FALSE;
  421. }
  422. }
  423. }
  424. /**
  425. * Add command structure info from each engine back into the command.
  426. */
  427. function _drush_merge_engine_data(&$command) {
  428. foreach ($command['engines'] as $engine_type => $config) {
  429. // Normalize engines structure.
  430. if (!is_array($config)) {
  431. unset($command['engines'][$engine_type]);
  432. $command['engines'][$config] = array();
  433. $engine_type = $config;
  434. }
  435. // Get all implementations for this engine type.
  436. $engine_info = drush_get_engines($engine_type);
  437. if ($engine_info === FALSE) {
  438. return FALSE;
  439. }
  440. // Override engine_info with customizations in the command.
  441. $config = $command['engines'][$engine_type] += $engine_info['info'];
  442. // Add engine type global options to the command.
  443. $command['options'] += $config['options'];
  444. $engine_data = array();
  445. // If there's a single implementation for this engine type, it will be
  446. // loaded by default, and makes no sense to provide a command line option
  447. // to select the only flavor (ie. --release_info=updatexml), so we won't
  448. // add an option in this case.
  449. // Additionally, depending on the command, it may be convenient to extend
  450. // the command with the engine options.
  451. if (count($engine_info['engines']) == 1) {
  452. if ($config['add-options-to-command'] !== FALSE) {
  453. $engine = key($engine_info['engines']);
  454. $data = $engine_info['engines'][$engine];
  455. foreach (array('options', 'sub-options') as $key) {
  456. if (isset($data[$key])) {
  457. $engine_data[$key] = $data[$key];
  458. }
  459. }
  460. }
  461. }
  462. // Otherwise, provide a command option to choose between engines and add
  463. // the engine options and sub-obtions.
  464. else {
  465. // Process engines in order. First the default engine, the rest alphabetically.
  466. $default = $config['default'];
  467. $engines = array_keys($engine_info['engines']);
  468. asort($engines);
  469. array_unshift($engines, $default);
  470. $engines = array_unique($engines);
  471. // Extend the default engine description.
  472. $desc = $engine_info['engines'][$default]['description'];
  473. $engine_info['engines'][$default]['description'] = dt('Default type engine.', array('type' => $engine_type)) . ' ' . $desc;
  474. $engine_data += array(
  475. 'options' => array(),
  476. 'sub-options' => array(),
  477. );
  478. foreach ($engines as $engine) {
  479. $data = $engine_info['engines'][$engine];
  480. $option = $config['option'] . '=' . $engine;
  481. $engine_data['options'][$option] = array_key_exists('description', $data) ? $data['description'] : NULL;
  482. if (isset($data['options'])) {
  483. $engine_data['sub-options'][$option] = $data['options'];
  484. }
  485. if (isset($data['sub-options'])) {
  486. $engine_data['sub-options'] += $data['sub-options'];
  487. }
  488. }
  489. }
  490. $command = array_merge_recursive($command, $engine_data);
  491. }
  492. }
  493. /**
  494. * Fail with an error if the user specified options on the
  495. * command line that are not documented in the current command
  496. * record.
  497. */
  498. function _drush_verify_cli_options($command) {
  499. // Start out with just the options in the current command record.
  500. $options = _drush_get_command_options($command);
  501. // Skip all tests if the command is marked to allow anything.
  502. // Also skip backend commands, which may have options on the commandline
  503. // that were inherited from the calling command.
  504. if (($command['allow-additional-options'] === TRUE) || (drush_get_option(array('backend', 'invoke'), FALSE))) {
  505. return TRUE;
  506. }
  507. // If 'allow-additional-options' contains a list of command names,
  508. // then union together all of the options from all of the commands.
  509. if (is_array($command['allow-additional-options'])) {
  510. $implemented = drush_get_commands();
  511. foreach ($command['allow-additional-options'] as $subcommand_name) {
  512. if (array_key_exists($subcommand_name, $implemented)) {
  513. $options = array_merge($options, _drush_get_command_options($implemented[$subcommand_name]));
  514. }
  515. }
  516. }
  517. // Also add in global options
  518. $options = array_merge($options, drush_get_global_options());
  519. // Now we will figure out which options in the cli context
  520. // are not represented in our options list.
  521. $cli_options = array_keys(drush_get_context('cli'));
  522. $allowed_options = _drush_flatten_options($options);
  523. $allowed_options = drush_append_negation_options($allowed_options);
  524. $disallowed_options = array_diff($cli_options, $allowed_options);
  525. if (!empty($disallowed_options)) {
  526. $unknown = count($disallowed_options) > 1 ? dt('Unknown options') : dt('Unknown option');
  527. $msg = dt("@unknown: --@options. See `drush help @command` for available options. To suppress this error, add the option --strict=0.", array('@unknown' => $unknown, '@options' => implode(', --', $disallowed_options), '@command' => $command['command']));
  528. if (drush_get_option('strict', TRUE)) {
  529. return drush_set_error('DRUSH_UNKNOWN_OPTION', $msg);
  530. }
  531. }
  532. // Next check to see if all required options were specified.
  533. $missing_required_options = array();
  534. foreach ($command['options'] as $key => $value) {
  535. if (is_array($value) && array_key_exists('required', $value)) {
  536. $option_value = drush_get_option($key, NULL);
  537. if (!isset($option_value)) {
  538. $missing_required_options[] = $key;
  539. }
  540. }
  541. }
  542. if (!empty($missing_required_options)) {
  543. $missing = count($missing_required_options) > 1 ? dt('Missing required options') : dt('Missing required option');
  544. return drush_set_error(dt("@missing: --@options. See `drush help @command` for information on usage.", array('@missing' => $missing, '@options' => implode(', --', $missing_required_options), '@command' => $command['command'])));
  545. }
  546. return TRUE;
  547. }
  548. function drush_append_negation_options($allowed_options) {
  549. $new_allowed = $allowed_options;
  550. foreach ($allowed_options as $option) {
  551. $new_allowed[] = 'no-' . $option;
  552. }
  553. return $new_allowed;
  554. }
  555. function _drush_verify_cli_arguments($command) {
  556. // Check to see if all of the required arguments
  557. // are specified.
  558. if ($command['required-arguments']) {
  559. $required_arg_count = $command['required-arguments'];
  560. if ($required_arg_count === TRUE) {
  561. $required_arg_count = count($command['argument-description']);
  562. }
  563. if ((count($command['arguments'])) < $required_arg_count) {
  564. $missing = count($required_arg_count) > 1 ? dt('Missing required arguments') : dt('Missing required argument');
  565. $required = implode("', '", array_keys($command['argument-description']));
  566. return drush_set_error(dt("@missing: '@required'. See `drush help @command` for information on usage.", array('@missing' => $missing, '@required' => $required, '@command' => $command['command'])));
  567. }
  568. }
  569. return TRUE;
  570. }
  571. /**
  572. * Return the list of all of the options for the given
  573. * command record by merging the 'options' and 'sub-options'
  574. * records.
  575. */
  576. function _drush_get_command_options($command) {
  577. drush_command_invoke_all_ref('drush_help_alter', $command);
  578. $options = $command['options'];
  579. foreach ($command['sub-options'] as $group => $suboptions) {
  580. $options = array_merge($options, $suboptions);
  581. }
  582. return $options;
  583. }
  584. /**
  585. * Return the array keys of $options, plus any 'short-form'
  586. * representations that may appear in the option's value.
  587. */
  588. function _drush_flatten_options($options) {
  589. $flattened_options = array();
  590. foreach($options as $key => $value) {
  591. // engine sections start with 'package-handler=git_drupalorg',
  592. // or something similar. Get rid of everything from the = onward.
  593. if (($eq_pos = strpos($key, '=')) !== FALSE) {
  594. $key = substr($key, 0, $eq_pos);
  595. }
  596. $flattened_options[] = $key;
  597. if (is_array($value)) {
  598. if (array_key_exists('short-form', $value)) {
  599. $flattened_options[] = $value['short-form'];
  600. }
  601. }
  602. }
  603. return $flattened_options;
  604. }
  605. /**
  606. * Get the options that were passed to the current command.
  607. *
  608. * This function returns an array that contains all of the options
  609. * that are appropriate for forwarding along to drush_invoke_process.
  610. *
  611. * @return
  612. * An associative array of option key => value pairs.
  613. */
  614. function drush_redispatch_get_options() {
  615. // Start off by taking everything from the site alias and command line
  616. // ('cli' context)
  617. $cli_context = drush_get_context('cli');
  618. // local php settings should not override sitealias settings
  619. unset($cli_context['php']);
  620. unset($cli_context['php-options']);
  621. // cli overrides sitealias and command specific
  622. $options = $cli_context + drush_get_context('alias') + drush_get_context('specific');
  623. $options = array_diff_key($options, array_flip(drush_sitealias_site_selection_keys()));
  624. unset($options['command-specific']);
  625. unset($options['path-aliases']);
  626. // If we can parse the current command, then examine all contexts
  627. // in order for any option that is directly related to the current command
  628. $command = drush_parse_command();
  629. if (is_array($command)) {
  630. foreach ($command['options'] as $key => $value) {
  631. // Strip leading --
  632. $key = ltrim($key, '-');
  633. $value = drush_get_option($key);
  634. if (isset($value)) {
  635. $options[$key] = $value;
  636. }
  637. }
  638. }
  639. // If --bootstrap-to-first-arg is specified, do not
  640. // pass it along to remote commands.
  641. unset($options['bootstrap-to-first-arg']);
  642. return $options;
  643. }
  644. /**
  645. * @} End of "defgroup dispatching".
  646. */
  647. /**
  648. * @file
  649. * The drush command engine.
  650. *
  651. * Since drush can be invoked independently of a proper Drupal
  652. * installation and commands may operate across sites, a distinct
  653. * command engine is needed.
  654. *
  655. * It mimics the Drupal module engine in order to economize on
  656. * concepts and to make developing commands as familiar as possible
  657. * to traditional Drupal module developers.
  658. */
  659. /**
  660. * Parse console arguments.
  661. */
  662. function drush_parse_args() {
  663. $args = drush_get_context('argv');
  664. $command_args = NULL;
  665. $global_options = array();
  666. $target_alias_name = NULL;
  667. // It would be nice if commandfiles could somehow extend this list,
  668. // but it is not possible. We need to parse args before we find commandfiles,
  669. // because the specified options may affect how commandfiles are located.
  670. // Therefore, commandfiles are loaded too late to affect arg parsing.
  671. // There are only a limited number of short options anyway; drush reserves
  672. // all for use by drush core.
  673. static $arg_opts = array('c', 'u', 'r', 'l', 'i');
  674. // Check to see if we were executed via a "#!/usr/bin/env drush" script
  675. drush_adjust_args_if_shebang_script($args);
  676. // Now process the command line arguments. We will divide them
  677. // into options (starting with a '-') and arguments.
  678. $arguments = $options = array();
  679. for ($i = 1; $i < count($args); $i++) {
  680. $opt = $args[$i];
  681. // We set $command_args to NULL until the first argument that is not
  682. // an alias is found (the command); we put everything that follows
  683. // into $command_args.
  684. if (is_array($command_args)) {
  685. $command_args[] = $opt;
  686. }
  687. // Is the arg an option (starting with '-')?
  688. if (!empty($opt) && $opt{0} == "-" && strlen($opt) != 1) {
  689. // Do we have multiple options behind one '-'?
  690. if (strlen($opt) > 2 && $opt{1} != "-") {
  691. // Each char becomes a key of its own.
  692. for ($j = 1; $j < strlen($opt); $j++) {
  693. $options[substr($opt, $j, 1)] = true;
  694. }
  695. }
  696. // Do we have a longopt (starting with '--')?
  697. elseif ($opt{1} == "-") {
  698. if ($pos = strpos($opt, '=')) {
  699. $options[substr($opt, 2, $pos - 2)] = substr($opt, $pos + 1);
  700. }
  701. else {
  702. $options[substr($opt, 2)] = true;
  703. }
  704. }
  705. else {
  706. $opt = substr($opt, 1);
  707. // Check if the current opt is in $arg_opts (= has to be followed by an argument).
  708. if ((in_array($opt, $arg_opts))) {
  709. // Raising errors for missing option values should be handled by the
  710. // bootstrap or specific command, so we no longer do this here.
  711. $options[$opt] = $args[$i + 1];
  712. $i++;
  713. }
  714. else {
  715. $options[$opt] = true;
  716. }
  717. }
  718. }
  719. // If it's not an option, it's a command.
  720. else {
  721. $arguments[] = $opt;
  722. // Once we find the first argument, record the command args and global options
  723. if (!is_array($command_args)) {
  724. // Remember whether we set $target_alias_name on a previous iteration,
  725. // then record the $target_alias_name iff this arguement references a valid site alias.
  726. $already_set_target = is_string($target_alias_name);
  727. if (!$already_set_target && drush_sitealias_valid_alias_format($opt)) {
  728. $target_alias_name = $opt;
  729. }
  730. // If an alias record was set on a previous iteration, then this
  731. // argument must be the command name. If we set the target alias
  732. // record on this iteration, then this is not the command name.
  733. // If we've found the command name, then save $options in $global_options
  734. // (all options that came before the command name), and initialize
  735. // $command_args to an array so that we will begin storing all args
  736. // and options that follow the command name in $command_args.
  737. if ($already_set_target || (!is_string($target_alias_name))) {
  738. $command_args = array();
  739. $global_options = $options;
  740. }
  741. }
  742. }
  743. }
  744. // If no arguments are specified, then the command will
  745. // be either 'help' or 'version' (the later if --version is specified)
  746. if (!sizeof($arguments)) {
  747. if (array_key_exists('version', $options)) {
  748. $arguments = array('version');
  749. }
  750. else {
  751. $arguments = array('help');
  752. }
  753. }
  754. if (is_array($command_args)) {
  755. drush_set_context('DRUSH_COMMAND_ARGS', $command_args);
  756. }
  757. drush_set_context('DRUSH_GLOBAL_CLI_OPTIONS', $global_options);
  758. // Handle the "@shift" alias, if present
  759. drush_process_bootstrap_to_first_arg($arguments);
  760. drush_set_arguments($arguments);
  761. drush_set_config_special_contexts($options);
  762. drush_set_context('cli', $options);
  763. return $arguments;
  764. }
  765. /**
  766. * Pop an argument off of drush's argument list
  767. */
  768. function drush_shift() {
  769. $arguments = drush_get_arguments();
  770. $result = NULL;
  771. if (!empty($arguments)) {
  772. // The php-script command uses the DRUSH_SHIFT_SKIP
  773. // context to cause drush_shift to skip the 'php-script'
  774. // command and the script path argument when it is
  775. // called from the user script.
  776. $skip_count = drush_get_context('DRUSH_SHIFT_SKIP');
  777. if (is_numeric($skip_count)) {
  778. for ($i = 0; $i < $skip_count; $i++) {
  779. array_shift($arguments);
  780. }
  781. $skip_count = drush_set_context('DRUSH_SHIFT_SKIP', 0);
  782. }
  783. $result = array_shift($arguments);
  784. drush_set_arguments($arguments);
  785. }
  786. return $result;
  787. }
  788. /**
  789. * Special checking for "shebang" script handling.
  790. *
  791. * If there is a file 'script.php' that begins like so:
  792. * #!/path/to/drush
  793. * Then $args will be:
  794. * /path/to/drush /path/to/script userArg1 userArg2 ...
  795. * If it instead starts like this:
  796. * #!/path/to/drush --flag php-script
  797. * Then $args will be:
  798. * /path/to/drush "--flag php-script" /path/to/script userArg1 userArg2 ...
  799. * (Note that execve does not split the parameters from
  800. * the shebang line on whitespace; see http://en.wikipedia.org/wiki/Shebang_%28Unix%29)
  801. * When drush is called via one of the "shebang" lines above,
  802. * the first or second parameter will be the full path
  803. * to the "shebang" script file -- and if the path to the
  804. * script is in the second position, then we will expect that
  805. * the argument in the first position must begin with a
  806. * '@' (alias) or '-' (flag). Under ordinary circumstances,
  807. * we do not expect that the drush command must come before
  808. * any argument that is the full path to a file. We use
  809. * this assumption to detect "shebang" script execution.
  810. */
  811. function drush_adjust_args_if_shebang_script(&$args) {
  812. if (drush_has_bash()) {
  813. // The drush script may add --php or --php-options at the
  814. // head of the argument list; skip past those.
  815. $base_arg_number = 1;
  816. while (substr($args[$base_arg_number], 0, 5) == '--php') {
  817. ++$base_arg_number;
  818. }
  819. if (_drush_is_drush_shebang_script($args[$base_arg_number])) {
  820. // If $args[1] is a drush "shebang" script, we will insert
  821. // the option "--bootstrap-to-first-arg" and the command
  822. // "php-script" at the beginning of @args, so the command
  823. // line args become:
  824. // /path/to/drush --bootstrap-to-first-arg php-script /path/to/script userArg1 userArg2 ...
  825. drush_set_option('bootstrap-to-first-arg', TRUE);
  826. array_splice($args, $base_arg_number, 0, array('php-script'));
  827. drush_set_context('DRUSH_SHEBANG_SCRIPT', TRUE);
  828. }
  829. elseif (((strpos($args[$base_arg_number], ' ') !== FALSE) || (!ctype_alnum($args[$base_arg_number][0]))) && (_drush_is_drush_shebang_script($args[$base_arg_number + 1]))) {
  830. // If $args[2] is a drush "shebang" script, we will insert
  831. // the space-exploded $arg[1] in place of $arg[1], so the
  832. // command line args become:
  833. // /path/to/drush scriptArg1 scriptArg2 ... /path/to/script userArg1 userArg2 ...
  834. // If none of the script arguments look like a drush command,
  835. // then we will insert "php-script" as the default command to
  836. // execute.
  837. $script_args = explode(' ', $args[$base_arg_number]);
  838. $has_command = FALSE;
  839. foreach ($script_args as $script_arg) {
  840. if (preg_match("/^[a-z][a-z0-9-]*$/",$script_arg)) {
  841. $has_command = TRUE;
  842. }
  843. }
  844. if (!$has_command) {
  845. $script_args[] = 'php-script';
  846. }
  847. array_splice($args, 1, $base_arg_number, $script_args);
  848. drush_set_context('DRUSH_SHEBANG_SCRIPT', TRUE);
  849. }
  850. }
  851. }
  852. /**
  853. * Process the --bootstrap-to-first-arg option, if it is present.
  854. *
  855. * This option checks to see if the first user-provided argument is an alias
  856. * or site specification; if it is, it will be shifted into the first argument
  857. * position, where it will specify the site to bootstrap. The result of this
  858. * is that if your shebang line looks like this:
  859. *
  860. * #!/path/to/drush --bootstrap-to-first-arg php-script
  861. *
  862. * Then when you run that script, you can optionally provide an alias such
  863. * as @dev as the first argument (e.g. $ ./mydrushscript.php @dev scriptarg1
  864. * scriptarg2). Since this is the behavior that one would usually want,
  865. * it is default behavior for a canonical script. That is, a script
  866. * with a simple shebang line, like so:
  867. *
  868. * #!/path/to/drush
  869. *
  870. * will implicitly have "--bootstrap-to-first-arg" and "php-script" prepended, and will therefore
  871. * behave exactly like the first example. To write a script that does not
  872. * use --bootstrap-to-first-arg, then the drush command or at least one flag must be explicitly
  873. * included, like so:
  874. *
  875. * #!/path/to/drush php-script
  876. */
  877. function drush_process_bootstrap_to_first_arg(&$arguments) {
  878. if (drush_get_option('bootstrap-to-first-arg', FALSE)) {
  879. $shift_alias_pos = 1 + (drush_get_context('DRUSH_SHEBANG_SCRIPT') === TRUE);
  880. if (sizeof($arguments) >= $shift_alias_pos) {
  881. $shifted_alias = $arguments[$shift_alias_pos];
  882. $alias_record = drush_sitealias_get_record($shifted_alias);
  883. if (!empty($alias_record)) {
  884. // Move the alias we shifted from its current position
  885. // in the argument list to the front of the list
  886. array_splice($arguments, $shift_alias_pos, 1);
  887. array_unshift($arguments, $shifted_alias);
  888. }
  889. }
  890. }
  891. }
  892. /**
  893. * Get the short commandfile name that matches the
  894. * command.
  895. *
  896. * @param $command
  897. * The name of the command (e.g. search-index)
  898. * @return String
  899. * The short commandfile name where that command was
  900. * defined (e.g. search, not search.drush.inc)
  901. */
  902. function drush_get_commandfile_for_command($command) {
  903. $commandfile = FALSE;
  904. $commands = drush_get_commands();
  905. if (array_key_exists($command, $commands)) {
  906. $commandfile = $commands[$command]['commandfile'];
  907. }
  908. return $commandfile;
  909. }
  910. /**
  911. * Get a list of all implemented commands.
  912. * This invokes hook_drush_command().
  913. *
  914. * @return
  915. * Associative array of currently active command descriptors.
  916. *
  917. */
  918. function drush_get_commands() {
  919. $commands = $available_commands = array();
  920. $list = drush_commandfile_list();
  921. foreach ($list as $commandfile => $path) {
  922. if (drush_command_hook($commandfile, 'drush_command')) {
  923. $function = $commandfile . '_drush_command';
  924. $result = $function();
  925. foreach ((array)$result as $key => $command) {
  926. // Add some defaults and normalize the command descriptor.
  927. $command += drush_command_defaults($key, $commandfile, $path);
  928. // Add engine data.
  929. _drush_merge_engine_data($command);
  930. // Translate command.
  931. drush_command_translate($command);
  932. // If command callback function name begins with "drush_$commandfile_",
  933. // then fix up the command entry so that drush_invoke will be
  934. // called by way of drush_command. This will cause all
  935. // of the applicable hook functions to be called for the
  936. // command when it is invoked. If the callback function does
  937. // -not- begin with its commandfile name, then it will be
  938. // called directly by drush_dispatch, and no hook functions
  939. // will be called (e.g. you cannot hook drush_print_file).
  940. if ($command['callback'] != 'drush_command') {
  941. $required_command_prefix = 'drush_' . $commandfile . '_';
  942. if ((substr($command['callback'], 0, strlen($required_command_prefix)) == $required_command_prefix)) {
  943. $command['command-hook'] = substr($command['callback'], strlen('drush_'));
  944. $command['callback'] = 'drush_command';
  945. }
  946. }
  947. $commands[$key] = $command;
  948. // For every alias, make a copy of the command and store it in the command list
  949. // using the alias as a key
  950. if (isset($command['aliases']) && count($command['aliases'])) {
  951. foreach ($command['aliases'] as $alias) {
  952. $commands[$alias] = $command;
  953. $commands[$alias]['is_alias'] = TRUE;
  954. }
  955. }
  956. }
  957. }
  958. }
  959. return drush_set_context('DRUSH_COMMANDS', $commands);
  960. }
  961. function drush_command_defaults($key, $commandfile, $path) {
  962. return array(
  963. 'command' => $key,
  964. 'command-hook' => $key,
  965. 'bootstrap' => DRUSH_BOOTSTRAP_DRUPAL_LOGIN,
  966. 'callback arguments' => array(),
  967. 'commandfile' => $commandfile,
  968. 'path' => dirname($path),
  969. 'engines' => array(), // Helpful for drush_show_help().
  970. 'callback' => 'drush_command',
  971. 'description' => NULL,
  972. 'sections' => array(
  973. 'examples' => 'Examples',
  974. 'arguments' => 'Arguments',
  975. 'options' => 'Options',
  976. ),
  977. 'arguments' => array(),
  978. 'required-arguments' => FALSE,
  979. 'options' => array(),
  980. 'sub-options' => array(),
  981. 'allow-additional-options' => FALSE,
  982. 'examples' => array(),
  983. 'aliases' => array(),
  984. 'core' => array(),
  985. 'scope' => 'site',
  986. 'drupal dependencies' => array(),
  987. 'drush dependencies' => array(),
  988. 'handle-remote-commands' => FALSE,
  989. 'strict-option-handling' => FALSE,
  990. 'bootstrap_errors' => array(),
  991. 'topics' => array(),
  992. 'hidden' => FALSE,
  993. );
  994. }
  995. /**
  996. * Translates description and other keys of a command definition.
  997. *
  998. * @param $command
  999. * A command definition.
  1000. */
  1001. function drush_command_translate(&$command) {
  1002. $command['description'] = _drush_command_translate($command['description']);
  1003. $keys = array('arguments', 'options', 'examples', 'sections');
  1004. foreach ($keys as $key) {
  1005. foreach ($command[$key] as $k => $v) {
  1006. if (is_array($v)) {
  1007. $v['description'] = _drush_command_translate($v['description']);
  1008. }
  1009. else {
  1010. $v = _drush_command_translate($v);
  1011. }
  1012. $command[$key][$k] = $v;
  1013. }
  1014. }
  1015. }
  1016. /**
  1017. * Helper function for drush_command_translate().
  1018. *
  1019. * @param $source
  1020. * String or array.
  1021. */
  1022. function _drush_command_translate($source) {
  1023. return is_array($source) ? call_user_func_array('dt', $source) : dt($source);
  1024. }
  1025. /**
  1026. * Matches a commands array, as returned by drush_get_arguments, with the
  1027. * current command table.
  1028. *
  1029. * Note that not all commands may be discoverable at the point-of-call,
  1030. * since Drupal modules can ship commands as well, and they are
  1031. * not available until after bootstrapping.
  1032. *
  1033. * drush_parse_command returns a normalized command descriptor, which
  1034. * is an associative array. Some of its entries are:
  1035. * - callback arguments: an array of arguments to pass to the calback.
  1036. * - description: description of the command.
  1037. * - arguments: an array of arguments that are understood by the command. for help texts.
  1038. * - required-arguments: The minimum number of arguments that are required, or TRUE if all are required.
  1039. * - options: an array of options that are understood by the command. for help texts.
  1040. * - examples: an array of examples that are understood by the command. for help texts.
  1041. * - scope: one of 'system', 'project', 'site'.
  1042. * - bootstrap: drupal bootstrap level (depends on Drupal major version). -1=no_bootstrap.
  1043. * - core: Drupal major version required.
  1044. * - drupal dependencies: drupal modules required for this command.
  1045. * - drush dependencies: other drush command files required for this command.
  1046. * - handle-remote-commands: set to TRUE if `drush @remote mycommand` should be executed
  1047. * locally rather than remotely dispatched. When this mode is set, the target site
  1048. * can be obtained via:
  1049. * drush_get_context('DRUSH_TARGET_SITE_ALIAS')
  1050. * - strict-option-handling: set to TRUE if drush should strictly separate local command
  1051. * cli options from the global options. Usually, drush allows global cli options and
  1052. * command cli options to be interspersed freely on the commandline. For commands where
  1053. * this flag is set, options are separated, with global options comming before the
  1054. * command names, and command options coming after, like so:
  1055. * drush --global-options command --command-options
  1056. * In this mode, the command options are no longer available via drush_get_option();
  1057. * instead, they can be retrieved via:
  1058. * $args = drush_get_original_cli_args_and_options();
  1059. * $args = drush_get_context('DRUSH_COMMAND_ARGS', array());
  1060. * In this case, $args will contain the command args and options literally, exactly as they
  1061. * were entered on the command line, and in the same order as they appeared.
  1062. */
  1063. function drush_parse_command() {
  1064. $args = drush_get_arguments();
  1065. $command = FALSE;
  1066. // Get a list of all implemented commands.
  1067. $implemented = drush_get_commands();
  1068. if (isset($implemented[$args[0]])) {
  1069. $command = $implemented[$args[0]];
  1070. $arguments = array_slice($args, 1);
  1071. }
  1072. // We have found a command that matches. Set the appropriate values.
  1073. if ($command) {
  1074. // Special case. Force help command if --help option was specified.
  1075. if (drush_get_option('help')) {
  1076. $arguments = array($command['command']);
  1077. $command = $implemented['help'];
  1078. $command['arguments'] = $arguments;
  1079. }
  1080. else {
  1081. _drush_prepare_command($command, $arguments);
  1082. }
  1083. drush_set_command($command);
  1084. }
  1085. return $command;
  1086. }
  1087. /*
  1088. * Called by drush_parse_command. If a command is dispatched
  1089. * directly by drush_dispatch, then drush_dispatch will call
  1090. * this function.
  1091. */
  1092. function _drush_prepare_command(&$command, $arguments = array()) {
  1093. // Drush overloads $command['arguments']; save the argument description
  1094. if (!isset($command['argument-description'])) {
  1095. $command['argument-description'] = $command['arguments'];
  1096. }
  1097. // Merge specified callback arguments, which precede the arguments passed on the command line.
  1098. if (isset($command['callback arguments']) && is_array($command['callback arguments'])) {
  1099. $arguments = array_merge($command['callback arguments'], $arguments);
  1100. }
  1101. $command['arguments'] = $arguments;
  1102. }
  1103. /**
  1104. * Invoke a hook in all available command files that implement it.
  1105. *
  1106. * @see drush_command_invoke_all_ref()
  1107. *
  1108. * @param $hook
  1109. * The name of the hook to invoke.
  1110. * @param ...
  1111. * Arguments to pass to the hook.
  1112. * @return
  1113. * An array of return values of the hook implementations. If commands return
  1114. * arrays from their implementations, those are merged into one array.
  1115. */
  1116. function drush_command_invoke_all() {
  1117. $args = func_get_args();
  1118. if (count($args) == 1) {
  1119. $args[] = NULL;
  1120. }
  1121. $reference_value = $args[1];
  1122. $args[1] = &$reference_value;
  1123. return call_user_func_array('drush_command_invoke_all_ref', $args);
  1124. }
  1125. /**
  1126. * A drush_command_invoke_all() that wants the first parameter to be passed by reference.
  1127. *
  1128. * @see drush_command_invoke_all()
  1129. */
  1130. function drush_command_invoke_all_ref($hook, &$reference_parameter) {
  1131. $args = func_get_args();
  1132. array_shift($args);
  1133. // Insure that call_user_func_array can alter first parameter
  1134. $args[0] = &$reference_parameter;
  1135. $return = array();
  1136. foreach (drush_command_implements($hook) as $module) {
  1137. $function = $module .'_'. $hook;
  1138. $result = call_user_func_array($function, $args);
  1139. if (isset($result) && is_array($result)) {
  1140. $return = array_merge_recursive($return, $result);
  1141. }
  1142. else if (isset($result)) {
  1143. $return[] = $result;
  1144. }
  1145. }
  1146. return $return;
  1147. }
  1148. /**
  1149. * Determine which command files are implementing a hook.
  1150. *
  1151. * @param $hook
  1152. * The name of the hook (e.g. "drush_help" or "drush_command").
  1153. *
  1154. * @return
  1155. * An array with the names of the command files which are implementing this hook.
  1156. */
  1157. function drush_command_implements($hook) {
  1158. $implementations[$hook] = array();
  1159. $list = drush_commandfile_list();
  1160. foreach ($list as $commandfile => $file) {
  1161. if (drush_command_hook($commandfile, $hook)) {
  1162. $implementations[$hook][] = $commandfile;
  1163. }
  1164. }
  1165. return (array)$implementations[$hook];
  1166. }
  1167. /**
  1168. * @param string
  1169. * name of command to check.
  1170. *
  1171. * @return boolean
  1172. * TRUE if the given command has an implementation.
  1173. */
  1174. function drush_is_command($command) {
  1175. $commands = drush_get_commands();
  1176. return isset($commands[$command]);
  1177. }
  1178. /**
  1179. * Collect a list of all available drush command files.
  1180. *
  1181. * Scans the following paths for drush command files:
  1182. *
  1183. * - The "/path/to/drush/commands" folder.
  1184. * - Folders listed in the 'include' option (see example.drushrc.php).
  1185. * - The system-wide drush commands folder, e.g. /usr/share/drush/commands
  1186. * - The ".drush" folder in the user's HOME folder.
  1187. * - sites/all/drush in current Drupal site.
  1188. * - Folders belonging to enabled modules in the current Drupal site.
  1189. *
  1190. * Commands implementing hook_drush_load() in MODULE.drush.load.inc with
  1191. * a return value FALSE will not be loaded.
  1192. *
  1193. * A Drush command file is a file that matches "*.drush.inc".
  1194. *
  1195. * @see drush_scan_directory()
  1196. *
  1197. * @return
  1198. * An associative array whose keys and values are the names of all available
  1199. * command files.
  1200. */
  1201. function drush_commandfile_list() {
  1202. return drush_get_context('DRUSH_COMMAND_FILES', array());
  1203. }
  1204. function _drush_find_commandfiles($phase, $phase_max = FALSE) {
  1205. if (!$phase_max) {
  1206. $phase_max = $phase;
  1207. }
  1208. $searchpath = array();
  1209. switch ($phase) {
  1210. case DRUSH_BOOTSTRAP_DRUSH:
  1211. // Core commands shipping with drush
  1212. $searchpath[] = realpath(dirname(__FILE__) . '/../commands/');
  1213. // User commands, specified by 'include' option
  1214. if ($include = drush_get_context('DRUSH_INCLUDE', FALSE)) {
  1215. foreach ($include as $path) {
  1216. if (is_dir($path)) {
  1217. drush_log('Include ' . $path, 'notice');
  1218. $searchpath[] = $path;
  1219. }
  1220. }
  1221. }
  1222. // System commands, residing in $SHARE_PREFIX/share/drush/commands
  1223. $share_path = drush_get_context('DRUSH_SITE_WIDE_COMMANDFILES');
  1224. if (is_dir($share_path)) {
  1225. $searchpath[] = $share_path;
  1226. }
  1227. // User commands, residing in ~/.drush
  1228. $per_user_config_dir = drush_get_context('DRUSH_PER_USER_CONFIGURATION');
  1229. if (!empty($per_user_config_dir)) {
  1230. $searchpath[] = $per_user_config_dir;
  1231. }
  1232. // Include commandfiles located in Drupal's sites/all/drush even before root is bootstrapped.
  1233. if ($drupal_root = drush_get_context('DRUSH_SELECTED_DRUPAL_ROOT')) {
  1234. $searchpath[] = $drupal_root . '/sites/all/drush';
  1235. }
  1236. break;
  1237. case DRUSH_BOOTSTRAP_DRUPAL_SITE:
  1238. // If we are going to stop bootstrapping at the site, then
  1239. // we will quickly add all commandfiles that we can find for
  1240. // any module associated with the site, whether it is enabled
  1241. // or not. If we are, however, going to continue on to bootstrap
  1242. // all the way to DRUSH_BOOTSTRAP_DRUPAL_FULL, then we will
  1243. // instead wait for that phase, which will more carefully add
  1244. // only those Drush command files that are associated with
  1245. // enabled modules.
  1246. if ($phase_max < DRUSH_BOOTSTRAP_DRUPAL_FULL) {
  1247. $searchpath[] = conf_path() . '/modules';
  1248. // Add all module paths, even disabled modules. Prefer speed over accuracy.
  1249. $searchpath[] = 'sites/all/modules';
  1250. }
  1251. if ($phase_max < DRUSH_BOOTSTRAP_DRUPAL_CONFIGURATION) {
  1252. // Too early for variable_get('install_profile', 'default'); look in all profiles.
  1253. // If we're definitely going to get to DRUPAL_CONFIGURATION, then wait and
  1254. // see if we have 'install_profile' available there.
  1255. $searchpath[] = "profiles";
  1256. }
  1257. // Planning ahead for Drush scripts in core Drupal.
  1258. if (drush_drupal_major_version() >=8) {
  1259. $searchpath[] = 'modules';
  1260. }
  1261. $searchpath[] = 'sites/all/themes';
  1262. $searchpath[] = conf_path() . '/themes';
  1263. break;
  1264. case DRUSH_BOOTSTRAP_DRUPAL_CONFIGURATION:
  1265. // See comment above regarding this if() condition.
  1266. if ($phase_max < DRUSH_BOOTSTRAP_DRUPAL_FULL) {
  1267. // You must define your install_profile in settings.php. The DB is not sufficient.
  1268. // Drupal core does not yet do that. See http://drupal.org/node/545452.
  1269. if ($profile = variable_get('install_profile', NULL)) {
  1270. $searchpath[] = "profiles/$profile/modules";
  1271. }
  1272. else {
  1273. // If 'install_profile' is not available, check all profiles.
  1274. $searchpath[] = "profiles";
  1275. }
  1276. }
  1277. break;
  1278. case DRUSH_BOOTSTRAP_DRUPAL_FULL:
  1279. // Add enabled module paths. Since we are bootstrapped,
  1280. // we can use the Drupal API.
  1281. $ignored_modules = drush_get_option_list('ignored-modules', array());
  1282. foreach (array_diff(module_list(), $ignored_modules) as $module) {
  1283. $filename = drupal_get_filename('module', $module);
  1284. if ($filename) {
  1285. $searchpath[] = dirname($filename);
  1286. }
  1287. }
  1288. break;
  1289. }
  1290. _drush_add_commandfiles($searchpath, $phase);
  1291. }
  1292. function _drush_add_commandfiles($searchpath, $phase = NULL, $reset = FALSE) {
  1293. static $evaluated = array();
  1294. static $deferred = array();
  1295. $cache =& drush_get_context('DRUSH_COMMAND_FILES', array());
  1296. if (sizeof($searchpath)) {
  1297. if (!$reset) {
  1298. // Assemble a cid specific to the bootstrap phase and searchpaths.
  1299. $cid = drush_get_cid('commandfiles-' . $phase, array(), $searchpath);
  1300. $command_cache = drush_cache_get($cid);
  1301. if (isset($command_cache->data)) {
  1302. $cached_list = $command_cache->data;
  1303. // Take drush_make out of the cache to help people transitioning
  1304. // from using drush make as a contrib module to drush make in core.
  1305. // See: http://drupal.org/node/1366746
  1306. unset($cached_list['drush_make']);
  1307. // If we want to temporarily ignore modules via 'ignored-modules',
  1308. // then we need to take these out of the cache as well.
  1309. foreach (drush_get_option_list('ignored-modules') as $ignored) {
  1310. unset($cached_list[$ignored]);
  1311. }
  1312. }
  1313. }
  1314. // Build a list of all of the modules to attempt to load.
  1315. // Start with any modules deferred from a previous phase.
  1316. $list = $deferred;
  1317. if (isset($cached_list)) {
  1318. $list = array_merge($list, $cached_list);
  1319. }
  1320. else {
  1321. // Scan for drush command files; add to list for consideration if found.
  1322. foreach (array_unique($searchpath) as $path) {
  1323. if (is_dir($path)) {
  1324. $nomask = array_merge(drush_filename_blacklist(), drush_get_option_list('ignored-modules'));
  1325. $dmv = DRUSH_MAJOR_VERSION;
  1326. $files = drush_scan_directory($path, "/\.drush($dmv|)\.inc$/", $nomask);
  1327. foreach ($files as $filename => $info) {
  1328. $module = basename($filename);
  1329. $module = str_replace(array('.drush.inc', ".drush$dmv.inc"), '', $module);
  1330. // Only try to bootstrap modules that we have never seen before, or that we
  1331. // have tried to load but did not due to an unmet _drush_load() requirement.
  1332. if (!array_key_exists($module, $evaluated) && file_exists($filename)) {
  1333. $evaluated[$module] = TRUE;
  1334. $list[$module] = $filename;
  1335. }
  1336. }
  1337. }
  1338. }
  1339. if (isset($cid)) {
  1340. drush_cache_set($cid, $list);
  1341. }
  1342. }
  1343. // Check each file in the consideration list; if there is
  1344. // a modulename_drush_load() function in modulename.drush.load.inc,
  1345. // then call it to determine if this file should be loaded.
  1346. foreach ($list as $module => $filename) {
  1347. $load_command = TRUE;
  1348. $load_test_inc = dirname($filename) . "/" . $module . ".drush.load.inc";
  1349. if (file_exists($load_test_inc)) {
  1350. include_once($load_test_inc);
  1351. $load_test_func = $module . "_drush_load";
  1352. if (function_exists($load_test_func)) {
  1353. $load_command = $load_test_func($phase);
  1354. }
  1355. }
  1356. if ($load_command) {
  1357. // Only try to require if the file exists. If not, a file from the
  1358. // command file cache may not be available anymore, in which case
  1359. // we rebuild the cache for this phase.
  1360. if ($filepath = realpath($filename)) {
  1361. require_once $filepath;
  1362. unset($deferred[$module]);
  1363. }
  1364. elseif (!$reset) {
  1365. _drush_add_commandfiles($searchpath, $phase, TRUE);
  1366. }
  1367. }
  1368. else {
  1369. unset($list[$module]);
  1370. // Signal that we should try again on
  1371. // the next bootstrap phase. We set
  1372. // the flag to the filename of the first
  1373. // module we find so that only that one
  1374. // will be retried.
  1375. $deferred[$module] = $filename;
  1376. }
  1377. }
  1378. if (sizeof($list)) {
  1379. $cache = array_merge($cache, $list);
  1380. ksort($cache);
  1381. }
  1382. }
  1383. }
  1384. /**
  1385. * Substrings to ignore during commandfile searching.
  1386. */
  1387. function drush_filename_blacklist() {
  1388. return array_diff(array('.', '..', 'drush_make', 'examples', 'tests', 'disabled', 'gitcache', 'cache', 'drush4', 'drush5', 'drush6', 'drush7'), array('drush' . DRUSH_MAJOR_VERSION));
  1389. }
  1390. /**
  1391. * Conditionally include files based on the command used.
  1392. *
  1393. * Steps through each of the currently loaded commandfiles and
  1394. * loads an optional commandfile based on the key.
  1395. *
  1396. * When a command such as 'pm-enable' is called, this
  1397. * function will find all 'enable.pm.inc' files that
  1398. * are present in each of the commandfile directories.
  1399. */
  1400. function drush_command_include($command) {
  1401. $include_files = drush_command_get_includes($command);
  1402. foreach($include_files as $filename => $commandfile) {
  1403. drush_log(dt('Including !filename', array('!filename' => $filename)), 'bootstrap');
  1404. include_once($filename);
  1405. }
  1406. }
  1407. function drush_command_get_includes($command) {
  1408. $include_files = array();
  1409. $parts = explode('-', $command);
  1410. $command = implode(".", array_reverse($parts));
  1411. $commandfiles = drush_commandfile_list();
  1412. $options = array();
  1413. foreach ($commandfiles as $commandfile => $file) {
  1414. $filename = sprintf("%s/%s.inc", dirname($file), $command);
  1415. if (file_exists($filename)) {
  1416. $include_files[$filename] = $commandfile;
  1417. }
  1418. }
  1419. return $include_files;
  1420. }
  1421. /**
  1422. * Conditionally include default options based on the command used.
  1423. */
  1424. function drush_command_default_options($command = NULL) {
  1425. $command_default_options = drush_get_context('command-specific');
  1426. drush_command_set_command_specific($command_default_options, $command);
  1427. }
  1428. function drush_sitealias_command_default_options($site_record, $prefix, $command = NULL) {
  1429. if (isset($site_record) && array_key_exists($prefix . 'command-specific', $site_record)) {
  1430. drush_command_set_command_specific($site_record[$prefix . 'command-specific'], $command);
  1431. }
  1432. return FALSE;
  1433. }
  1434. function drush_command_set_command_specific($command_default_options, $command = NULL) {
  1435. if (!$command) {
  1436. $command = drush_get_command();
  1437. }
  1438. if ($command) {
  1439. // Look for command-specific options for this command
  1440. // keyed both on the command's primary name, and on each
  1441. // of its aliases.
  1442. $options_were_set = _drush_command_set_default_options($command_default_options, $command['command']);
  1443. if (isset($command['aliases']) && count($command['aliases'])) {
  1444. foreach ($command['aliases'] as $alias) {
  1445. $options_were_set += _drush_command_set_default_options($command_default_options, $alias);
  1446. }
  1447. }
  1448. // If we set or cleared any options, go back and re-bootstrap any global
  1449. // options such as -y and -v.
  1450. if (!empty($options_were_set)) {
  1451. _drush_bootstrap_global_options();
  1452. }
  1453. // If the command uses strict option handling, back out any global
  1454. // options that were set.
  1455. if ($command['strict-option-handling']) {
  1456. $global_options = drush_get_global_options();
  1457. foreach ($options_were_set as $key) {
  1458. if (array_key_exists($key, $global_options)) {
  1459. if (!array_key_exists('context', $global_options[$key])) {
  1460. $strict_options_warning =& drush_get_context('DRUSH_STRICT_OPTIONS_WARNING', array());
  1461. if (!array_key_exists($key, $strict_options_warning)) {
  1462. drush_log(dt("Global option --!option not supported in command-specific options for command !command due to a limitation in strict option handling.", array('!option' => $key, '!command' => $command['command'])), 'warning');
  1463. $strict_options_warning[$key] = TRUE;
  1464. }
  1465. }
  1466. drush_unset_option($key, 'specific');
  1467. }
  1468. }
  1469. }
  1470. }
  1471. }
  1472. function _drush_command_set_default_options($command_default_options, $command) {
  1473. $options_were_set = array();
  1474. if (array_key_exists($command, $command_default_options)) {
  1475. foreach ($command_default_options[$command] as $key => $value) {
  1476. // We set command-specific options in their own context
  1477. // that is higher precedence than the various config file
  1478. // context, but lower than command-line options.
  1479. if (!drush_get_option('no-' . $key, FALSE)) {
  1480. drush_set_option($key, $value, 'specific');
  1481. $options_were_set[] = $key;
  1482. }
  1483. }
  1484. }
  1485. return $options_were_set;
  1486. }
  1487. /**
  1488. * Return the original cli args and options, exactly as they
  1489. * appeared on the command line, and in the same order.
  1490. * Any command-specific options that were set will also
  1491. * appear in this list, appended at the very end.
  1492. *
  1493. * The args and options returned are raw, and must be
  1494. * escaped as necessary before use.
  1495. */
  1496. function drush_get_original_cli_args_and_options($command = NULL) {
  1497. $args = drush_get_context('DRUSH_COMMAND_ARGS', array());
  1498. $command_specific_options = drush_get_context('specific');
  1499. if ($command == NULL) {
  1500. $command = drush_get_command();
  1501. }
  1502. $command_options = ($command == NULL) ? array() : _drush_get_command_options($command);
  1503. foreach ($command_specific_options as $key => $value) {
  1504. if (!array_key_exists($key, $command_options)) {
  1505. if (($value === TRUE) || (!isset($value))) {
  1506. $args[] = "--$key";
  1507. }
  1508. else {
  1509. $args[] = "--$key=$value";
  1510. }
  1511. }
  1512. }
  1513. return $args;
  1514. }
  1515. /**
  1516. * Determine whether a command file implements a hook.
  1517. *
  1518. * @param $module
  1519. * The name of the module (without the .module extension).
  1520. * @param $hook
  1521. * The name of the hook (e.g. "help" or "menu").
  1522. * @return
  1523. * TRUE if the the hook is implemented.
  1524. */
  1525. function drush_command_hook($commandfile, $hook) {
  1526. return function_exists($commandfile . '_' . $hook);
  1527. }
  1528. /**
  1529. * Check that a command is valid for the current bootstrap phase.
  1530. *
  1531. * @param $command
  1532. * Command to check. Any errors will be added to the 'bootstrap_errors' element.
  1533. *
  1534. * @return
  1535. * TRUE if command is valid.
  1536. */
  1537. function drush_enforce_requirement_bootstrap_phase(&$command) {
  1538. $valid = array();
  1539. $current_phase = drush_get_context('DRUSH_BOOTSTRAP_PHASE');
  1540. if ($command['bootstrap'] <= $current_phase) {
  1541. return TRUE;
  1542. }
  1543. // TODO: provide description text for each bootstrap level so we can give
  1544. // the user something more helpful and specific here.
  1545. $command['bootstrap_errors']['DRUSH_COMMAND_INSUFFICIENT_BOOTSTRAP'] = dt('Command !command needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.', array('!command' => $command['command']));
  1546. }
  1547. /**
  1548. * Check that a command has its declared dependencies available or have no
  1549. * dependencies.
  1550. *
  1551. * @param $command
  1552. * Command to check. Any errors will be added to the 'bootstrap_errors' element.
  1553. *
  1554. * @return
  1555. * TRUE if command is valid.
  1556. */
  1557. function drush_enforce_requirement_drupal_dependencies(&$command) {
  1558. // If the command bootstrap is DRUSH_BOOTSTRAP_MAX, then we will
  1559. // allow the requirements to pass if we have not successfully
  1560. // bootstrapped Drupal. The combination of DRUSH_BOOTSTRAP_MAX
  1561. // and 'drupal dependencies' indicates that the drush command
  1562. // will use the dependent modules only if they are available.
  1563. if ($command['bootstrap'] == DRUSH_BOOTSTRAP_MAX) {
  1564. // If we have not bootstrapped, then let the dependencies pass;
  1565. // if we have bootstrapped, then enforce them.
  1566. if (drush_get_context('DRUSH_BOOTSTRAP_PHASE') < DRUSH_BOOTSTRAP_DRUPAL_FULL) {
  1567. return TRUE;
  1568. }
  1569. }
  1570. // If there are no drupal dependencies, then do nothing
  1571. if (!empty($command['drupal dependencies'])) {
  1572. foreach ($command['drupal dependencies'] as $dependency) {
  1573. if(!function_exists('module_exists') || !module_exists($dependency)) {
  1574. $command['bootstrap_errors']['DRUSH_COMMAND_DEPENDENCY_ERROR'] = dt('Command !command needs the following modules installed/enabled to run: !dependencies.', array('!command' => $command['command'], '!dependencies' => implode(', ', $command['drupal dependencies'])));
  1575. return FALSE;
  1576. }
  1577. }
  1578. }
  1579. return TRUE;
  1580. }
  1581. /**
  1582. * Check that a command has its declared drush dependencies available or have no
  1583. * dependencies. Drush dependencies are helpful when a command is invoking
  1584. * another command, or implementing its API.
  1585. *
  1586. * @param $command
  1587. * Command to check. Any errors will be added to the 'bootstrap_errors' element.
  1588. * @return
  1589. * TRUE if dependencies are met.
  1590. */
  1591. function drush_enforce_requirement_drush_dependencies(&$command) {
  1592. // If there are no drush dependencies, then do nothing.
  1593. if (!empty($command['drush dependencies'])) {
  1594. $commandfiles = drush_commandfile_list();
  1595. foreach ($command['drush dependencies'] as $dependency) {
  1596. if (!isset($commandfiles[$dependency])) {
  1597. $dt_args = array(
  1598. '!command' => $command['command'],
  1599. '!dependency' => "$dependency.drush.inc",
  1600. );
  1601. $command['bootstrap_errors']['DRUSH_COMMANDFILE_DEPENDENCY_ERROR'] = dt('Command !command needs the following drush command file to run: !dependency.', $dt_args);
  1602. return FALSE;
  1603. }
  1604. }
  1605. }
  1606. return TRUE;
  1607. }
  1608. /**
  1609. * Check that a command is valid for the current major version of core. Handles
  1610. * explicit version numbers and 'plus' numbers like 7+ (compatible with 7,8 ...).
  1611. *
  1612. * @param $command
  1613. * Command to check. Any errors will be added to the 'bootstrap_errors' element.
  1614. *
  1615. * @return
  1616. * TRUE if command is valid.
  1617. */
  1618. function drush_enforce_requirement_core(&$command) {
  1619. $major = drush_drupal_major_version();
  1620. if (!$core = $command['core']) {
  1621. return TRUE;
  1622. }
  1623. foreach ($core as $compat) {
  1624. if ($compat == $major) {
  1625. return TRUE;
  1626. }
  1627. elseif (substr($compat, -1) == '+' && $major >= substr($compat, 0, strlen($compat)-1)) {
  1628. return TRUE;
  1629. }
  1630. }
  1631. $versions = array_pop($core);
  1632. if (!empty($core)) {
  1633. $versions = implode(', ', $core) . dt(' or ') . $versions;
  1634. }
  1635. $command['bootstrap_errors']['DRUSH_COMMAND_CORE_VERSION_ERROR'] = dt('Command !command requires Drupal core version !versions to run.', array('!command' => $command['command'], '!versions' => $versions));
  1636. }
  1637. /*
  1638. * Check if a shell alias exists for current request. If so, re-route to
  1639. * core-execute like the and pass alias value along with rest of CLI arguments.
  1640. */
  1641. function drush_shell_alias_replace() {
  1642. $args = drush_get_arguments();
  1643. $argv = drush_get_context('argv');
  1644. $first = current($args);
  1645. // @todo drush_get_option is awkward here.
  1646. $shell_aliases = drush_get_context('shell-aliases', array());
  1647. if (isset($shell_aliases[$first])) {
  1648. // Shell alias found for first argument in the request.
  1649. $alias_value = $shell_aliases[$first];
  1650. if (!is_array($alias_value)) {
  1651. // Shell aliases can have embedded variables such as {{@target}} and {{%root}}
  1652. // that are replaced with the name of the target site alias, or the value of a
  1653. // path alias defined in the target site alias record. We only support replacements
  1654. // when the alias value is a string; if it is already broken out into an array,
  1655. // then the values therein are used literally.
  1656. $alias_variables = array( '{{@target}}' => '@none' );
  1657. $target_site_alias = drush_get_context('DRUSH_TARGET_SITE_ALIAS', FALSE);
  1658. if ($target_site_alias) {
  1659. $alias_variables = array( '{{@target}}' => $target_site_alias );
  1660. $target = drush_sitealias_get_record($target_site_alias);
  1661. foreach ($target as $key => $value) {
  1662. if (!is_array($value)) {
  1663. $alias_variables['{{' . $key . '}}'] = $value;
  1664. }
  1665. }
  1666. if (array_key_exists('path-aliases', $target)) {
  1667. foreach ($target['path-aliases'] as $key => $value) {
  1668. // n.b. $key will contain something like "%root" or "%files".
  1669. $alias_variables['{{' . $key . '}}'] = $value;
  1670. }
  1671. }
  1672. }
  1673. $alias_value = str_replace(array_keys($alias_variables), array_values($alias_variables), $alias_value);
  1674. // Check for unmatched replacements
  1675. $matches = array();
  1676. $match_result = preg_match('/{{[%@#]*[a-z0-9.]*}}/', $alias_value, $matches);
  1677. if ($match_result) {
  1678. $unmatched_replacements = implode(', ', $matches);
  1679. $unmatched_replacements = preg_replace('/[{}]/', '', $unmatched_replacements);
  1680. return drush_set_error('DRUSH_SHELL_ALIAS_UNMATCHED_REPLACEMENTS', dt('The shell alias @alias-name uses replacements "@unmatched". You must use this command with a site alias (e.g. `drush @myalias @alias-name ...`) that defines all of these variables.', array('@alias-name' => $first, '@unmatched' => $unmatched_replacements)));
  1681. }
  1682. if (function_exists('str_getcsv')) {
  1683. $alias_value = str_getcsv($alias_value, ' ');
  1684. }
  1685. else {
  1686. $alias_value = explode(' ', $alias_value);
  1687. }
  1688. }
  1689. drush_log(dt('Shell alias found: !key => !value', array('!key' => $first, '!value' => implode(' ', $alias_value))), 'debug');
  1690. $replacement = $alias_value;
  1691. if (substr($alias_value[0], 0, 1) == '!') {
  1692. $replacement[0] = ltrim($replacement[0], '!');
  1693. array_unshift($replacement, 'core-execute');
  1694. }
  1695. $pos = array_search($first, $argv);
  1696. array_splice($argv, $pos, 1, $replacement);
  1697. drush_set_context('argv', $argv);
  1698. drush_parse_args();
  1699. _drush_bootstrap_global_options();
  1700. }
  1701. }