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 ascending Description
_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.
_drush_verify_cli_arguments
_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_invoke_hooks Invoke Drush API calls, including all hooks.
_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_flatten_options Return the array keys of $options, plus any 'short-form' representations that may appear in the option's value.
_drush_find_commandfiles
_drush_command_translate Helper function for drush_command_translate().
_drush_command_set_default_options
_drush_add_commandfiles
drush_sitealias_command_default_options
drush_shift Pop an argument off of drush's argument list
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_redispatch_get_options Get the options that were passed to the current command.
drush_process_bootstrap_to_first_arg Process the --bootstrap-to-first-arg option, if it is present.
drush_parse_command Matches a commands array, as returned by drush_get_arguments, with the current command table.
drush_parse_args Parse console arguments.
drush_is_command
drush_invoke_process Invoke a command in a new process, targeting the site specified by the provided site alias record.
drush_invoke Invokes a Drush API call, including all hooks.
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_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_get_commands Get a list of all implemented commands. This invokes hook_drush_command().
drush_filename_blacklist Substrings to ignore during commandfile and site alias searching.
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_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_bootstrap_phase Check that a command is valid for the current bootstrap phase.
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_command_translate Translates description and other keys of a command definition.
drush_command_set_command_specific_options
drush_command_set_command_specific
drush_command_normalize_name
drush_command_invoke_all_ref A drush_command_invoke_all() that wants the first parameter to be passed by reference.
drush_command_invoke_all Invoke a hook in all available command files that implement it.
drush_command_include Conditionally include files based on the command used.
drush_command_implements Determine which command files are implementing a hook.
drush_command_hook Determine whether a command file implements a hook.
drush_command_get_includes
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_default_options Conditionally include default options based on the command used.
drush_command_defaults
drush_commands_categorize Organize commands into categories. Used by help listing and core-cli.
drush_commandfile_list Collect a list of all available drush command files.
drush_command Entry point for commands into the drush_invoke() API
drush_append_negation_options
drush_adjust_args_if_shebang_script Special checking for "shebang" script handling.
commandfiles_cache

File

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