FirstCommand.java

  1. /*
  2.  * Copyright (C) 2018, Google LLC. and others
  3.  *
  4.  * This program and the accompanying materials are made available under the
  5.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  6.  * https://www.eclipse.org/org/documents/edl-v10.php.
  7.  *
  8.  * SPDX-License-Identifier: BSD-3-Clause
  9.  */
  10. package org.eclipse.jgit.internal.transport.parser;

  11. import static java.util.Arrays.asList;
  12. import static java.util.Collections.emptySet;
  13. import static java.util.Collections.unmodifiableSet;
  14. import static java.util.stream.Collectors.toSet;

  15. import java.util.Set;

  16. import org.eclipse.jgit.annotations.NonNull;

  17. /**
  18.  * In a push, the client sends a list of commands. The first command
  19.  * is special, as it can include a list of capabilities at its end.
  20.  * <p>
  21.  * For example:
  22.  * "oid oid name\0cap1 cap cap3"
  23.  * <p>
  24.  * Not to be confused with {@link FirstWant}, nor with the first line
  25.  * of the reference advertisement parsed by
  26.  * {@code BasePackConnection.readAdvertisedRefs}.
  27.  * <p>
  28.  * This class parses the inputted command line and holds the results:
  29.  * the actual command line and the capabilities.
  30.  */
  31. public final class FirstCommand {
  32.     private final String line;
  33.     private final Set<String> capabilities;

  34.     /**
  35.      * Parse the first line of a receive-pack request.
  36.      *
  37.      * @param line
  38.      *            line from the client.
  39.      * @return an instance of FirstCommand with capabilities parsed out
  40.      */
  41.     @NonNull
  42.     public static FirstCommand fromLine(String line) {
  43.         int nul = line.indexOf('\0');
  44.         if (nul < 0) {
  45.             return new FirstCommand(line, emptySet());
  46.         }
  47.         Set<String> opts =
  48.                 asList(line.substring(nul + 1).split(" ")) //$NON-NLS-1$
  49.                     .stream()
  50.                     .collect(toSet());
  51.         return new FirstCommand(line.substring(0, nul), unmodifiableSet(opts));
  52.     }

  53.     private FirstCommand(String line, Set<String> capabilities) {
  54.         this.line = line;
  55.         this.capabilities = capabilities;
  56.     }

  57.     /** @return non-capabilities part of the line. */
  58.     @NonNull
  59.     public String getLine() {
  60.         return line;
  61.     }

  62.     /** @return capabilities parsed from the line, as an immutable set. */
  63.     @NonNull
  64.     public Set<String> getCapabilities() {
  65.         return capabilities;
  66.     }
  67. }