12a13,415
> diff --git a/migrate_tools.drush.inc b/migrate_tools.drush.inc
> index 5548408..ff62949 100644
> --- a/migrate_tools.drush.inc
> +++ b/migrate_tools.drush.inc
> @@ -142,111 +142,28 @@ function migrate_tools_drush_command() {
>   * @param string $migration_names
>   */
>  function drush_migrate_tools_migrate_status($migration_names = '') {
> -  $names_only = drush_get_option('names-only');
> -
> -  $migrations = drush_migrate_tools_migration_list($migration_names);
> -
> -  $table = [];
> -  // Take it one group at a time, listing the migrations within each group.
> -  foreach ($migrations as $group_id => $migration_list) {
> -    $group = MigrationGroup::load($group_id);
> -    $group_name = !empty($group) ? "{$group->label()} ({$group->id()})" : $group_id;
> -    if ($names_only) {
> -      $table[] = [
> -        dt('Group: @name', array('@name' => $group_name))
> -      ];
> -    }
> -    else {
> -      $table[] = [
> -        dt('Group: @name', array('@name' => $group_name)),
> -        dt('Status'),
> -        dt('Total'),
> -        dt('Imported'),
> -        dt('Unprocessed'),
> -        dt('Last imported'),
> -      ];
> -    }
> -    foreach ($migration_list as $migration_id => $migration) {
> -      try {
> -        $map = $migration->getIdMap();
> -        $imported = $map->importedCount();
> -        $source_plugin = $migration->getSourcePlugin();
> -      }
> -      catch (Exception $e) {
> -        drush_log(dt('Failure retrieving information on @migration: @message',
> -          ['@migration' => $migration_id, '@message' => $e->getMessage()]));
> -        continue;
> -      }
> -      if ($names_only) {
> -        $table[] = [$migration_id];
> -      }
> -      else {
> -        try {
> -          $source_rows = $source_plugin->count();
> -          // -1 indicates uncountable sources.
> -          if ($source_rows == -1) {
> -            $source_rows = dt('N/A');
> -            $unprocessed = dt('N/A');
> -          }
> -          else {
> -            $unprocessed = $source_rows - $map->processedCount();
> -          }
> -        }
> -        catch (Exception $e) {
> -          drush_print($e->getMessage());
> -          drush_log(dt('Could not retrieve source count from @migration: @message',
> -            ['@migration' => $migration_id, '@message' => $e->getMessage()]));
> -          $source_rows = dt('N/A');
> -          $unprocessed = dt('N/A');
> -        }
> -
> -        $status = $migration->getStatusLabel();
> -        $migrate_last_imported_store = \Drupal::keyValue('migrate_last_imported');
> -        $last_imported = $migrate_last_imported_store->get($migration->id(), FALSE);
> -        if ($last_imported) {
> -          /** @var DateFormatter $date_formatter */
> -          $date_formatter = \Drupal::service('date.formatter');
> -          $last_imported = $date_formatter->format($last_imported / 1000,
> -            'custom', 'Y-m-d H:i:s');
> -        }
> -        else {
> -          $last_imported = '';
> -        }
> -        $table[] = [$migration_id, $status, $source_rows, $imported, $unprocessed, $last_imported];
> -      }
> -    }
> -  }
> -  drush_print_table($table);
> +  \Drupal::service('migrate_tools.commands')->status($migration_names, [
> +    'group' => drush_get_option('group'),
> +    'tag' => drush_get_option('tag'),
> +    'names-only' => drush_get_option('names-only'),
> +  ]);
>  }
>  
>  /**
>   * @param string $migration_names
>   */
>  function drush_migrate_tools_migrate_import($migration_names = '') {
> -  $group_names = drush_get_option('group');
> -  $tag_names = drush_get_option('tag');
> -  $all = drush_get_option('all');
> -  $options = [];
> -  if (!$all && !$group_names && !$migration_names && !$tag_names) {
> -    drush_set_error('MIGRATE_ERROR', dt('You must specify --all, --group, --tag or one or more migration names separated by commas'));
> -    return;
> -  }
> -
> -  foreach (['limit', 'feedback', 'idlist', 'update', 'force'] as $option) {
> -    if (drush_get_option($option)) {
> -      $options[$option] = drush_get_option($option);
> -    }
> -  }
> -
> -  $migrations = drush_migrate_tools_migration_list($migration_names);
> -  if (empty($migrations)) {
> -    drush_log(dt('No migrations found.'), 'error');
> -  }
> -
> -  // Take it one group at a time, importing the migrations within each group.
> -  foreach ($migrations as $group_id => $migration_list) {
> -    array_walk($migration_list, '_drush_migrate_tools_execute_migration', $options);
> -  }
> +  \Drupal::service('migrate_tools.commands')->import($migration_names, [
> +    'all' => drush_get_option('all'),
> +    'group' => drush_get_option('group'),
> +    'tag' => drush_get_option('tag'),
> +    'limit' => drush_get_option('limit'),
> +    'feedback' => drush_get_option('feedback'),
> +    'idlist' => drush_get_option('idlist'),
> +    'update' => drush_get_option('update'),
> +    'force' => drush_get_option('force'),
> +    'execute-dependencies' => drush_get_option('execute-dependencies'),
> +  ]);
>  }
>  
>  /**
> @@ -261,179 +178,51 @@ function drush_migrate_tools_migrate_import($migration_names = '') {
>   *  Additional options for the migration.
>   */
>  function _drush_migrate_tools_execute_migration(MigrationInterface $migration, $migration_id,  array $options = []) {
> -  $log = new DrushLogMigrateMessage();
> -
> -  if (drush_get_option('execute-dependencies')) {
> -    if ($required_IDS = $migration->get('requirements')) {
> -      $manager = \Drupal::service('plugin.manager.migration');
> -      $required_migrations = $manager->createInstances($required_IDS);
> -      $dependency_options = array_merge($options, ['is_dependency' => TRUE]);
> -      array_walk($required_migrations, __FUNCTION__, $dependency_options);
> -    }
> -  }
> -  if (!empty($options['force'])) {
> -    $migration->set('requirements', []);
> -  }
> -  if (!empty($options['update'])) {
> -    $migration->getIdMap()->prepareUpdate();
> -  }
> -  $executable = new MigrateExecutable($migration, $log, $options);
> -  // drush_op() provides --simulate support
> -  drush_op(array($executable, 'import'));
> -  if ($count = $executable->getFailedCount()) {
> -    // Nudge Drush to use a non-zero exit code.
> -    drush_set_error('MIGRATE_ERROR', dt('!name Migration - !count failed.', array('!name' => $migration_id, '!count' => $count)));
> -  }
> +  \Drupal::service('migrate_tools.commands')->executeMigration(
> +    $migration,
> +    $migration_id,
> +    ['execute-dependencies' => drush_get_option('execute-dependencies')]
> +  );
>  }
>  
>  /**
>   * @param string $migration_names
>   */
>  function drush_migrate_tools_migrate_rollback($migration_names = '') {
> -  $group_names = drush_get_option('group');
> -  $tag_names = drush_get_option('tag');
> -  $all = drush_get_option('all');
> -  $options = [];
> -  if (!$all && !$group_names && !$migration_names && !$tag_names) {
> -    drush_set_error('MIGRATE_ERROR', dt('You must specify --all, --group, --tag, or one or more migration names separated by commas'));
> -    return;
> -  }
> -
> -  if (drush_get_option('feedback')) {
> -    $options['feedback'] = drush_get_option('feedback');
> -  }
> -
> -  $log = new DrushLogMigrateMessage();
> -
> -  $migrations = drush_migrate_tools_migration_list($migration_names);
> -  if (empty($migrations)) {
> -    drush_log(dt('No migrations found.'), 'error');
> -  }
> -
> -  // Take it one group at a time, rolling back the migrations within each group.
> -  foreach ($migrations as $group_id => $migration_list) {
> -    // Roll back in reverse order.
> -    $migration_list = array_reverse($migration_list);
> -    foreach ($migration_list as $migration_id => $migration) {
> -      $executable = new MigrateExecutable($migration, $log, $options);
> -      // drush_op() provides --simulate support.
> -      drush_op(array($executable, 'rollback'));
> -    }
> -  }
> +  \Drupal::service('migrate_tools.commands')->rollback($migration_names, [
> +    'all' => drush_get_option('all'),
> +    'group' => drush_get_option('group'),
> +    'tag' => drush_get_option('tag'),
> +    'feedback' => drush_get_option('feedback'),
> +  ]);
>  }
>  
>  /**
>   * @param string $migration_id
>   */
>  function drush_migrate_tools_migrate_stop($migration_id = '') {
> -  /** @var MigrationInterface $migration */
> -  $migration = \Drupal::service('plugin.manager.migration')->createInstance($migration_id);
> -  if ($migration) {
> -    $status = $migration->getStatus();
> -    switch ($status) {
> -      case MigrationInterface::STATUS_IDLE:
> -        drush_log(dt('Migration @id is idle', ['@id' => $migration_id]), 'warning');
> -        break;
> -      case MigrationInterface::STATUS_DISABLED:
> -        drush_log(dt('Migration @id is disabled', ['@id' => $migration_id]), 'warning');
> -        break;
> -      case MigrationInterface::STATUS_STOPPING:
> -        drush_log(dt('Migration @id is already stopping', ['@id' => $migration_id]), 'warning');
> -        break;
> -      default:
> -        $migration->interruptMigration(MigrationInterface::RESULT_STOPPED);
> -        drush_log(dt('Migration @id requested to stop', ['@id' => $migration_id]), 'success');
> -        break;
> -    }
> -  }
> -  else {
> -    drush_log(dt('Migration @id does not exist', ['@id' => $migration_id]), 'error');
> -  }
> +  \Drupal::service('migrate_tools.commands')->stop($migration_names);
>  }
>  
>  /**
>   * @param string $migration_id
>   */
>  function drush_migrate_tools_migrate_reset_status($migration_id = '') {
> -  /** @var MigrationInterface $migration */
> -  $migration = \Drupal::service('plugin.manager.migration')->createInstance($migration_id);
> -  if ($migration) {
> -    $status = $migration->getStatus();
> -    if ($status == MigrationInterface::STATUS_IDLE) {
> -      drush_log(dt('Migration @id is already Idle', ['@id' => $migration_id]), 'warning');
> -    }
> -    else {
> -      $migration->setStatus(MigrationInterface::STATUS_IDLE);
> -      drush_log(dt('Migration @id reset to Idle', ['@id' => $migration_id]), 'status');
> -    }
> -  }
> -  else {
> -    drush_log(dt('Migration @id does not exist', ['@id' => $migration_id]), 'error');
> -  }
> +  \Drupal::service('migrate_tools.commands')->resetStatus($migration_names);
>  }
>  
>  /**
>   * @param string $migration_id
>   */
>  function drush_migrate_tools_migrate_messages($migration_id) {
> -  /** @var MigrationInterface $migration */
> -  $migration = \Drupal::service('plugin.manager.migration')->createInstance($migration_id);
> -  if ($migration) {
> -    $map = $migration->getIdMap();
> -    $first = TRUE;
> -    $table = [];
> -    foreach ($map->getMessageIterator() as $row) {
> -      unset($row->msgid);
> -      if ($first) {
> -        // @todo: Ideally, replace sourceid* with source key names. Or, should
> -        // getMessageIterator() do that?
> -        foreach ($row as $column => $value) {
> -          $table[0][] = $column;
> -        }
> -        $first = FALSE;
> -      }
> -      $table[] = (array)$row;
> -    }
> -    if (empty($table)) {
> -      drush_log(dt('No messages for this migration'), 'status');
> -    }
> -    else {
> -      if (drush_get_option('csv')) {
> -        foreach ($table as $row) {
> -          fputcsv(STDOUT, $row);
> -        }
> -      }
> -      else {
> -        $widths = [];
> -        foreach ($table[0] as $header) {
> -          $widths[] = strlen($header) + 1;
> -        }
> -        drush_print_table($table, TRUE, $widths);
> -      }
> -    }
> -  }
> -  else {
> -    drush_log(dt('Migration @id does not exist', ['@id' => $migration_id]), 'error');
> -  }
> +  \Drupal::service('migrate_tools.commands')->messages($migration_id);
>  }
>  
>  /**
>   * @param string $migration_id
>   */
>  function drush_migrate_tools_migrate_fields_source($migration_id) {
> -  /** @var MigrationInterface $migration */
> -  $migration = \Drupal::service('plugin.manager.migration')->createInstance($migration_id);
> -  if ($migration) {
> -    $source = $migration->getSourcePlugin();
> -    $table = [];
> -    foreach ($source->fields() as $machine_name => $description) {
> -      $table[] = [strip_tags($description), $machine_name];
> -    }
> -    drush_print_table($table);
> -  }
> -  else {
> -    drush_log(dt('Migration @id does not exist', ['@id' => $migration_id]), 'error');
> -  }
> +  \Drupal::service('migrate_tools.commands')->fieldsSource($migration_id);
>  }
>  
>  /**
> @@ -447,71 +236,8 @@ function drush_migrate_tools_migrate_fields_source($migration_id) {
>   *   migrations or an empty array if no migrations match the input criteria.
>   */
>  function drush_migrate_tools_migration_list($migration_ids = '') {
> -  // Filter keys must match the migration configuration property name.
> -  $filter['migration_group'] = drush_get_option('group') ? explode(',', drush_get_option('group')) : [];
> -  $filter['migration_tags'] = drush_get_option('tag') ? explode(',', drush_get_option('tag')) : [];
> -
> -  $manager = \Drupal::service('plugin.manager.migration');
> -  $plugins = $manager->createInstances([]);
> -  $matched_migrations = [];
> -
> -  // Get the set of migrations that may be filtered.
> -  if (empty($migration_ids)) {
> -    $matched_migrations = $plugins;
> -  }
> -  else {
> -    // Get the requested migrations.
> -    $migration_ids = explode(',', Unicode::strtolower($migration_ids));
> -    foreach ($plugins as $id => $migration) {
> -      if (in_array(Unicode::strtolower($id), $migration_ids)) {
> -        $matched_migrations[$id] = $migration;
> -      }
> -    }
> -  }
> -
> -  // Do not return any migrations which fail to meet requirements.
> -  /** @var \Drupal\migrate\Plugin\Migration $migration */
> -  foreach ($matched_migrations as $id => $migration) {
> -    if ($migration->getSourcePlugin() instanceof RequirementsInterface) {
> -      try {
> -        $migration->getSourcePlugin()->checkRequirements();
> -      }
> -      catch (RequirementsException $e) {
> -        unset($matched_migrations[$id]);
> -      }
> -    }
> -  }
> -
> -  // Filters the matched migrations if a group or a tag has been input.
> -  if (!empty($filter['migration_group']) || !empty($filter['migration_tags'])) {
> -    // Get migrations in any of the specified groups and with any of the
> -    // specified tags.
> -    foreach ($filter as $property => $values) {
> -      if (!empty($values)) {
> -        $filtered_migrations = [];
> -        foreach ($values as $search_value) {
> -          foreach ($matched_migrations as $id => $migration) {
> -            // Cast to array because migration_tags can be an array.
> -            $configured_values = (array) $migration->get($property);
> -            $configured_id = (in_array($search_value, $configured_values)) ? $search_value : 'default';
> -            if (empty($search_value) || $search_value == $configured_id) {
> -              if (empty($migration_ids) || in_array(Unicode::strtolower($id), $migration_ids)) {
> -                $filtered_migrations[$id] = $migration;
> -              }
> -            }
> -          }
> -        }
> -        $matched_migrations = $filtered_migrations;
> -      }
> -    }
> -  }
> -
> -  // Sort the matched migrations by group.
> -  if (!empty($matched_migrations)) {
> -    foreach ($matched_migrations as $id => $migration) {
> -      $configured_group_id = empty($migration->get('migration_group')) ? 'default' : $migration->get('migration_group');
> -      $migrations[$configured_group_id][$id] = $migration;
> -    }
> -  }
> -  return isset($migrations) ? $migrations : [];
> +  \Drupal::service('migrate_tools.commands')->migrationsList($migration_ids, [
> +    'group' => drush_get_option('group'),
> +    'tag' => drush_get_option('tag'),
> +  ]);
>  }
15c418
< index 0000000..65fb4d2
---
> index 0000000..6a07e98
18c421
< @@ -0,0 +1,701 @@
---
> @@ -0,0 +1,717 @@
31a435
> +use Drupal\migrate_tools\DrushLogMigrateMessage;
75a480
> +    parent::__construct();
454,455d858
< +    $log = new Drush9LogMigrateMessage($this->logger());
< +
469c872
< +          $log,
---
> +          $this->getMigrateMessage(),
689,691c1092
< +    $log = new Drush9LogMigrateMessage($this->logger());
< +
< +    if ($options['execute-dependencies']) {
---
> +    if (isset($options['execute-dependencies'])) {
705c1106
< +    $executable = new MigrateExecutable($migration, $log, $options);
---
> +    $executable = new MigrateExecutable($migration, $this->getMigrateMessage(), $options);
718a1120,1137
> +  /**
> +   * Gets the migrate message logger.
> +   *
> +   * @return \Drupal\migrate\MigrateMessageInterface
> +   *   The migrate message service.
> +   */
> +  protected function getMigrateMessage() {
> +    if (!isset($this->migrateMessage)) {
> +      if (Drush::getMajorVersion() >= 9) {
> +        $this->migrateMessage = new Drush9LogMigrateMessage($this->logger());
> +      }
> +      else {
> +        $this->migrateMessage = new DrushLogMigrateMessage();
> +      }
> +    }
> +    return $this->migrateMessage;
> +  }
> +
