features.drush.inc 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. <?php
  2. /**
  3. * @file
  4. * Features module drush integration.
  5. */
  6. /**
  7. * Implements hook_drush_command().
  8. *
  9. * @return
  10. * An associative array describing your command(s).
  11. *
  12. * @see drush_parse_command()
  13. */
  14. function features_drush_command() {
  15. $items = array();
  16. // If Features is enabled display the configured default export path,
  17. // otherwise just show the default.
  18. if (defined('FEATURES_DEFAULT_EXPORT_PATH')) {
  19. $path = variable_get('features_default_export_path', FEATURES_DEFAULT_EXPORT_PATH);
  20. }
  21. else {
  22. $path = 'sites/all/modules';
  23. }
  24. $items['features-list'] = array(
  25. 'description' => "List all the available features for your site.",
  26. 'options' => array(
  27. 'status' => "Feature status, can be 'enabled', 'disabled' or 'all'",
  28. ),
  29. 'drupal dependencies' => array('features'),
  30. 'aliases' => array('fl', 'features'),
  31. );
  32. $items['features-export'] = array(
  33. 'description' => "Export a feature from your site into a module.",
  34. 'arguments' => array(
  35. 'feature' => 'Feature name to export.',
  36. 'components' => 'Patterns of components to include, see features-components for the format of patterns.'
  37. ),
  38. 'options' => array(
  39. 'destination' => "Destination path (from Drupal root) of the exported feature. Defaults to '" . $path . "'.",
  40. 'version-set' => "Specify a version number for the feature.",
  41. 'version-increment' => "Increment the feature's version number.",
  42. ),
  43. 'drupal dependencies' => array('features'),
  44. 'aliases' => array('fe'),
  45. );
  46. $items['features-add'] = array(
  47. 'description' => "Add a component to a feature module. (DEPRECATED: use features-export)",
  48. 'arguments' => array(
  49. 'feature' => 'Feature name to add to.',
  50. 'components' => 'List of components to add.',
  51. ),
  52. 'options' => array(
  53. 'version-set' => "Specify a version number for the feature.",
  54. 'version-increment' => "Increment the feature's version number.",
  55. ),
  56. 'drupal dependencies' => array('features'),
  57. 'aliases' => array('fa'),
  58. );
  59. $items['features-components'] = array(
  60. 'description' => 'List features components.',
  61. 'arguments' => array(
  62. 'patterns' => 'The features components type to list. Omit this argument to list all components.',
  63. ),
  64. 'options' => array(
  65. 'exported' => array(
  66. 'description' => 'Show only components that have been exported.',
  67. ),
  68. 'not-exported' => array(
  69. 'description' => 'Show only components that have not been exported.',
  70. ),
  71. ),
  72. 'aliases' => array('fc'),
  73. );
  74. $items['features-update'] = array(
  75. 'description' => "Update a feature module on your site.",
  76. 'arguments' => array(
  77. 'feature' => 'A space delimited list of features.',
  78. ),
  79. 'options' => array(
  80. 'version-set' => "Specify a version number for the feature.",
  81. 'version-increment' => "Increment the feature's version number.",
  82. ),
  83. 'drupal dependencies' => array('features'),
  84. 'aliases' => array('fu'),
  85. );
  86. $items['features-update-all'] = array(
  87. 'description' => "Update all feature modules on your site.",
  88. 'arguments' => array(
  89. 'feature_exclude' => 'A space-delimited list of features to exclude from being updated.',
  90. ),
  91. 'drupal dependencies' => array('features'),
  92. 'aliases' => array('fu-all', 'fua'),
  93. );
  94. $items['features-revert'] = array(
  95. 'description' => "Revert a feature module on your site.",
  96. 'arguments' => array(
  97. 'feature' => 'A space delimited list of features or feature.component pairs.',
  98. ),
  99. 'options' => array(
  100. 'force' => "Force revert even if Features assumes components' state are default.",
  101. ),
  102. 'examples' => array(
  103. 'drush fr foo.node foo.taxonomy bar' => 'Revert node and taxonomy components of feature "foo", but only if they are overriden. Revert all overriden components of feature "bar".',
  104. 'drush fr foo.node foo.taxonomy bar --force' => 'Revert node and taxonomy components of feature "foo". Revert all components of feature "bar".',
  105. ),
  106. 'drupal dependencies' => array('features'),
  107. 'aliases' => array('fr'),
  108. );
  109. $items['features-revert-all'] = array(
  110. 'description' => "Revert all enabled feature module on your site.",
  111. 'arguments' => array(
  112. 'feature_exclude' => 'A space-delimited list of features to exclude from being reverted.',
  113. ),
  114. 'options' => array(
  115. 'force' => "Force revert even if Features assumes components' state are default.",
  116. ),
  117. 'drupal dependencies' => array('features'),
  118. 'aliases' => array('fr-all', 'fra'),
  119. );
  120. $items['features-diff'] = array(
  121. 'description' => "Show the difference between the default and overridden state of a feature.",
  122. 'arguments' => array(
  123. 'feature' => 'The feature in question.',
  124. ),
  125. 'options' => array(
  126. 'ctypes' => 'Comma separated list of component types to limit the output to. Defaults to all types.',
  127. 'lines' => 'Generate diffs with <n> lines of context instead of the usual two.',
  128. ),
  129. 'drupal dependencies' => array('features', 'diff'),
  130. 'aliases' => array('fd'),
  131. );
  132. return $items;
  133. }
  134. /**
  135. * Implements hook_drush_help().
  136. */
  137. function features_drush_help($section) {
  138. // If Features is enabled display the configured default export path,
  139. // otherwise just show the default.
  140. if (defined('FEATURES_DEFAULT_EXPORT_PATH')) {
  141. $path = variable_get('features_default_export_path', FEATURES_DEFAULT_EXPORT_PATH);
  142. }
  143. else {
  144. $path = 'sites/all/modules';
  145. }
  146. switch ($section) {
  147. case 'drush:features':
  148. return dt("List all the available features for your site.");
  149. case 'drush:features-export':
  150. return dt("Export a feature from your site into a module. If called with no arguments, display a list of available components. If called with a single argument, attempt to create a feature including the given component with the same name. The option '--destination=foo' may be used to specify the path (from Drupal root) where the feature should be created. The default destination is '@path'. The option '--version-set=foo' may be used to specify a version number for the feature or the option '--version-increment' may also to increment the feature's version number.", array('@path' => $path));
  151. case 'drush:features-components':
  152. return dt("List feature components matching patterns. The listing may be limited to exported/not-exported components.
  153. A component pattern consists of a source, a colon and a component. Both source and component may be a full name (as in \"dependencies\"), a shorthand (for instance \"dep\") or a pattern (like \"%denci%\").
  154. Shorthands are unique shortenings of a name. They will only match if exactly one option contains the shorthand. So in a standard installation, \"dep\" will work for dependencies, but \"user\" wont, as it matches both user_permission and user_role.
  155. Patterns uses * or % for matching multiple sources/components. Unlike shorthands, patterns must match the whole name, so \"field:%article%\" should be used to select all fields containing \"article\" (which could both be those on the node type article, as well as those fields named article). * and % are equivalent, but the latter doesn't have to be escaped in UNIX shells.
  156. Lastly, a pattern without a colon is interpreted as having \":%\" appended, for easy listing of all components of a source.
  157. ");
  158. case 'drush:features-update':
  159. return dt("Update a feature module on your site. The option '--version-set=foo' may be used to specify a version number for the feature or the option '--version-increment' may also to increment the feature's version number.");
  160. case 'drush:features-update-all':
  161. return dt("Update all feature modules on your site.");
  162. case 'drush:features-revert':
  163. return dt("Revert a feature module on your site.");
  164. case 'drush:features-revert-all':
  165. return dt("Revert all enabled feature module on your site.");
  166. case 'drush:features-diff':
  167. return dt("Show a diff of a feature module.");
  168. case 'drush:features-add':
  169. return dt("Add a component to a feature module. The option '--version-set=foo' may be used to specify a version number for the feature or the option '--version-increment' may also to increment the feature's version number.");
  170. }
  171. }
  172. /**
  173. * Get a list of all feature modules.
  174. */
  175. function drush_features_list() {
  176. $status = drush_get_option('status') ? drush_get_option('status') : 'all';
  177. if (!in_array($status, array('enabled', 'disabled', 'all'))) {
  178. return drush_set_error('', dt('!status is not valid', array('!status' => $status)));
  179. }
  180. module_load_include('inc', 'features', 'features.export');
  181. $rows = array(array(dt('Name'), dt('Feature'), dt('Status'), dt('Version'), dt('State')));
  182. // Sort the Features list before compiling the output.
  183. $features = features_get_features(NULL, TRUE);
  184. ksort($features);
  185. foreach ($features as $k => $m) {
  186. switch (features_get_storage($m->name)) {
  187. case FEATURES_DEFAULT:
  188. case FEATURES_REBUILDABLE:
  189. $storage = '';
  190. break;
  191. case FEATURES_OVERRIDDEN:
  192. $storage = dt('Overridden');
  193. break;
  194. case FEATURES_NEEDS_REVIEW:
  195. $storage = dt('Needs review');
  196. break;
  197. }
  198. if (
  199. ($m->status == 0 && ($status == 'all' || $status == 'disabled')) ||
  200. ($m->status == 1 && ($status == 'all' || $status == 'enabled'))
  201. ) {
  202. $rows[] = array(
  203. $m->info['name'],
  204. $m->name,
  205. $m->status ? dt('Enabled') : dt('Disabled'),
  206. $m->info['version'],
  207. $storage
  208. );
  209. }
  210. }
  211. drush_print_table($rows, TRUE);
  212. }
  213. /**
  214. * List components, with pattern matching.
  215. */
  216. function drush_features_components() {
  217. $args = func_get_args();
  218. $components = _drush_features_component_list();
  219. ksort($components);
  220. // If no args supplied, prompt with a list.
  221. if (empty($args)) {
  222. $types = array_keys($components);
  223. array_unshift($types, 'all');
  224. $choice = drush_choice($types, 'Enter a number to choose which component type to list.');
  225. if ($choice === FALSE) {
  226. return;
  227. }
  228. $args = ($choice == 0) ? array('*') : array($types[$choice]);
  229. }
  230. $options = array(
  231. 'provided by' => TRUE,
  232. );
  233. if (drush_get_option(array('exported', 'e'), NULL)) {
  234. $options['not exported'] = FALSE;
  235. }
  236. elseif (drush_get_option(array('not-exported', 'o'), NULL)) {
  237. $options['exported'] = FALSE;
  238. }
  239. $filtered_components = _drush_features_component_filter($components, $args, $options);
  240. if ($filtered_components){
  241. _drush_features_component_print($filtered_components);
  242. }
  243. }
  244. /**
  245. * Returns a listing of all known components, indexed by source.
  246. */
  247. function _drush_features_component_list() {
  248. $components = array();
  249. foreach (features_get_feature_components() as $source => $info) {
  250. if ($options = features_invoke($source, 'features_export_options')) {
  251. foreach ($options as $name => $title) {
  252. $components[$source][$name] = $title;
  253. }
  254. }
  255. }
  256. return $components;
  257. }
  258. /**
  259. * Filters components by patterns.
  260. */
  261. function _drush_features_component_filter($all_components, $patterns = array(), $options = array()) {
  262. $options += array(
  263. 'exported' => TRUE,
  264. 'not exported' => TRUE,
  265. 'provided by' => FALSE,
  266. );
  267. $pool = array();
  268. // Maps exported components to feature modules.
  269. $components_map = features_get_component_map();
  270. // First filter on exported state.
  271. foreach ($all_components as $source => $components) {
  272. foreach ($components as $name => $title) {
  273. $exported = sizeof($components_map[$source][$name]) > 0;
  274. if ($exported) {
  275. if ($options['exported']) {
  276. $pool[$source][$name] = $title;
  277. }
  278. }
  279. else {
  280. if ($options['not exported']) {
  281. $pool[$source][$name] = $title;
  282. }
  283. }
  284. }
  285. }
  286. $state_string = '';
  287. if (!$options['exported']) {
  288. $state_string = 'unexported';
  289. }
  290. elseif (!$options['not exported']) {
  291. $state_string = 'exported';
  292. }
  293. $selected = array();
  294. foreach ($patterns as $pattern) {
  295. // Rewrite * to %. Let users use both as wildcard.
  296. $pattern = strtr($pattern, array('*' => '%'));
  297. $sources = array();
  298. list($source_pattern, $component_pattern) = explode(':', $pattern, 2);
  299. // If source is empty, use a pattern.
  300. if ($source_pattern == '') {
  301. $source_pattern = '%';
  302. }
  303. if ($component_pattern == '') {
  304. $component_pattern = '%';
  305. }
  306. $preg_source_pattern = strtr(preg_quote($source_pattern, '/'), array('%' => '.*'));
  307. $preg_component_pattern = strtr(preg_quote($component_pattern, '/'), array('%' => '.*'));
  308. /*
  309. * If it isn't a pattern, but a simple string, we don't anchor the
  310. * pattern, this allows for abbreviating. Else, we do, as this seems more
  311. * natural for patterns.
  312. */
  313. if (strpos($source_pattern, '%') !== FALSE) {
  314. $preg_source_pattern = '^' . $preg_source_pattern . '$';
  315. }
  316. if (strpos($component_pattern, '%') !== FALSE) {
  317. $preg_component_pattern = '^' . $preg_component_pattern . '$';
  318. }
  319. $matches = array();
  320. // Find the sources.
  321. $all_sources = array_keys($pool);
  322. $matches = preg_grep('/' . $preg_source_pattern . '/', $all_sources);
  323. if (sizeof($matches) > 0) {
  324. // If we have multiple matches and the source string wasn't a
  325. // pattern, check if one of the matches is equal to the pattern, and
  326. // use that, or error out.
  327. if (sizeof($matches) > 1 and $preg_source_pattern[0] != '^') {
  328. if (in_array($source_pattern, $matches)) {
  329. $matches = array($source_pattern);
  330. }
  331. else {
  332. return drush_set_error('', dt('Ambiguous source "!source", matches !matches', array('!source' => $source_pattern, '!matches' => join(', ', $matches))));
  333. }
  334. }
  335. // Loose the indexes preg_grep preserved.
  336. $sources = array_values($matches);
  337. }
  338. else {
  339. return drush_set_error('', dt('No !state sources match "!source"', array('!state' => $state_string, '!source' => $source_pattern)));
  340. }
  341. // Now find the components.
  342. foreach ($sources as $source) {
  343. // Find the components.
  344. $all_components = array_keys($pool[$source]);
  345. // See if there's any matches.
  346. $matches = preg_grep('/' . $preg_component_pattern . '/', $all_components);
  347. if (sizeof($matches) > 0) {
  348. // If we have multiple matches and the components string wasn't a
  349. // pattern, check if one of the matches is equal to the pattern, and
  350. // use that, or error out.
  351. if (sizeof($matches) > 1 and $preg_component_pattern[0] != '^') {
  352. if (in_array($component_pattern, $matches)) {
  353. $matches = array($component_pattern);
  354. }
  355. else {
  356. return drush_set_error('', dt('Ambiguous component "!component", matches !matches', array('!component' => $component_pattern, '!matches' => join(', ', $matches))));
  357. }
  358. }
  359. if (!is_array($selected[$source])) {
  360. $selected[$source] = array();
  361. }
  362. $selected[$source] += array_intersect_key($pool[$source], array_flip($matches));
  363. }
  364. else {
  365. // No matches. If the source was a pattern, just carry on, else
  366. // error out. Allows for patterns like :*field*
  367. if ($preg_source_pattern[0] != '^') {
  368. return drush_set_error('', dt('No !state !source components match "!component"', array('!state' => $state_string, '!component' => $component_pattern, '!source' => $source)));
  369. }
  370. }
  371. }
  372. }
  373. // Lastly, provide feature module information on the selected components, if
  374. // requested.
  375. $provided_by = array();
  376. if ($options['provided by'] && $options['exported'] ) {
  377. foreach ($selected as $source => $components) {
  378. foreach ($components as $name => $title) {
  379. $exported = sizeof($components_map[$source][$name]) > 0;
  380. if ($exported) {
  381. $provided_by[$source . ':' . $name] = join(', ', $components_map[$source][$name]);
  382. }
  383. }
  384. }
  385. }
  386. return array(
  387. 'components' => $selected,
  388. 'sources' => $provided_by,
  389. );
  390. }
  391. /**
  392. * Prints a list of filtered components.
  393. */
  394. function _drush_features_component_print($filtered_components) {
  395. $rows = array(array(dt('Available sources')));
  396. foreach ($filtered_components['components'] as $source => $components) {
  397. foreach ($components as $name => $value) {
  398. $row = array($source .':'. $name);
  399. if (isset($filtered_components['sources'][$source .':'. $name])) {
  400. $row[] = dt('Provided by') . ': ' . $filtered_components['sources'][$source .':'. $name];
  401. }
  402. $rows[] = $row;
  403. }
  404. }
  405. drush_print_table($rows, TRUE);
  406. }
  407. /**
  408. * Add a component to a features module, or create a new module with
  409. * the selected components.
  410. */
  411. function drush_features_export() {
  412. if ($args = func_get_args()) {
  413. $module = array_shift($args);
  414. if (empty($args)) {
  415. return drush_set_error('', 'No components supplied.');
  416. }
  417. $components = _drush_features_component_list();
  418. $options = array(
  419. 'exported' => FALSE,
  420. );
  421. $filtered_components = _drush_features_component_filter($components, $args, $options);
  422. $items = $filtered_components['components'];
  423. if (empty($items)) {
  424. return drush_set_error('', 'No components to add.');
  425. }
  426. $items = array_map('array_keys', $items);
  427. if (($feature = features_load_feature($module, TRUE)) && module_exists($module)) {
  428. module_load_include('inc', 'features', 'features.export');
  429. _features_populate($items, $feature->info, $feature->name);
  430. _drush_features_export($feature->info, $feature->name, dirname($feature->filename));
  431. }
  432. elseif ($feature) {
  433. _features_drush_set_error($module, 'FEATURES_FEATURE_NOT_ENABLED');
  434. }
  435. else {
  436. // Same logic as in _drush_features_export. Should be refactored.
  437. $destination = drush_get_option(array('destination'), variable_get('features_default_export_path', FEATURES_DEFAULT_EXPORT_PATH));
  438. $directory = isset($directory) ? $directory : $destination . '/' . $module;
  439. drush_print(dt('Will create a new module in !dir', array('!dir' => $directory)));
  440. if (!drush_confirm(dt('Do you really want to continue?'))) {
  441. drush_die('Aborting.');
  442. }
  443. $export = _drush_features_generate_export($items, $module);
  444. _features_populate($items, $export[info], $export[name]);
  445. _drush_features_export($export['info'], $module, $directory);
  446. }
  447. }
  448. else {
  449. return drush_set_error('', 'No feature name given.');
  450. }
  451. }
  452. /**
  453. * Add a component to a features module
  454. * the selected components.
  455. *
  456. * This is DEPRECATED, but keeping it around for a bit longer for user migration
  457. */
  458. function drush_features_add() {
  459. drush_print(dt('features-add is DEPRECATED.'));
  460. drush_print(dt('Calling features-export instead.'));
  461. drush_features_export();
  462. }
  463. /**
  464. * Update an existing feature module.
  465. */
  466. function drush_features_update() {
  467. if ($args = func_get_args()) {
  468. foreach ($args as $module) {
  469. if (($feature = features_load_feature($module, TRUE)) && module_exists($module)) {
  470. _drush_features_export($feature->info, $feature->name, dirname($feature->filename));
  471. }
  472. elseif ($feature) {
  473. _features_drush_set_error($module, 'FEATURES_FEATURE_NOT_ENABLED');
  474. }
  475. else {
  476. _features_drush_set_error($module);
  477. }
  478. }
  479. }
  480. else {
  481. // By default just show contexts that are available.
  482. $rows = array(array(dt('Available features')));
  483. foreach (features_get_features(NULL, TRUE) as $name => $info) {
  484. $rows[] = array($name);
  485. }
  486. drush_print_table($rows, TRUE);
  487. }
  488. }
  489. /**
  490. * Update all enabled features. Optionally pass in a list of features to
  491. * exclude from being updated.
  492. */
  493. function drush_features_update_all() {
  494. $features_to_update = array();
  495. $features_to_exclude = func_get_args();
  496. foreach (features_get_features() as $module) {
  497. if ($module->status && !in_array($module->name, $features_to_exclude)) {
  498. $features_to_update[] = $module->name;
  499. }
  500. }
  501. $dt_args = array('!modules' => implode(', ', $features_to_update));
  502. drush_print(dt('The following modules will be updated: !modules', $dt_args));
  503. if (!drush_confirm(dt('Do you really want to continue?'))) {
  504. return drush_user_abort('Aborting.');
  505. }
  506. // If we got here, set affirmative to TRUE, so that the user doesn't have to
  507. // confirm each and every feature. Start off by storing the current value,
  508. // so we can set it back afteward.
  509. $skip_confirmation = drush_get_context('DRUSH_AFFIRMATIVE');
  510. drush_set_context('DRUSH_AFFIRMATIVE', TRUE);
  511. // Now update all the features.
  512. drush_invoke('features-update', $features_to_update);
  513. // Now set it back as it was, in case other commands are called after this.
  514. drush_set_context('DRUSH_AFFIRMATIVE', $skip_confirmation);
  515. }
  516. /**
  517. * Write a module to the site dir.
  518. *
  519. * @param $info
  520. * The feature info associative array.
  521. * @param $module_name
  522. * Optional. The name for the exported module.
  523. */
  524. function _drush_features_export($info, $module_name = NULL, $directory = NULL) {
  525. $root = drush_get_option(array('r', 'root'), drush_locate_root());
  526. $skip_confirmation = drush_get_context('DRUSH_AFFIRMATIVE');
  527. if ($root) {
  528. $destination = drush_get_option(array('destination'), variable_get('features_default_export_path', FEATURES_DEFAULT_EXPORT_PATH));
  529. $directory = isset($directory) ? $directory : $destination . '/' . $module_name;
  530. if (is_dir($directory)) {
  531. // If we aren't skipping confirmation and the directory already exists,
  532. // prompt the user. This message most make sense for but fe and fu.
  533. if (!$skip_confirmation && !drush_confirm(dt('Module located at !dir will be updated. Do you want to continue?', array('!dir' => $directory)))) {
  534. drush_die('Aborting.');
  535. }
  536. }
  537. else {
  538. drush_op('mkdir', $directory);
  539. }
  540. if (is_dir($directory)) {
  541. drupal_flush_all_caches();
  542. $export = _drush_features_generate_export($info, $module_name);
  543. $files = features_export_render($export, $module_name, TRUE);
  544. foreach ($files as $extension => $file_contents) {
  545. if (!in_array($extension, array('module', 'info'))) {
  546. $extension .= '.inc';
  547. }
  548. drush_op('file_put_contents', "{$directory}/{$module_name}.$extension", $file_contents);
  549. }
  550. drush_log(dt("Created module: !module in !directory", array('!module' => $module_name, '!directory' => $directory)), 'ok');
  551. }
  552. else {
  553. drush_die(dt('Couldn\'t create directory !directory', array('!directory' => $directory)));
  554. }
  555. }
  556. else {
  557. drush_die(dt('Couldn\'t locate site root'));
  558. }
  559. }
  560. /**
  561. * Helper function for _drush_feature_export.
  562. *
  563. * @param $info
  564. * The feature info associative array.
  565. * @param $module_name
  566. * Optional. The name for the exported module.
  567. */
  568. function _drush_features_generate_export(&$info, &$module_name) {
  569. module_load_include('inc', 'features', 'features.export');
  570. $export = features_populate($info, $module_name);
  571. if (!features_load_feature($module_name)) {
  572. $export['name'] = $module_name;
  573. }
  574. // Set the feature version if the --version-set or --version-increment option is passed.
  575. if ($version = drush_get_option(array('version-set'))) {
  576. preg_match('/^(?P<core>\d+\.x)-(?P<major>\d+)\.(?P<patch>\d+)-?(?P<extra>\w+)?$/', $version, $matches);
  577. if (!isset($matches['core'], $matches['major'])) {
  578. drush_die(dt('Please enter a valid version with core and major version number. Example: !example', array('!example' => '7.x-1.0')));
  579. }
  580. $export['version'] = $version;
  581. }
  582. elseif ($version = drush_get_option(array('version-increment'))) {
  583. // Determine current version and increment it.
  584. $export_load = features_export_prepare($export, $module_name);
  585. $version = $export_load['version'];
  586. $version_explode = explode('.', $version);
  587. $version_minor = array_pop($version_explode);
  588. // Increment minor version number if numeric or not a dev release.
  589. if (is_numeric($version_minor) || strpos($version_minor, 'dev') !== (strlen($version_minor) - 3)) {
  590. // Check for prefixed versions (alpha, beta, rc).
  591. if (ctype_digit($version_minor)) {
  592. ++$version_minor;
  593. }
  594. else {
  595. // Split version number parts.
  596. $pattern = '/([0-9]-[a-z]+([0-9])+)/';
  597. $matches = array();
  598. preg_match($pattern, $version_minor, $matches);
  599. $number = array_pop($matches);
  600. ++$number;
  601. $pattern = '/[0-9]+$/';
  602. $version_minor = preg_replace($pattern, $number, $version_minor);
  603. }
  604. }
  605. array_push($version_explode, $version_minor);
  606. // Rebuild version string.
  607. $version = implode('.', $version_explode);
  608. $export['version'] = $version;
  609. }
  610. return $export;
  611. }
  612. /**
  613. * Revert a feature to it's code definition.
  614. * Optionally accept a list of components to revert.
  615. */
  616. function drush_features_revert() {
  617. if ($args = func_get_args()) {
  618. module_load_include('inc', 'features', 'features.export');
  619. features_include();
  620. // Determine if revert should be forced.
  621. $force = drush_get_option('force');
  622. // Determine if -y was supplied. If so, we can filter out needless output
  623. // from this command.
  624. $skip_confirmation = drush_get_context('DRUSH_AFFIRMATIVE');
  625. // Parse list of arguments.
  626. $modules = array();
  627. foreach ($args as $arg) {
  628. $arg = explode('.', $arg);
  629. $module = array_shift($arg);
  630. $component = array_shift($arg);
  631. if (isset($module)) {
  632. if (empty($component)) {
  633. // If we received just a feature name, this means that we need all of it's components.
  634. $modules[$module] = TRUE;
  635. }
  636. elseif ($modules[$module] !== TRUE) {
  637. if (!isset($modules[$module])) {
  638. $modules[$module] = array();
  639. }
  640. $modules[$module][] = $component;
  641. }
  642. }
  643. }
  644. // Process modules.
  645. foreach ($modules as $module => $components_needed) {
  646. $dt_args['@module'] = $module;
  647. if (($feature = features_load_feature($module, TRUE)) && module_exists($module)) {
  648. $components = array();
  649. // Forcefully revert all components of a feature.
  650. if ($force) {
  651. foreach (array_keys($feature->info['features']) as $component) {
  652. if (features_hook($component, 'features_revert')) {
  653. $components[] = $component;
  654. }
  655. }
  656. }
  657. // Only revert components that are detected to be Overridden/Needs review/rebuildable.
  658. else {
  659. $states = features_get_component_states(array($feature->name), FALSE);
  660. foreach ($states[$feature->name] as $component => $state) {
  661. $revertable_states = array(FEATURES_OVERRIDDEN, FEATURES_NEEDS_REVIEW, FEATURES_REBUILDABLE);
  662. if (in_array($state, $revertable_states) && features_hook($component, 'features_revert')) {
  663. $components[] = $component;
  664. }
  665. }
  666. }
  667. if (!empty($components_needed) && is_array($components_needed)) {
  668. $components = array_intersect($components, $components_needed);
  669. }
  670. if (empty($components)) {
  671. drush_log(dt('Current state already matches defaults, aborting.'), 'ok');
  672. }
  673. else {
  674. foreach ($components as $component) {
  675. $dt_args['@component'] = $component;
  676. $confirmation_message = 'Do you really want to revert @module.@component?';
  677. if ($skip_confirmation || drush_confirm(dt($confirmation_message, $dt_args))) {
  678. if (features_feature_is_locked($module, $component)) {
  679. drush_log(dt('Skipping locked @module.@component.', $dt_args), 'ok');
  680. }
  681. else {
  682. features_revert(array($module => array($component)));
  683. drush_log(dt('Reverted @module.@component.', $dt_args), 'ok');
  684. }
  685. }
  686. else {
  687. drush_log(dt('Skipping @module.@component.', $dt_args), 'ok');
  688. }
  689. }
  690. }
  691. }
  692. elseif ($feature) {
  693. _features_drush_set_error($module, 'FEATURES_FEATURE_NOT_ENABLED');
  694. }
  695. else {
  696. _features_drush_set_error($module);
  697. }
  698. }
  699. }
  700. else {
  701. drush_features_list();
  702. return;
  703. }
  704. }
  705. /**
  706. * Revert all enabled features to their definitions in code.
  707. *
  708. * @param ...
  709. * (Optional) A list of features to exclude from being reverted.
  710. */
  711. function drush_features_revert_all() {
  712. module_load_include('inc', 'features', 'features.export');
  713. $force = drush_get_option('force');
  714. $features_to_exclude = func_get_args();
  715. $features_to_revert = array();
  716. foreach (features_get_features(NULL, TRUE) as $module) {
  717. if ($module->status && !in_array($module->name, $features_to_exclude)) {
  718. // If forced, add module regardless of status.
  719. if ($force) {
  720. $features_to_revert[] = $module->name;
  721. }
  722. else {
  723. switch (features_get_storage($module->name)) {
  724. case FEATURES_OVERRIDDEN:
  725. case FEATURES_NEEDS_REVIEW:
  726. case FEATURES_REBUILDABLE:
  727. $features_to_revert[] = $module->name;
  728. break;
  729. }
  730. }
  731. }
  732. }
  733. if ($features_to_revert) {
  734. $dt_args = array('!modules' => implode(', ', $features_to_revert));
  735. drush_print(dt('The following modules will be reverted: !modules', $dt_args));
  736. // Confirm that the user would like to continue. If not, simply abort.
  737. if (!drush_confirm(dt('Do you really want to continue?'))) {
  738. return drush_user_abort('Aborting.');
  739. }
  740. drush_invoke('features-revert', $features_to_revert);
  741. }
  742. else {
  743. drush_log(dt('Current state already matches defaults, aborting.'), 'ok');
  744. }
  745. }
  746. /**
  747. * Show the diff of a feature module.
  748. */
  749. function drush_features_diff() {
  750. if (!$args = func_get_args()) {
  751. drush_features_list();
  752. return;
  753. }
  754. $module = $args[0];
  755. $filter_ctypes = drush_get_option("ctypes");
  756. if ($filter_ctypes) {
  757. $filter_ctypes = explode(',', $filter_ctypes);
  758. }
  759. $feature = features_load_feature($module);
  760. if (!module_exists($module)) {
  761. drush_log(dt('No such feature is enabled: ' . $module), 'error');
  762. return;
  763. }
  764. module_load_include('inc', 'features', 'features.export');
  765. $overrides = features_detect_overrides($feature);
  766. if (empty($overrides)) {
  767. drush_log(dt('Feature is in its default state. No diff needed.'), 'ok');
  768. return;
  769. }
  770. module_load_include('inc', 'diff', 'diff.engine');
  771. if (!class_exists('DiffFormatter')) {
  772. if (drush_confirm(dt('It seems that the Diff module is not available. Would you like to download and enable it?'))) {
  773. // Download it if it's not already here.
  774. $project_info = drush_get_projects();
  775. if (empty($project_info['diff']) && !drush_invoke('dl', array('diff'))) {
  776. return drush_set_error(dt('Diff module could not be downloaded.'));
  777. }
  778. if (!drush_invoke('en', array('diff'))) {
  779. return drush_set_error(dt('Diff module could not be enabled.'));
  780. }
  781. }
  782. else {
  783. return drush_set_error(dt('Diff module is not enabled.'));
  784. }
  785. // If we're still here, now we can include the diff.engine again.
  786. module_load_include('inc', 'diff', 'diff.engine');
  787. }
  788. $lines = (int) drush_get_option('lines');
  789. $lines = $lines > 0 ? $lines : 2;
  790. $formatter = new DiffFormatter();
  791. $formatter->leading_context_lines = $lines;
  792. $formatter->trailing_context_lines = $lines;
  793. $formatter->show_header = FALSE;
  794. if (drush_get_context('DRUSH_NOCOLOR')) {
  795. $red = $green = "%s";
  796. }
  797. else {
  798. $red = "\033[31;40m\033[1m%s\033[0m";
  799. $green = "\033[0;32;40m\033[1m%s\033[0m";
  800. }
  801. // Print key for colors
  802. drush_print(dt('Legend: '));
  803. drush_print(sprintf($red, dt('Code: drush features-revert will remove the overrides.')));
  804. drush_print(sprintf($green, dt('Overrides: drush features-update will update the exported feature with the displayed overrides')));
  805. drush_print();
  806. if ($filter_ctypes) {
  807. $overrides = array_intersect_key($overrides, array_flip($filter_ctypes));
  808. }
  809. foreach ($overrides as $component => $items) {
  810. $diff = new Diff(explode("\n", $items['default']), explode("\n", $items['normal']));
  811. drush_print();
  812. drush_print(dt("Component type: !component", array('!component' => $component)));
  813. $rows = explode("\n", $formatter->format($diff));
  814. foreach ($rows as $row) {
  815. if (strpos($row, '>') === 0) {
  816. drush_print(sprintf($green, $row));
  817. }
  818. elseif (strpos($row, '<') === 0) {
  819. drush_print(sprintf($red, $row));
  820. }
  821. else {
  822. drush_print($row);
  823. }
  824. }
  825. }
  826. }
  827. /**
  828. * Helper function to call drush_set_error().
  829. *
  830. * @param $feature
  831. * The string name of the feature.
  832. * @param $error
  833. * A text string identifying the type of error.
  834. * @return
  835. * FALSE. See drush_set_error().
  836. */
  837. function _features_drush_set_error($feature, $error = '') {
  838. $args = array('!feature' => $feature);
  839. switch ($error) {
  840. case 'FEATURES_FEATURE_NOT_ENABLED':
  841. $message = 'The feature !feature is not enabled.';
  842. break;
  843. case 'FEATURES_COMPONENT_NOT_FOUND':
  844. $message = 'The given component !feature could not be found.';
  845. break;
  846. default:
  847. $error = 'FEATURES_FEATURE_NOT_FOUND';
  848. $message = 'The feature !feature could not be found.';
  849. }
  850. return drush_set_error($error, dt($message, $args));
  851. }