features.drush.inc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. <?php
  2. /**
  3. * @file
  4. * Features module drush integration.
  5. */
  6. use Drupal\features\ConfigurationItem;
  7. use Drupal\features\FeaturesManagerInterface;
  8. use Drupal\features\Plugin\FeaturesGeneration\FeaturesGenerationWrite;
  9. use Drupal\Component\Diff\DiffFormatter;
  10. /**
  11. * Implements hook_drush_command().
  12. */
  13. function features_drush_command() {
  14. $items = array();
  15. $items['features-status'] = array(
  16. 'description' => 'Display current Features settings.',
  17. 'aliases' => array('fs'),
  18. );
  19. $items['features-list-packages'] = array(
  20. 'description' => 'Display a list of all existing features and packages available to be generated. If a package name is provided as an argument, then all of the configuration objects assigned to that package will be listed.',
  21. 'examples' => array(
  22. "drush features-list-packages" => 'Display a list of all existing featurea and packages available to be generated.',
  23. "drush features-list-packages 'example_article'" => "Display a list of all configuration objects assigned to the 'example_article' package.",
  24. ),
  25. 'arguments' => array(
  26. 'package' => 'The package to list. Optional; if specified, lists all configuration objects assigned to that package. If no package is specified, lists all of the features.',
  27. ),
  28. 'outputformat' => array(
  29. 'default' => 'table',
  30. 'pipe-format' => 'list',
  31. 'field-labels' => array(
  32. 'name' => 'Name',
  33. 'machine_name' => 'Machine name',
  34. 'status' => 'Status',
  35. 'version' => 'Version',
  36. 'state' => 'State',
  37. 'object' => 'Configuration object',
  38. ),
  39. 'output-data-type' => 'format-table',
  40. ),
  41. 'aliases' => array('fl'),
  42. );
  43. $items['features-import-all'] = array(
  44. 'description' => 'Import module config from all installed features.',
  45. 'examples' => array(
  46. "drush features-import-all" => 'Import module config from all installed features.',
  47. ),
  48. 'aliases' => array('fra', 'fia', 'fim-all'),
  49. );
  50. $items['features-export'] = array(
  51. 'description' => "Export the configuration on your site into a custom module.",
  52. 'arguments' => array(
  53. 'package' => 'A space delimited list of features to export.',
  54. ),
  55. 'options' => array(
  56. 'add-profile' => 'Package features into an install profile.',
  57. ),
  58. 'examples' => array(
  59. "drush features-export" => 'Export all available packages.',
  60. "drush features-export example_article example_page" => "Export the example_article and example_page packages.",
  61. "drush features-export --add-profile" => "Export all available packages and add them to an install profile.",
  62. ),
  63. // Add previous "fu" alias for compatibility.
  64. 'aliases' => array('fex', 'fu', 'fua', 'fu-all'),
  65. );
  66. $items['features-add'] = array(
  67. 'description' => "Add a config item to a feature package.",
  68. 'arguments' => array(
  69. 'feature' => 'Feature package to export and add config to.',
  70. 'components' => 'Patterns of config to add, see features-components for the format of patterns.',
  71. ),
  72. 'aliases' => array('fa', 'fe'),
  73. );
  74. $items['features-components'] = array(
  75. 'description' => 'List features components.',
  76. 'arguments' => array(
  77. 'patterns' => 'The features components type to list. Omit this argument to list all components.',
  78. ),
  79. 'options' => array(
  80. 'exported' => array(
  81. 'description' => 'Show only components that have been exported.',
  82. ),
  83. 'not-exported' => array(
  84. 'description' => 'Show only components that have not been exported.',
  85. ),
  86. ),
  87. 'aliases' => array('fc'),
  88. );
  89. $items['features-diff'] = array(
  90. 'description' => "Show the difference between the active config and the default config stored in a feature package.",
  91. 'arguments' => array(
  92. 'feature' => 'The feature in question.',
  93. ),
  94. 'options' => array(
  95. 'ctypes' => 'Comma separated list of component types to limit the output to. Defaults to all types.',
  96. 'lines' => 'Generate diffs with <n> lines of context instead of the usual two.',
  97. ),
  98. 'aliases' => array('fd'),
  99. );
  100. $items['features-import'] = array(
  101. 'description' => "Import a module config into your site.",
  102. 'arguments' => array(
  103. 'feature' => 'A space delimited list of features or feature:component pairs to import.',
  104. ),
  105. 'options' => array(
  106. 'force' => "Force import even if config is not overridden.",
  107. ),
  108. 'examples' => array(
  109. 'drush features-import foo:node.type.page foo:taxonomy.vocabulary.tags bar' => 'Import node and taxonomy config of feature "foo". Import all config of feature "bar".',
  110. ),
  111. 'aliases' => array('fim', 'fr'),
  112. );
  113. foreach ($items as $name => &$item) {
  114. $item['options']['bundle'] = array(
  115. 'description' => 'Use a specific bundle namespace.',
  116. );
  117. }
  118. return $items;
  119. }
  120. /**
  121. * Applies global options for Features drush commands.
  122. *
  123. * The option --name="bundle_name" sets the bundle namespace.
  124. *
  125. * @return \Drupal\features\FeaturesAssignerInterface
  126. */
  127. function _drush_features_options() {
  128. /** @var \Drupal\features\FeaturesAssignerInterface $assigner */
  129. $assigner = \Drupal::service('features_assigner');
  130. $bundle_name = drush_get_option('bundle');
  131. if (!empty($bundle_name)) {
  132. $bundle = $assigner->applyBundle($bundle_name);
  133. if ($bundle->getMachineName() != $bundle_name) {
  134. drush_log(dt('Bundle @name not found. Using default.', array('@name' => $bundle_name)), 'warning');
  135. }
  136. }
  137. else {
  138. $assigner->assignConfigPackages();
  139. }
  140. return $assigner;
  141. }
  142. /**
  143. * Provides Drush command callback for features-status.
  144. */
  145. function drush_features_status() {
  146. $args = func_get_args();
  147. $assigner = _drush_features_options();
  148. /** @var \Drupal\features\FeaturesManagerInterface $manager */
  149. $manager = \Drupal::service('features.manager');
  150. $current_bundle = $assigner->getBundle();
  151. $export_settings = $manager->getExportSettings();
  152. $methods = $assigner->getEnabledAssigners();
  153. if ($current_bundle->isDefault()) {
  154. drush_print(dt('Current bundle: none'));
  155. }
  156. else {
  157. drush_print(dt('Current bundle: @name (@machine_name)',
  158. array(
  159. '@name' => $current_bundle->getName(),
  160. '@machine_name' => $current_bundle->getMachineName(),
  161. )));
  162. }
  163. drush_print(dt('Export folder: @folder', array('@folder' => $export_settings['folder'])));
  164. $dt_args = array('@methods' => implode(', ', array_keys($methods)));
  165. drush_print(dt('The following assignment methods are enabled:'));
  166. drush_print(dt(' @methods', $dt_args));
  167. if (!empty($args)) {
  168. $config = $manager->getConfigCollection();
  169. if (count($args) > 1) {
  170. print_r(array_keys($config));
  171. }
  172. else {
  173. print_r($config[$args[0]]);
  174. }
  175. }
  176. }
  177. /**
  178. * Drush command callback for features-list-packages.
  179. *
  180. * @param string $package_name
  181. * (optional) The package name.
  182. *
  183. * @return array|bool
  184. */
  185. function drush_features_list_packages($package_name = '') {
  186. $assigner = _drush_features_options();
  187. $current_bundle = $assigner->getBundle();
  188. $namespace = $current_bundle->isDefault() ? '' : $current_bundle->getMachineName();
  189. /** @var \Drupal\features\FeaturesManagerInterface $manager */
  190. $manager = \Drupal::service('features.manager');
  191. $packages = $manager->getPackages();
  192. $packages = $manager->filterPackages($packages, $namespace);
  193. $result = array();
  194. // If no package was specified, list all packages.
  195. if (empty($package_name)) {
  196. drush_hide_output_fields(array('object'));
  197. foreach ($packages as $package) {
  198. $overrides = $manager->detectOverrides($package);
  199. $state = $package->getState();
  200. if (!empty($overrides) && ($package->getStatus() != FeaturesManagerInterface::STATUS_NO_EXPORT)) {
  201. $state = FeaturesManagerInterface::STATE_OVERRIDDEN;
  202. }
  203. $result[$package->getMachineName()] = array(
  204. 'name' => $package->getName(),
  205. 'machine_name' => $package->getMachineName(),
  206. 'status' => $manager->statusLabel($package->getStatus()),
  207. 'version' => $package->getVersion(),
  208. 'state' => ($state != FeaturesManagerInterface::STATE_DEFAULT)
  209. ? $manager->stateLabel($state)
  210. : '',
  211. );
  212. }
  213. return $result;
  214. }
  215. // If a valid package was listed, list its configuration.
  216. else {
  217. foreach ($packages as $package) {
  218. if ($package->getMachineName() == $package_name) {
  219. drush_hide_output_fields(array(
  220. 'machine_name',
  221. 'name',
  222. 'status',
  223. 'version',
  224. 'state',
  225. ));
  226. foreach ($package->getConfig() as $item_name) {
  227. $result[$item_name] = array(
  228. 'object' => $item_name,
  229. );
  230. }
  231. return $result;
  232. }
  233. }
  234. }
  235. // If no matching package found, return an error.
  236. drush_log(dt('Package "@package" not found.', array('@package' => $package_name)), 'warning');
  237. return FALSE;
  238. }
  239. /**
  240. * Drush command callback for features-import-all.
  241. *
  242. */
  243. function drush_features_import_all() {
  244. $assigner = _drush_features_options();
  245. $current_bundle = $assigner->getBundle();
  246. $namespace = $current_bundle->isDefault() ? '' : $current_bundle->getMachineName();
  247. /** @var \Drupal\features\FeaturesManagerInterface $manager */
  248. $manager = \Drupal::service('features.manager');
  249. $packages = $manager->getPackages();
  250. $packages = $manager->filterPackages($packages, $namespace);
  251. $overridden = array();
  252. foreach ($packages as $package) {
  253. $overrides = $manager->detectOverrides($package);
  254. $missing = $manager->detectMissing($package);
  255. if ((!empty($missing) || !empty($overrides)) && ($package->getStatus() == FeaturesManagerInterface::STATUS_INSTALLED)) {
  256. $overridden[] = $package->getMachineName();
  257. }
  258. }
  259. if (!empty($overridden)) {
  260. call_user_func_array('drush_features_import', $overridden);
  261. }
  262. else {
  263. drush_log(dt('Current state already matches active config, aborting.'), 'ok');
  264. }
  265. }
  266. /**
  267. * Provides Drush command callback for features-export.
  268. */
  269. function drush_features_export($packages = NULL) {
  270. $packages = func_get_args();
  271. $assigner = _drush_features_options();
  272. /** @var \Drupal\features\FeaturesManagerInterface $manager */
  273. $manager = \Drupal::service('features.manager');
  274. /** @var \Drupal\features\FeaturesGeneratorInterface $generator */
  275. $generator = \Drupal::service('features_generator');
  276. $current_bundle = $assigner->getBundle();
  277. if (drush_get_option('add-profile')) {
  278. if ($current_bundle->isDefault) {
  279. return drush_set_error('', dt("Must specify a profile name with --name"));
  280. }
  281. $current_bundle->setIsProfile(TRUE);
  282. }
  283. $all_packages = $manager->getPackages();
  284. foreach ($packages as $name) {
  285. if (!isset($all_packages[$name])) {
  286. return drush_set_error('', dt("The package @name does not exist.", array('@name' => $name)));
  287. }
  288. }
  289. if (empty($packages)) {
  290. $packages = $all_packages;
  291. $dt_args = array('@modules' => implode(', ', array_keys($packages)));
  292. drush_print(dt('The following extensions will be exported: @modules', $dt_args));
  293. if (!drush_confirm(dt('Do you really want to continue?'))) {
  294. return drush_user_abort('Aborting.');
  295. }
  296. }
  297. // If any packages exist, confirm before overwriting.
  298. if ($existing_packages = $manager->listPackageDirectories($packages, $current_bundle)) {
  299. foreach ($existing_packages as $name => $directory) {
  300. drush_print(dt("The extension @name already exists at @directory.", array('@name' => $name, '@directory' => $directory)));
  301. }
  302. // Apparently, format_plural is not always available.
  303. if (count($existing_packages) == 1) {
  304. $message = dt('Would you like to overwrite it?');
  305. }
  306. else {
  307. $message = dt('Would you like to overwrite them?');
  308. }
  309. if (!drush_confirm($message)) {
  310. return drush_user_abort();
  311. }
  312. }
  313. // Use the write generation method.
  314. $method_id = FeaturesGenerationWrite::METHOD_ID;
  315. $result = $generator->generatePackages($method_id, $current_bundle, $packages);
  316. foreach ($result as $message) {
  317. $type = $message['success'] ? 'success' : 'error';
  318. drush_log($message['message'], $message['variables'], $type);
  319. }
  320. }
  321. /**
  322. * Adds a component to a features module.
  323. *
  324. * @param
  325. * The selected components.
  326. */
  327. function drush_features_add() {
  328. if ($args = func_get_args()) {
  329. $assigner = _drush_features_options();
  330. /** @var \Drupal\features\FeaturesManagerInterface $manager */
  331. $manager = \Drupal::service('features.manager');
  332. /** @var \Drupal\features\FeaturesGeneratorInterface $generator */
  333. $generator = \Drupal::service('features_generator');
  334. $current_bundle = $assigner->getBundle();
  335. $module = array_shift($args);
  336. if (empty($args)) {
  337. return drush_set_error('', 'No components supplied.');
  338. }
  339. $components = _drush_features_component_list();
  340. $options = array(
  341. 'exported' => FALSE,
  342. );
  343. $filtered_components = _drush_features_component_filter($components, $args, $options);
  344. $items = $filtered_components['components'];
  345. if (empty($items)) {
  346. return drush_set_error('', 'No components to add.');
  347. }
  348. $packages = array($module);
  349. // If any packages exist, confirm before overwriting.
  350. if ($existing_packages = $manager->listPackageDirectories($packages)) {
  351. foreach ($existing_packages as $name => $directory) {
  352. drush_print(dt("The extension @name already exists at @directory.", array('@name' => $name, '@directory' => $directory)));
  353. }
  354. // Apparently, format_plural is not always available.
  355. if (count($existing_packages) == 1) {
  356. $message = dt('Would you like to overwrite it?');
  357. }
  358. else {
  359. $message = dt('Would you like to overwrite them?');
  360. }
  361. if (!drush_confirm($message)) {
  362. return drush_user_abort();
  363. }
  364. }
  365. else {
  366. $package = $manager->initPackage($module, NULL, '', 'module', $current_bundle);
  367. list($full_name, $path) = $manager->getExportInfo($package, $current_bundle);
  368. drush_print(dt('Will create a new extension @name in @directory', array('@name' => $full_name, '@directory' => $path)));
  369. if (!drush_confirm(dt('Do you really want to continue?'))) {
  370. drush_die('Aborting.');
  371. }
  372. }
  373. $config = _drush_features_build_config($items);
  374. $manager->assignConfigPackage($module, $config);
  375. // Use the write generation method.
  376. $method_id = FeaturesGenerationWrite::METHOD_ID;
  377. $result = $generator->generatePackages($method_id, $current_bundle, $packages);
  378. foreach ($result as $message) {
  379. $type = $message['success'] ? 'success' : 'error';
  380. drush_log($message['message'], $message['variables'], $type);
  381. }
  382. }
  383. else {
  384. return drush_set_error('', 'No feature name given.');
  385. }
  386. }
  387. /**
  388. * Lists components, with pattern matching.
  389. */
  390. function drush_features_components() {
  391. $args = func_get_args();
  392. _drush_features_options();
  393. $components = _drush_features_component_list();
  394. ksort($components);
  395. // If no args supplied, prompt with a list.
  396. if (empty($args)) {
  397. $types = array_keys($components);
  398. array_unshift($types, 'all');
  399. $choice = drush_choice($types, 'Enter a number to choose which component type to list.');
  400. if ($choice === FALSE) {
  401. return;
  402. }
  403. $args = ($choice == 0) ? array('*') : array($types[$choice]);
  404. }
  405. $options = array(
  406. 'provided by' => TRUE,
  407. );
  408. if (drush_get_option(array('exported', 'e'), NULL)) {
  409. $options['not exported'] = FALSE;
  410. }
  411. elseif (drush_get_option(array('not-exported', 'o'), NULL)) {
  412. $options['exported'] = FALSE;
  413. }
  414. $filtered_components = _drush_features_component_filter($components, $args, $options);
  415. if ($filtered_components) {
  416. _drush_features_component_print($filtered_components);
  417. }
  418. }
  419. /**
  420. * Lists the differences in the package config vs the active store.
  421. *
  422. * @param string $package
  423. * The machine name of a package.
  424. */
  425. function drush_features_diff() {
  426. if (!$args = func_get_args()) {
  427. drush_print_table(drush_features_list_packages());
  428. return;
  429. }
  430. /** @var \Drupal\features\FeaturesManagerInterface $manager */
  431. $manager = \Drupal::service('features.manager');
  432. /** @var \Drupal\features\FeaturesAssignerInterface $assigner */
  433. $assigner = \Drupal::service('features_assigner');
  434. $assigner->assignConfigPackages();
  435. $module = $args[0];
  436. $filter_ctypes = drush_get_option("ctypes");
  437. if ($filter_ctypes) {
  438. $filter_ctypes = explode(',', $filter_ctypes);
  439. }
  440. $feature = $manager->loadPackage($module, TRUE);
  441. if (empty($feature)) {
  442. drush_log(dt('No such feature is available: @module', array('@module' => $module)), 'error');
  443. return;
  444. }
  445. $lines = drush_get_option('lines');
  446. $lines = isset($lines) ? $lines : 2;
  447. $formatter = new DiffFormatter();
  448. $formatter->leading_context_lines = $lines;
  449. $formatter->trailing_context_lines = $lines;
  450. $formatter->show_header = FALSE;
  451. if (drush_get_context('DRUSH_NOCOLOR')) {
  452. $red = $green = "%s";
  453. }
  454. else {
  455. $red = "\033[31;40m\033[1m%s\033[0m";
  456. $green = "\033[0;32;40m\033[1m%s\033[0m";
  457. }
  458. $overrides = $manager->detectOverrides($feature);
  459. $missing = $manager->reorderMissing($manager->detectMissing($feature));
  460. $overrides = array_merge($overrides, $missing);
  461. if (empty($overrides)) {
  462. drush_print(dt('Active config matches stored config for @module.', array('@module' => $module)));
  463. }
  464. else {
  465. /** @var \Drupal\config_update\ConfigDiffInterface $config_diff */
  466. $config_diff = \Drupal::service('config_update.config_diff');
  467. /** @var \Drupal\Core\Config\StorageInterface $active_storage */
  468. $active_storage = \Drupal::service('config.storage');
  469. // Print key for colors.
  470. drush_print(dt('Legend: '));
  471. drush_print(sprintf($red, dt('Code: drush features-import will replace the active config with the displayed code.')));
  472. drush_print(sprintf($green, dt('Active: drush features-export will update the exported feature with the displayed active config')));
  473. foreach ($overrides as $name) {
  474. $message = '';
  475. if (in_array($name, $missing)) {
  476. $message = sprintf($red, t('(missing from active)'));
  477. $extension = array();
  478. }
  479. else {
  480. $active = $manager->getActiveStorage()->read($name);
  481. $extension = $manager->getExtensionStorages()->read($name);
  482. if (empty($extension)) {
  483. $extension = array();
  484. $message = sprintf($green, t('(not exported)'));
  485. }
  486. $diff = $config_diff->diff($extension, $active);
  487. $rows = explode("\n", $formatter->format($diff));
  488. }
  489. drush_print();
  490. drush_print(dt("Config @name @message", array('@name' => $name, '@message' => $message)));
  491. if (!empty($extension)) {
  492. foreach ($rows as $row) {
  493. if (strpos($row, '>') === 0) {
  494. drush_print(sprintf($green, $row));
  495. }
  496. elseif (strpos($row, '<') === 0) {
  497. drush_print(sprintf($red, $row));
  498. }
  499. else {
  500. drush_print($row);
  501. }
  502. }
  503. }
  504. }
  505. }
  506. }
  507. /**
  508. * Imports module config into the active store.
  509. *
  510. * Same as the old "revert" functionality.
  511. */
  512. function drush_features_import() {
  513. if ($args = func_get_args()) {
  514. _drush_features_options();
  515. // Determine if revert should be forced.
  516. $force = drush_get_option('force');
  517. // Determine if -y was supplied. If so, we can filter out needless output
  518. // from this command.
  519. $skip_confirmation = drush_get_context('DRUSH_AFFIRMATIVE');
  520. /** @var \Drupal\features\FeaturesManagerInterface $manager */
  521. $manager = \Drupal::service('features.manager');
  522. // Parse list of arguments.
  523. $modules = array();
  524. foreach ($args as $arg) {
  525. $arg = explode(':', $arg);
  526. $module = array_shift($arg);
  527. $component = array_shift($arg);
  528. if (isset($module)) {
  529. if (empty($component)) {
  530. // If we received just a feature name, this means that we need all of
  531. // its components.
  532. $modules[$module] = TRUE;
  533. }
  534. elseif ($modules[$module] !== TRUE) {
  535. if (!isset($modules[$module])) {
  536. $modules[$module] = array();
  537. }
  538. $modules[$module][] = $component;
  539. }
  540. }
  541. }
  542. // Process modules.
  543. foreach ($modules as $module => $components_needed) {
  544. $dt_args['@module'] = $module;
  545. /** @var \Drupal\features\Package $feature */
  546. $feature = $manager->loadPackage($module, TRUE);
  547. if (empty($feature)) {
  548. drush_log(dt('No such feature is available: @module', $dt_args), 'error');
  549. return;
  550. }
  551. if ($feature->getStatus() != FeaturesManagerInterface::STATUS_INSTALLED) {
  552. drush_log(dt('No such feature is installed: @module', $dt_args), 'error');
  553. return;
  554. }
  555. // Forcefully revert all components of a feature.
  556. if ($force) {
  557. $components = $feature->getConfigOrig();
  558. }
  559. // Only revert components that are detected to be Overridden.
  560. else {
  561. $components = $manager->detectOverrides($feature);
  562. $missing = $manager->reorderMissing($manager->detectMissing($feature));
  563. // Be sure to import missing components first.
  564. $components = array_merge($missing, $components);
  565. }
  566. if (!empty($components_needed) && is_array($components_needed)) {
  567. $components = array_intersect($components, $components_needed);
  568. }
  569. if (empty($components)) {
  570. drush_log(dt('Current state already matches active config, aborting.'), 'ok');
  571. }
  572. else {
  573. // Determine which config the user wants to import/revert.
  574. $config_to_create = [];
  575. foreach ($components as $component) {
  576. $dt_args['@component'] = $component;
  577. $confirmation_message = 'Do you really want to import @module : @component?';
  578. if ($skip_confirmation || drush_confirm(dt($confirmation_message, $dt_args))) {
  579. $config_to_create[$component] = '';
  580. }
  581. }
  582. // Perform the import/revert.
  583. $config_imported = $manager->createConfiguration($config_to_create);
  584. // List the results.
  585. foreach ($components as $component) {
  586. $dt_args['@component'] = $component;
  587. if (isset($config_imported['new'][$component])) {
  588. drush_log(dt('Imported @module : @component.', $dt_args), 'ok');
  589. }
  590. elseif (isset($config_imported['updated'][$component])) {
  591. drush_log(dt('Reverted @module : @component.', $dt_args), 'ok');
  592. }
  593. elseif (!isset($config_to_create[$component])) {
  594. drush_log(dt('Skipping @module : @component.', $dt_args), 'ok');
  595. }
  596. else {
  597. drush_log(dt('Error importing @module : @component.', $dt_args), 'error');
  598. }
  599. }
  600. }
  601. }
  602. }
  603. else {
  604. drush_print_table(drush_features_list_packages());
  605. return;
  606. }
  607. }
  608. /**
  609. * Returns an array of full config names given a array[$type][$component].
  610. *
  611. * @param array $items
  612. * The items to return data for.
  613. */
  614. function _drush_features_build_config(array $items) {
  615. /** @var \Drupal\features\FeaturesManagerInterface $manager */
  616. $manager = \Drupal::service('features.manager');
  617. $result = array();
  618. foreach ($items as $config_type => $item) {
  619. foreach ($item as $item_name => $title) {
  620. $result[] = $manager->getFullName($config_type, $item_name);
  621. }
  622. }
  623. return $result;
  624. }
  625. /**
  626. * Returns a listing of all known components, indexed by source.
  627. */
  628. function _drush_features_component_list() {
  629. $result = array();
  630. /** @var \Drupal\features\FeaturesManagerInterface $manager */
  631. $manager = \Drupal::service('features.manager');
  632. $config = $manager->getConfigCollection();
  633. foreach ($config as $item_name => $item) {
  634. $result[$item->getType()][$item->getShortName()] = $item->getLabel();
  635. }
  636. return $result;
  637. }
  638. /**
  639. * Filters components by patterns.
  640. */
  641. function _drush_features_component_filter($all_components, $patterns = array(), $options = array()) {
  642. $options += array(
  643. 'exported' => TRUE,
  644. 'not exported' => TRUE,
  645. 'provided by' => FALSE,
  646. );
  647. $pool = array();
  648. // Maps exported components to feature modules.
  649. $components_map = _drush_features_get_component_map();
  650. // First filter on exported state.
  651. foreach ($all_components as $source => $components) {
  652. foreach ($components as $name => $title) {
  653. $exported = count($components_map[$source][$name]) > 0;
  654. if ($exported) {
  655. if ($options['exported']) {
  656. $pool[$source][$name] = $title;
  657. }
  658. }
  659. else {
  660. if ($options['not exported']) {
  661. $pool[$source][$name] = $title;
  662. }
  663. }
  664. }
  665. }
  666. $state_string = '';
  667. if (!$options['exported']) {
  668. $state_string = 'unexported';
  669. }
  670. elseif (!$options['not exported']) {
  671. $state_string = 'exported';
  672. }
  673. $selected = array();
  674. foreach ($patterns as $pattern) {
  675. // Rewrite * to %. Let users use both as wildcard.
  676. $pattern = strtr($pattern, array('*' => '%'));
  677. $sources = array();
  678. list($source_pattern, $component_pattern) = explode(':', $pattern, 2);
  679. // If source is empty, use a pattern.
  680. if ($source_pattern == '') {
  681. $source_pattern = '%';
  682. }
  683. if ($component_pattern == '') {
  684. $component_pattern = '%';
  685. }
  686. $preg_source_pattern = strtr(preg_quote($source_pattern, '/'), array('%' => '.*'));
  687. $preg_component_pattern = strtr(preg_quote($component_pattern, '/'), array('%' => '.*'));
  688. // If it isn't a pattern, but a simple string, we don't anchor the
  689. // pattern. This allows for abbreviating. Otherwise, we do, as this seems
  690. // more natural for patterns.
  691. if (strpos($source_pattern, '%') !== FALSE) {
  692. $preg_source_pattern = '^' . $preg_source_pattern . '$';
  693. }
  694. if (strpos($component_pattern, '%') !== FALSE) {
  695. $preg_component_pattern = '^' . $preg_component_pattern . '$';
  696. }
  697. $matches = array();
  698. // Find the sources.
  699. $all_sources = array_keys($pool);
  700. $matches = preg_grep('/' . $preg_source_pattern . '/', $all_sources);
  701. if (count($matches) > 0) {
  702. // If we have multiple matches and the source string wasn't a
  703. // pattern, check if one of the matches is equal to the pattern, and
  704. // use that, or error out.
  705. if (count($matches) > 1 and $preg_source_pattern[0] != '^') {
  706. if (in_array($source_pattern, $matches)) {
  707. $matches = array($source_pattern);
  708. }
  709. else {
  710. return drush_set_error('', dt('Ambiguous source "@source", matches @matches', array(
  711. '@source' => $source_pattern,
  712. '@matches' => implode(', ', $matches),
  713. )));
  714. }
  715. }
  716. // Loose the indexes preg_grep preserved.
  717. $sources = array_values($matches);
  718. }
  719. else {
  720. return drush_set_error('', dt('No @state sources match "@source"', array('@state' => $state_string, '@source' => $source_pattern)));
  721. }
  722. // Now find the components.
  723. foreach ($sources as $source) {
  724. // Find the components.
  725. $all_components = array_keys($pool[$source]);
  726. // See if there's any matches.
  727. $matches = preg_grep('/' . $preg_component_pattern . '/', $all_components);
  728. if (count($matches) > 0) {
  729. // If we have multiple matches and the components string wasn't a
  730. // pattern, check if one of the matches is equal to the pattern, and
  731. // use that, or error out.
  732. if (count($matches) > 1 and $preg_component_pattern[0] != '^') {
  733. if (in_array($component_pattern, $matches)) {
  734. $matches = array($component_pattern);
  735. }
  736. else {
  737. return drush_set_error('', dt('Ambiguous component "@component", matches @matches', array(
  738. '@component' => $component_pattern,
  739. '@matches' => implode(', ', $matches),
  740. )));
  741. }
  742. }
  743. if (!is_array($selected[$source])) {
  744. $selected[$source] = array();
  745. }
  746. $selected[$source] += array_intersect_key($pool[$source], array_flip($matches));
  747. }
  748. else {
  749. // No matches. If the source was a pattern, just carry on, else
  750. // error out. Allows for patterns like :*field*
  751. if ($preg_source_pattern[0] != '^') {
  752. return drush_set_error('', dt('No @state @source components match "@component"', array(
  753. '@state' => $state_string,
  754. '@component' => $component_pattern,
  755. '@source' => $source,
  756. )));
  757. }
  758. }
  759. }
  760. }
  761. // Lastly, provide feature module information on the selected components, if
  762. // requested.
  763. $provided_by = array();
  764. if ($options['provided by'] && $options['exported']) {
  765. foreach ($selected as $source => $components) {
  766. foreach ($components as $name => $title) {
  767. $exported = count($components_map[$source][$name]) > 0;
  768. if ($exported) {
  769. $provided_by[$source . ':' . $name] = implode(', ', $components_map[$source][$name]);
  770. }
  771. }
  772. }
  773. }
  774. return array(
  775. 'components' => $selected,
  776. 'sources' => $provided_by,
  777. );
  778. }
  779. /**
  780. * Provides a component to feature map (port of features_get_component_map).
  781. */
  782. function _drush_features_get_component_map() {
  783. $result = array();
  784. /** @var \Drupal\features\FeaturesManagerInterface $manager */
  785. $manager = \Drupal::service('features.manager');
  786. // Recalc full config list without running assignments.
  787. $config = $manager->getConfigCollection();
  788. $packages = $manager->getPackages();
  789. foreach ($config as $item_name => $item) {
  790. $type = $item->getType();
  791. $short_name = $item->getShortName();
  792. $name = $item->getName();
  793. if (!isset($result[$type][$short_name])) {
  794. $result[$type][$short_name] = array();
  795. }
  796. if (!empty($item->getPackage())) {
  797. $package = $packages[$item->getPackage()];
  798. $result[$type][$short_name][] = $package->getMachineName();
  799. }
  800. }
  801. return $result;
  802. }
  803. /**
  804. * Prints a list of filtered components.
  805. */
  806. function _drush_features_component_print($filtered_components) {
  807. $rows = array(array(dt('Available sources')));
  808. foreach ($filtered_components['components'] as $source => $components) {
  809. foreach ($components as $name => $value) {
  810. $row = array($source . ':' . $name);
  811. if (isset($filtered_components['sources'][$source . ':' . $name])) {
  812. $row[] = dt('Provided by') . ': ' . $filtered_components['sources'][$source . ':' . $name];
  813. }
  814. $rows[] = $row;
  815. }
  816. }
  817. drush_print_table($rows, TRUE);
  818. }