<commit_before>/*
 * Copyright (c) 2014 Spotify AB.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package com.spotify.helios.cli.command;

import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.Ordering.natural;
import static com.spotify.helios.cli.Output.formatHostname;
import static com.spotify.helios.cli.Output.humanDuration;
import static com.spotify.helios.cli.Output.table;
import static com.spotify.helios.cli.Utils.allAsMap;
import static com.spotify.helios.common.descriptors.HostStatus.Status.UP;
import static java.lang.String.format;
import static java.lang.System.currentTimeMillis;
import static net.sourceforge.argparse4j.impl.Arguments.append;
import static net.sourceforge.argparse4j.impl.Arguments.storeTrue;

import com.spotify.helios.cli.Table;
import com.spotify.helios.client.HeliosClient;
import com.spotify.helios.common.Json;
import com.spotify.helios.common.descriptors.DockerVersion;
import com.spotify.helios.common.descriptors.HostInfo;
import com.spotify.helios.common.descriptors.HostStatus;
import com.spotify.helios.common.descriptors.JobId;
import com.spotify.helios.common.descriptors.TaskStatus;

import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import net.sourceforge.argparse4j.inf.Argument;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;

import java.io.BufferedReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ExecutionException;

public class HostListCommand extends ControlCommand {

  private final Argument quietArg;
  private final Argument patternArg;
  private final Argument fullArg;
  private final Argument statusArg;
  private final Argument hostSelectorsArg;

  private final String statusChoicesString;

  public HostListCommand(final Subparser parser) {
    super(parser);

    Collection<String> statusChoices = Collections2.transform(
        Arrays.asList(HostStatus.Status.values()), new Function<HostStatus.Status, String>() {
          @Override
          public String apply(final HostStatus.Status input) {
            return input.toString();
          }
        });

    statusChoicesString = Joiner.on(", ").join(statusChoices);

    parser.help("list hosts");

    patternArg = parser.addArgument("pattern")
        .nargs("?")
        .setDefault("")
        .help("Pattern to filter hosts with");

    quietArg = parser.addArgument("-q")
        .action(storeTrue())
        .help("only print host names");

    fullArg = parser.addArgument("-f")
        .action(storeTrue())
        .help("Print full host names.");

    statusArg = parser.addArgument("--status")
        .nargs("?")
        .choices(statusChoices.toArray(new String[statusChoices.size()]))
        .help("Filter hosts by its status. Valid statuses are: " + statusChoicesString);

    hostSelectorsArg = parser.addArgument("-s", "--selector")
        .action(append())
        .setDefault(new ArrayList<String>())
        .help("Host selector expression. The list of hosts will be filtered to match only those "
              + "whose labels match all of the supplied expressions. "
              + "Multiple selector expressions can be specified with multiple `-s` arguments "
              + "(e.g. `-s site=foo -s bar!=yes`). "
              + "Supported operators are '=', '!=', 'in' and 'notin'.");
  }

  @Override
  int run(final Namespace options, final HeliosClient client, final PrintStream out,
          final boolean json, final BufferedReader stdin)
      throws ExecutionException, InterruptedException {

    final String pattern = options.getString(patternArg.getDest());
    final List<String> selectorArgValue = options.getList(hostSelectorsArg.getDest());
    final Set<String> selectors = ImmutableSet.copyOf(selectorArgValue);

    final List<String> hosts;

    if (pattern.isEmpty() && selectors.isEmpty()) {
      hosts = client.listHosts().get();
    } else if (!pattern.isEmpty() && selectors.isEmpty()) {
      hosts = client.listHosts(pattern).get();
    } else if (pattern.isEmpty() && !selectors.isEmpty()) {
      hosts = client.listHosts(selectors).get();
    } else {
      hosts = client.listHosts(pattern, selectors).get();
    }

    final Map<String, String> queryParams = Maps.newHashMap();
    final String statusFilter = options.getString(statusArg.getDest());
    if (!isNullOrEmpty(statusFilter)) {
      try {
        HostStatus.Status.valueOf(statusFilter);
        queryParams.put("status", statusFilter);
      } catch (IllegalArgumentException ignored) {
        throw new IllegalArgumentException(
            "Invalid status. Valid statuses are: " + statusChoicesString);
      }
    }

    final boolean full = options.getBoolean(fullArg.getDest());
    final boolean quiet = options.getBoolean(quietArg.getDest());

    if (!isNullOrEmpty(pattern) && hosts.isEmpty()) {
      if (json) {
        out.println(Json.asPrettyStringUnchecked(hosts));
      } else if (!quiet) {
        out.printf("host pattern %s matched no hosts%n", pattern);
      }
      return 1;
    }

    final List<String> sortedHosts = natural().sortedCopy(hosts);

    if (quiet) {
      if (json) {
        out.println(Json.asPrettyStringUnchecked(sortedHosts));
      } else {
        for (final String host : sortedHosts) {
          out.println(formatHostname(full, host));
        }
      }
    } else {<commit_msg>Fix HostListcommand output for no hosts<commit_after>/*
 * Copyright (c) 2014 Spotify AB.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package com.spotify.helios.cli.command;

import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.Ordering.natural;
import static com.spotify.helios.cli.Output.formatHostname;
import static com.spotify.helios.cli.Output.humanDuration;
import static com.spotify.helios.cli.Output.table;
import static com.spotify.helios.cli.Utils.allAsMap;
import static com.spotify.helios.common.descriptors.HostStatus.Status.UP;
import static java.lang.String.format;
import static java.lang.System.currentTimeMillis;
import static net.sourceforge.argparse4j.impl.Arguments.append;
import static net.sourceforge.argparse4j.impl.Arguments.storeTrue;

import com.spotify.helios.cli.Table;
import com.spotify.helios.client.HeliosClient;
import com.spotify.helios.common.Json;
import com.spotify.helios.common.descriptors.DockerVersion;
import com.spotify.helios.common.descriptors.HostInfo;
import com.spotify.helios.common.descriptors.HostStatus;
import com.spotify.helios.common.descriptors.JobId;
import com.spotify.helios.common.descriptors.TaskStatus;

import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import net.sourceforge.argparse4j.inf.Argument;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;

import java.io.BufferedReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ExecutionException;

public class HostListCommand extends ControlCommand {

  private final Argument quietArg;
  private final Argument patternArg;
  private final Argument fullArg;
  private final Argument statusArg;
  private final Argument hostSelectorsArg;

  private final String statusChoicesString;

  public HostListCommand(final Subparser parser) {
    super(parser);

    Collection<String> statusChoices = Collections2.transform(
        Arrays.asList(HostStatus.Status.values()), new Function<HostStatus.Status, String>() {
          @Override
          public String apply(final HostStatus.Status input) {
            return input.toString();
          }
        });

    statusChoicesString = Joiner.on(", ").join(statusChoices);

    parser.help("list hosts");

    patternArg = parser.addArgument("pattern")
        .nargs("?")
        .setDefault("")
        .help("Pattern to filter hosts with");

    quietArg = parser.addArgument("-q")
        .action(storeTrue())
        .help("only print host names");

    fullArg = parser.addArgument("-f")
        .action(storeTrue())
        .help("Print full host names.");

    statusArg = parser.addArgument("--status")
        .nargs("?")
        .choices(statusChoices.toArray(new String[statusChoices.size()]))
        .help("Filter hosts by its status. Valid statuses are: " + statusChoicesString);

    hostSelectorsArg = parser.addArgument("-s", "--selector")
        .action(append())
        .setDefault(new ArrayList<String>())
        .help("Host selector expression. The list of hosts will be filtered to match only those "
              + "whose labels match all of the supplied expressions. "
              + "Multiple selector expressions can be specified with multiple `-s` arguments "
              + "(e.g. `-s site=foo -s bar!=yes`). "
              + "Supported operators are '=', '!=', 'in' and 'notin'.");
  }

  @Override
  int run(final Namespace options, final HeliosClient client, final PrintStream out,
          final boolean json, final BufferedReader stdin)
      throws ExecutionException, InterruptedException {

    final String pattern = options.getString(patternArg.getDest());
    final List<String> selectorArgValue = options.getList(hostSelectorsArg.getDest());
    final Set<String> selectors = ImmutableSet.copyOf(selectorArgValue);

    final List<String> hosts;

    if (pattern.isEmpty() && selectors.isEmpty()) {
      hosts = client.listHosts().get();
    } else if (!pattern.isEmpty() && selectors.isEmpty()) {
      hosts = client.listHosts(pattern).get();
    } else if (pattern.isEmpty() && !selectors.isEmpty()) {
      hosts = client.listHosts(selectors).get();
    } else {
      hosts = client.listHosts(pattern, selectors).get();
    }

    final Map<String, String> queryParams = Maps.newHashMap();
    final String statusFilter = options.getString(statusArg.getDest());
    if (!isNullOrEmpty(statusFilter)) {
      try {
        HostStatus.Status.valueOf(statusFilter);
        queryParams.put("status", statusFilter);
      } catch (IllegalArgumentException ignored) {
        throw new IllegalArgumentException(
            "Invalid status. Valid statuses are: " + statusChoicesString);
      }
    }

    final boolean full = options.getBoolean(fullArg.getDest());
    final boolean quiet = options.getBoolean(quietArg.getDest());

    if (hosts.isEmpty()) {
      if (json) {
        out.println("{ }");
      } else if (!quiet && !isNullOrEmpty(pattern)) {
        out.printf("host pattern %s matched no hosts%n", pattern);
      }
      return 1;
    }

    final List<String> sortedHosts = natural().sortedCopy(hosts);

    if (quiet) {
      if (json) {
        out.println(Json.asPrettyStringUnchecked(sortedHosts));
      } else {
        for (final String host : sortedHosts) {
          out.println(formatHostname(full, host));
        }
      }
    } else {
{'fraction_non_alphanumeric': 0.11486486486486487, 'fraction_numerical': 0.0024852438645542093, 'mean_word_length': 3.6353491720662348, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3753840', 'n_tokens_mistral': 3734, 'n_tokens_neox': 3660, 'n_words': 897}