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_command_specific_options Return all of the command-specific options defined in the given options set for the specified command name. Note that it is valid to use the command name alias rather than the primary command name, both in the parameter to this function, and in the…
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_normalize_name
drush_command_set_command_specific
drush_command_set_command_specific_options
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_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_handle_command_output Convert the structured output array provided from the Drush command into formatted output. Output is only printed for commands that define 'default-format' &/or 'default-pipe-format'; all other commands are expected to do…
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 Check if a shell alias exists for current request. If so, re-route to core-execute and pass alias value along with rest of CLI arguments.
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_prepare_command Called by drush_parse_command. If a command is dispatched directly by drush_dispatch, then drush_dispatch will call this function.
_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. Also verify that required options are present.

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