Ejemplo n.º 1
0
 /**
  * Parse the complete commit message and decode it to a string.
  *
  * <p>This method parses and returns the message portion of the commit buffer, after taking the
  * commit's character set into account and decoding the buffer using that character set. This
  * method is a fairly expensive operation and produces a new string on each invocation.
  *
  * @return decoded commit message as a string. Never null.
  */
 public final String getFullMessage() {
   final byte[] raw = buffer;
   final int msgB = RawParseUtils.commitMessage(raw, 0);
   if (msgB < 0) return ""; // $NON-NLS-1$
   final Charset enc = RawParseUtils.parseEncoding(raw);
   return RawParseUtils.decode(enc, raw, msgB, raw.length);
 }
  /** @return true if commit info is ok */
  public boolean checkCommitInfo() {
    updateStateFromUI();

    if (commitMessage.trim().length() == 0) {
      MessageDialog.openWarning(
          getShell(),
          UIText.CommitDialog_ErrorNoMessage,
          UIText.CommitDialog_ErrorMustEnterCommitMessage);
      return false;
    }

    boolean authorValid = false;
    if (author.length() > 0) authorValid = RawParseUtils.parsePersonIdent(author) != null;
    if (!authorValid) {
      MessageDialog.openWarning(
          getShell(),
          UIText.CommitDialog_ErrorInvalidAuthor,
          UIText.CommitDialog_ErrorInvalidAuthorSpecified);
      return false;
    }

    boolean committerValid = false;
    if (committer.length() > 0) committerValid = RawParseUtils.parsePersonIdent(committer) != null;
    if (!committerValid) {
      MessageDialog.openWarning(
          getShell(),
          UIText.CommitDialog_ErrorInvalidAuthor,
          UIText.CommitDialog_ErrorInvalidCommitterSpecified);
      return false;
    }

    authorHandler.updateProposals();
    committerHandler.updateProposals();
    return true;
  }
Ejemplo n.º 3
0
  /**
   * Parse the footer lines (e.g. "Signed-off-by") for machine processing.
   *
   * <p>This method splits all of the footer lines out of the last paragraph of the commit message,
   * providing each line as a key-value pair, ordered by the order of the line's appearance in the
   * commit message itself.
   *
   * <p>A footer line's key must match the pattern {@code ^[A-Za-z0-9-]+:}, while the value is
   * free-form, but must not contain an LF. Very common keys seen in the wild are:
   *
   * <ul>
   *   <li>{@code Signed-off-by} (agrees to Developer Certificate of Origin)
   *   <li>{@code Acked-by} (thinks change looks sane in context)
   *   <li>{@code Reported-by} (originally found the issue this change fixes)
   *   <li>{@code Tested-by} (validated change fixes the issue for them)
   *   <li>{@code CC}, {@code Cc} (copy on all email related to this change)
   *   <li>{@code Bug} (link to project's bug tracking system)
   * </ul>
   *
   * @return ordered list of footer lines; empty list if no footers found.
   */
  public final List<FooterLine> getFooterLines() {
    final byte[] raw = buffer;
    int ptr = raw.length - 1;
    while (raw[ptr] == '\n') // trim any trailing LFs, not interesting
    ptr--;

    final int msgB = RawParseUtils.commitMessage(raw, 0);
    final ArrayList<FooterLine> r = new ArrayList<FooterLine>(4);
    final Charset enc = getEncoding();
    for (; ; ) {
      ptr = RawParseUtils.prevLF(raw, ptr);
      if (ptr <= msgB) break; // Don't parse commit headers as footer lines.

      final int keyStart = ptr + 2;
      if (raw[keyStart] == '\n') break; // Stop at first paragraph break, no footers above it.

      final int keyEnd = RawParseUtils.endOfFooterLineKey(raw, keyStart);
      if (keyEnd < 0) continue; // Not a well formed footer line, skip it.

      // Skip over the ': *' at the end of the key before the value.
      //
      int valStart = keyEnd + 1;
      while (valStart < raw.length && raw[valStart] == ' ') valStart++;

      // Value ends at the LF, and does not include it.
      //
      int valEnd = RawParseUtils.nextLF(raw, valStart);
      if (raw[valEnd - 1] == '\n') valEnd--;

      r.add(new FooterLine(raw, enc, keyStart, keyEnd, valStart, valEnd));
    }
    Collections.reverse(r);
    return r;
  }
Ejemplo n.º 4
0
  /**
   * Parse the tag message and return the first "line" of it.
   *
   * <p>The first line is everything up to the first pair of LFs. This is the "oneline" format,
   * suitable for output in a single line display.
   *
   * <p>This method parses and returns the message portion of the tag buffer, after taking the tag's
   * character set into account and decoding the buffer using that character set. This method is a
   * fairly expensive operation and produces a new string on each invocation.
   *
   * @return decoded tag message as a string. Never null. The returned string does not contain any
   *     LFs, even if the first paragraph spanned multiple lines. Embedded LFs are converted to
   *     spaces.
   */
  public final String getShortMessage() {
    final byte[] raw = buffer;
    final int msgB = RawParseUtils.tagMessage(raw, 0);
    if (msgB < 0) return ""; // $NON-NLS-1$

    final Charset enc = RawParseUtils.parseEncoding(raw);
    final int msgE = RawParseUtils.endOfParagraph(raw, msgB);
    String str = RawParseUtils.decode(enc, raw, msgB, msgE);
    if (RevCommit.hasLF(raw, msgB, msgE)) str = str.replace('\n', ' ');
    return str;
  }
Ejemplo n.º 5
0
  /**
   * Parse the commit message and return the first "line" of it.
   *
   * <p>The first line is everything up to the first pair of LFs. This is the "oneline" format,
   * suitable for output in a single line display.
   *
   * <p>This method parses and returns the message portion of the commit buffer, after taking the
   * commit's character set into account and decoding the buffer using that character set. This
   * method is a fairly expensive operation and produces a new string on each invocation.
   *
   * @return decoded commit message as a string. Never null. The returned string does not contain
   *     any LFs, even if the first paragraph spanned multiple lines. Embedded LFs are converted to
   *     spaces.
   */
  public final String getShortMessage() {
    final byte[] raw = buffer;
    final int msgB = RawParseUtils.commitMessage(raw, 0);
    if (msgB < 0) return ""; // $NON-NLS-1$

    final Charset enc = RawParseUtils.parseEncoding(raw);
    final int msgE = RawParseUtils.endOfParagraph(raw, msgB);
    String str = RawParseUtils.decode(enc, raw, msgB, msgE);
    if (hasLF(raw, msgB, msgE)) str = StringUtils.replaceLineBreaksWithSpace(str);
    return str;
  }
Ejemplo n.º 6
0
 private static final ObjectId fromHexString(final byte[] bs, int p) {
   try {
     final int a = RawParseUtils.parseHexInt32(bs, p);
     final int b = RawParseUtils.parseHexInt32(bs, p + 8);
     final int c = RawParseUtils.parseHexInt32(bs, p + 16);
     final int d = RawParseUtils.parseHexInt32(bs, p + 24);
     final int e = RawParseUtils.parseHexInt32(bs, p + 32);
     return new ObjectId(a, b, c, d, e);
   } catch (ArrayIndexOutOfBoundsException e1) {
     throw new InvalidObjectIdException(bs, p, Constants.OBJECT_ID_STRING_LENGTH);
   }
 }
Ejemplo n.º 7
0
 public List<String> getHeaderLines() {
   final IntList m = RawParseUtils.lineMap(header, 0, header.length);
   final List<String> headerLines = new ArrayList<>(m.size() - 1);
   for (int i = 1; i < m.size() - 1; i++) {
     final int b = m.get(i);
     int e = m.get(i + 1);
     if (header[e - 1] == '\n') {
       e--;
     }
     headerLines.add(RawParseUtils.decode(Constants.CHARSET, header, b, e));
   }
   return headerLines;
 }
Ejemplo n.º 8
0
  void parseCanonical(final RevWalk walk, final byte[] raw) throws IOException {
    if (!walk.shallowCommitsInitialized) walk.initializeShallowCommits();

    final MutableObjectId idBuffer = walk.idBuffer;
    idBuffer.fromString(raw, 5);
    tree = walk.lookupTree(idBuffer);

    int ptr = 46;
    if (parents == null) {
      RevCommit[] pList = new RevCommit[1];
      int nParents = 0;
      for (; ; ) {
        if (raw[ptr] != 'p') break;
        idBuffer.fromString(raw, ptr + 7);
        final RevCommit p = walk.lookupCommit(idBuffer);
        if (nParents == 0) pList[nParents++] = p;
        else if (nParents == 1) {
          pList = new RevCommit[] {pList[0], p};
          nParents = 2;
        } else {
          if (pList.length <= nParents) {
            RevCommit[] old = pList;
            pList = new RevCommit[pList.length + 32];
            System.arraycopy(old, 0, pList, 0, nParents);
          }
          pList[nParents++] = p;
        }
        ptr += 48;
      }
      if (nParents != pList.length) {
        RevCommit[] old = pList;
        pList = new RevCommit[nParents];
        System.arraycopy(old, 0, pList, 0, nParents);
      }
      parents = pList;
    }

    // extract time from "committer "
    ptr = RawParseUtils.committer(raw, ptr);
    if (ptr > 0) {
      ptr = RawParseUtils.nextLF(raw, ptr, '>');

      // In 2038 commitTime will overflow unless it is changed to long.
      commitTime = RawParseUtils.parseBase10(raw, ptr, null);
    }

    if (walk.isRetainBody()) buffer = raw;
    flags |= PARSED;
  }
  public String getProjectDescription(final Project.NameKey name)
      throws RepositoryNotFoundException, IOException {
    final Repository e = openRepository(name);
    try {
      final File d = new File(e.getDirectory(), "description");

      String description;
      try {
        description = RawParseUtils.decode(IO.readFully(d));
      } catch (FileNotFoundException err) {
        return null;
      }

      if (description != null) {
        description = description.trim();
        if (description.isEmpty()) {
          description = null;
        }
        if (UNNAMED.equals(description)) {
          description = null;
        }
      }
      return description;
    } finally {
      e.close();
    }
  }
Ejemplo n.º 10
0
  void parseCanonical(final RevWalk walk, final byte[] rawTag) throws CorruptObjectException {
    final MutableInteger pos = new MutableInteger();
    final int oType;

    pos.value = 53; // "object $sha1\ntype "
    oType = Constants.decodeTypeString(this, rawTag, (byte) '\n', pos);
    walk.idBuffer.fromString(rawTag, 7);
    object = walk.lookupAny(walk.idBuffer, oType);

    int p = pos.value += 4; // "tag "
    final int nameEnd = RawParseUtils.nextLF(rawTag, p) - 1;
    tagName = RawParseUtils.decode(Constants.CHARSET, rawTag, p, nameEnd);

    if (walk.isRetainBody()) buffer = rawTag;
    flags |= PARSED;
  }
Ejemplo n.º 11
0
  private void setAuthorAndCommitter(CommitCommand commitCommand) throws GitAPIException {
    final Date commitDate = new Date();
    final TimeZone timeZone = TimeZone.getDefault();

    final PersonIdent enteredAuthor = RawParseUtils.parsePersonIdent(author);
    final PersonIdent enteredCommitter = RawParseUtils.parsePersonIdent(committer);
    if (enteredAuthor == null) throw new CoreException("The enteredAuthor could not be parsed.");
    if (enteredCommitter == null)
      throw new CoreException("The enteredCommitter could not be parsed.");

    final PersonIdent authorIdent = new PersonIdent(enteredAuthor, commitDate, timeZone);

    final PersonIdent committerIdent = new PersonIdent(enteredCommitter, commitDate, timeZone);

    commitCommand.setAuthor(authorIdent);
    commitCommand.setCommitter(committerIdent);
  }
Ejemplo n.º 12
0
  /* (non-Javadoc)
   * @see org.eclipse.jgit.internal.storage.file.ReflogReaader#getReverseEntries(int)
   */
  public List<ReflogEntry> getReverseEntries(int max) throws IOException {
    final byte[] log;
    try {
      log = IO.readFully(logName);
    } catch (FileNotFoundException e) {
      if (logName.exists()) {
        throw e;
      }
      return Collections.emptyList();
    }

    int rs = RawParseUtils.prevLF(log, log.length);
    List<ReflogEntry> ret = new ArrayList<ReflogEntry>();
    while (rs >= 0 && max-- > 0) {
      rs = RawParseUtils.prevLF(log, rs);
      ReflogEntry entry = new ReflogEntryImpl(log, rs < 0 ? 0 : rs + 2);
      ret.add(entry);
    }
    return ret;
  }
Ejemplo n.º 13
0
 /**
  * Test a string of characters to verify it is a hex format.
  *
  * <p>If true the string can be parsed with {@link #fromString(String)}.
  *
  * @param id the string to test.
  * @return true if the string can converted into an ObjectId.
  */
 public static final boolean isId(final String id) {
   if (id.length() != Constants.OBJECT_ID_STRING_LENGTH) return false;
   try {
     for (int i = 0; i < Constants.OBJECT_ID_STRING_LENGTH; i++) {
       RawParseUtils.parseHexInt4((byte) id.charAt(i));
     }
     return true;
   } catch (ArrayIndexOutOfBoundsException e) {
     return false;
   }
 }
  /**
   * Get the status of whether the commit operation should be enabled or disabled.
   *
   * <p>This method checks the current state of the widgets and must always be called from the
   * UI-thread.
   *
   * <p>The returned status includes a message and type denoting why committing cannot be completed.
   *
   * @return non-null commit status
   */
  public CommitStatus getStatus() {
    if (!commitAllowed) return new CommitStatus(cannotCommitMessage, IMessageProvider.ERROR);

    String authorValue = authorText.getText();
    if (authorValue.length() == 0 || RawParseUtils.parsePersonIdent(authorValue) == null)
      return new CommitStatus(
          UIText.CommitMessageComponent_MessageInvalidAuthor, IMessageProvider.ERROR);

    String committerValue = committerText.getText();
    if (committerValue.length() == 0 || RawParseUtils.parsePersonIdent(committerValue) == null) {
      return new CommitStatus(
          UIText.CommitMessageComponent_MessageInvalidCommitter, IMessageProvider.ERROR);
    }

    if (amending && amendingCommitInRemoteBranch)
      return new CommitStatus(
          UIText.CommitMessageComponent_AmendingCommitInRemoteBranch, IMessageProvider.WARNING);

    return CommitStatus.OK;
  }
Ejemplo n.º 15
0
  /* (non-Javadoc)
   * @see org.eclipse.jgit.internal.storage.file.ReflogReaader#getReverseEntry(int)
   */
  public ReflogEntry getReverseEntry(int number) throws IOException {
    if (number < 0) throw new IllegalArgumentException();

    final byte[] log;
    try {
      log = IO.readFully(logName);
    } catch (FileNotFoundException e) {
      if (logName.exists()) {
        throw e;
      }
      return null;
    }

    int rs = RawParseUtils.prevLF(log, log.length);
    int current = 0;
    while (rs >= 0) {
      rs = RawParseUtils.prevLF(log, rs);
      if (number == current) return new ReflogEntryImpl(log, rs < 0 ? 0 : rs + 2);
      current++;
    }
    return null;
  }
Ejemplo n.º 16
0
 /**
  * Load the configuration as a Git text style configuration file.
  *
  * <p>If the file does not exist, this configuration is cleared, and thus behaves the same as
  * though the file exists, but is empty.
  *
  * @throws IOException the file could not be read (but does exist).
  * @throws ConfigInvalidException the file is not a properly formatted configuration file.
  */
 @Override
 public void load() throws IOException, ConfigInvalidException {
   final FileSnapshot oldSnapshot = snapshot;
   final FileSnapshot newSnapshot = FileSnapshot.save(getFile());
   try {
     final byte[] in = IO.readFully(getFile());
     final ObjectId newHash = hash(in);
     if (hash.equals(newHash)) {
       if (oldSnapshot.equals(newSnapshot)) oldSnapshot.setClean(newSnapshot);
       else snapshot = newSnapshot;
     } else {
       final String decoded;
       if (in.length >= 3
           && in[0] == (byte) 0xEF
           && in[1] == (byte) 0xBB
           && in[2] == (byte) 0xBF) {
         decoded = RawParseUtils.decode(RawParseUtils.UTF8_CHARSET, in, 3, in.length);
         utf8Bom = true;
       } else {
         decoded = RawParseUtils.decode(in);
       }
       fromText(decoded);
       snapshot = newSnapshot;
       hash = newHash;
     }
   } catch (FileNotFoundException noFile) {
     clear();
     snapshot = newSnapshot;
   } catch (IOException e) {
     final IOException e2 =
         new IOException(MessageFormat.format(JGitText.get().cannotReadFile, getFile()));
     e2.initCause(e);
     throw e2;
   } catch (ConfigInvalidException e) {
     throw new ConfigInvalidException(
         MessageFormat.format(JGitText.get().cannotReadFile, getFile()), e);
   }
 }
 @Override
 public void write(byte[] b, int offset, int length) {
   if (binaryDiffHandler != null
       && RawParseUtils.decode(Arrays.copyOfRange(b, offset, offset + length))
           .contains(BINARY_DIFFERENCE)) {
     String binaryDiff = binaryDiffHandler.renderBinaryDiff(formatter.entry);
     if (binaryDiff != null) {
       byte[] bb =
           ("<tr><td colspan='4' align='center'>" + binaryDiff + "</td></tr>")
               .getBytes(StandardCharsets.UTF_8);
       super.write(bb, 0, bb.length);
       return;
     }
   }
   super.write(b, offset, length);
 }
Ejemplo n.º 18
0
  private String[] extractFileLines(final Charset[] csGuess) {
    final TemporaryBuffer[] tmp = new TemporaryBuffer[getParentCount() + 1];
    try {
      for (int i = 0; i < tmp.length; i++) tmp[i] = new TemporaryBuffer.LocalFile();
      for (final HunkHeader h : getHunks()) h.extractFileLines(tmp);

      final String[] r = new String[tmp.length];
      for (int i = 0; i < tmp.length; i++) {
        Charset cs = csGuess != null ? csGuess[i] : null;
        if (cs == null) cs = Constants.CHARSET;
        r[i] = RawParseUtils.decode(cs, tmp[i].toByteArray());
      }
      return r;
    } catch (IOException ioe) {
      throw new RuntimeException(JGitText.get().cannotConvertScriptToText, ioe);
    } finally {
      for (final TemporaryBuffer b : tmp) {
        if (b != null) b.destroy();
      }
    }
  }
Ejemplo n.º 19
0
 static short parse16(byte[] src, int pos) {
   return (short) RawParseUtils.parseHexInt16(src, pos);
 }
Ejemplo n.º 20
0
 /**
  * Parse the committer identity from the raw buffer.
  *
  * <p>This method parses and returns the content of the committer line, after taking the commit's
  * character set into account and decoding the committer name and email address. This method is
  * fairly expensive and produces a new PersonIdent instance on each invocation. Callers should
  * invoke this method only if they are certain they will be outputting the result, and should
  * cache the return value for as long as necessary to use all information from it.
  *
  * <p>RevFilter implementations should try to use {@link RawParseUtils} to scan the {@link
  * #getRawBuffer()} instead, as this will allow faster evaluation of commits.
  *
  * @return identity of the committer (name, email) and the time the commit was made by the
  *     committer; null if no committer line was found.
  */
 public final PersonIdent getCommitterIdent() {
   final byte[] raw = buffer;
   final int nameB = RawParseUtils.committer(raw, 0);
   if (nameB < 0) return null;
   return RawParseUtils.parsePersonIdent(raw, nameB);
 }
Ejemplo n.º 21
0
  /**
   * Format this delta as a human readable string.
   *
   * @param delta the delta instruction sequence to format.
   * @param includeHeader true if the header (base size and result size) should be included in the
   *     formatting.
   * @return the formatted delta.
   */
  public static String format(byte[] delta, boolean includeHeader) {
    StringBuilder r = new StringBuilder();
    int deltaPtr = 0;

    long baseLen = 0;
    int c, shift = 0;
    do {
      c = delta[deltaPtr++] & 0xff;
      baseLen |= (c & 0x7f) << shift;
      shift += 7;
    } while ((c & 0x80) != 0);

    long resLen = 0;
    shift = 0;
    do {
      c = delta[deltaPtr++] & 0xff;
      resLen |= (c & 0x7f) << shift;
      shift += 7;
    } while ((c & 0x80) != 0);

    if (includeHeader) r.append("DELTA( BASE=" + baseLen + " RESULT=" + resLen + " )\n");

    while (deltaPtr < delta.length) {
      final int cmd = delta[deltaPtr++] & 0xff;
      if ((cmd & 0x80) != 0) {
        // Determine the segment of the base which should
        // be copied into the output. The segment is given
        // as an offset and a length.
        //
        int copyOffset = 0;
        if ((cmd & 0x01) != 0) copyOffset = delta[deltaPtr++] & 0xff;
        if ((cmd & 0x02) != 0) copyOffset |= (delta[deltaPtr++] & 0xff) << 8;
        if ((cmd & 0x04) != 0) copyOffset |= (delta[deltaPtr++] & 0xff) << 16;
        if ((cmd & 0x08) != 0) copyOffset |= (delta[deltaPtr++] & 0xff) << 24;

        int copySize = 0;
        if ((cmd & 0x10) != 0) copySize = delta[deltaPtr++] & 0xff;
        if ((cmd & 0x20) != 0) copySize |= (delta[deltaPtr++] & 0xff) << 8;
        if ((cmd & 0x40) != 0) copySize |= (delta[deltaPtr++] & 0xff) << 16;
        if (copySize == 0) copySize = 0x10000;

        r.append("  COPY  (" + copyOffset + ", " + copySize + ")\n");

      } else if (cmd != 0) {
        // Anything else the data is literal within the delta
        // itself.
        //
        r.append("  INSERT(");
        r.append(
            QuotedString.GIT_PATH.quote(RawParseUtils.decode(delta, deltaPtr, deltaPtr + cmd)));
        r.append(")\n");
        deltaPtr += cmd;
      } else {
        // cmd == 0 has been reserved for future encoding but
        // for now its not acceptable.
        //
        throw new IllegalArgumentException(JGitText.get().unsupportedCommand0);
      }
    }

    return r.toString();
  }
Ejemplo n.º 22
0
  LooseRef scanRef(LooseRef ref, String name) throws IOException {
    final File path = fileFor(name);
    FileSnapshot currentSnapshot = null;

    if (ref != null) {
      currentSnapshot = ref.getSnapShot();
      if (!currentSnapshot.isModified(path)) return ref;
      name = ref.getName();
    }

    final int limit = 4096;
    final byte[] buf;
    FileSnapshot otherSnapshot = FileSnapshot.save(path);
    try {
      buf = IO.readSome(path, limit);
    } catch (FileNotFoundException noFile) {
      if (path.exists() && path.isFile()) {
        throw noFile;
      }
      return null; // doesn't exist or no file; not a reference.
    }

    int n = buf.length;
    if (n == 0) return null; // empty file; not a reference.

    if (isSymRef(buf, n)) {
      if (n == limit) return null; // possibly truncated ref

      // trim trailing whitespace
      while (0 < n && Character.isWhitespace(buf[n - 1])) n--;
      if (n < 6) {
        String content = RawParseUtils.decode(buf, 0, n);
        throw new IOException(MessageFormat.format(JGitText.get().notARef, name, content));
      }
      final String target = RawParseUtils.decode(buf, 5, n);
      if (ref != null && ref.isSymbolic() && ref.getTarget().getName().equals(target)) {
        assert (currentSnapshot != null);
        currentSnapshot.setClean(otherSnapshot);
        return ref;
      }
      return newSymbolicRef(otherSnapshot, name, target);
    }

    if (n < OBJECT_ID_STRING_LENGTH)
      return null; // impossibly short object identifier; not a reference.

    final ObjectId id;
    try {
      id = ObjectId.fromString(buf, 0);
      if (ref != null && !ref.isSymbolic() && id.equals(ref.getTarget().getObjectId())) {
        assert (currentSnapshot != null);
        currentSnapshot.setClean(otherSnapshot);
        return ref;
      }

    } catch (IllegalArgumentException notRef) {
      while (0 < n && Character.isWhitespace(buf[n - 1])) n--;
      String content = RawParseUtils.decode(buf, 0, n);

      IOException ioException =
          new IOException(MessageFormat.format(JGitText.get().notARef, name, content));
      ioException.initCause(notRef);
      throw ioException;
    }
    return new LooseUnpeeled(otherSnapshot, name, id);
  }
Ejemplo n.º 23
0
 static String pathOf(final AbstractTreeIterator t) {
   return RawParseUtils.decode(Constants.CHARSET, t.path, 0, t.pathLen);
 }
Ejemplo n.º 24
0
 /**
  * Get the current entry's name within its parent tree.
  *
  * <p>This method is not very efficient and is primarily meant for debugging and final output
  * generation. Applications should try to avoid calling it, and if invoked do so only once per
  * interesting entry, where the name is absolutely required for correct function.
  *
  * @return name of the current entry within the parent tree (or directory). The name never
  *     includes a '/'.
  */
 public String getNameString() {
   final AbstractTreeIterator t = currentHead;
   final int off = t.pathOffset;
   final int end = t.pathLen;
   return RawParseUtils.decode(Constants.CHARSET, t.path, off, end);
 }
 /**
  * Workaround function for complex private methods in DiffFormatter. This sets the html for the
  * diff headers.
  *
  * @return
  */
 public String getHtml() {
   String html = RawParseUtils.decode(os.toByteArray());
   String[] lines = html.split("\n");
   StringBuilder sb = new StringBuilder();
   for (String line : lines) {
     if (line.startsWith("index")) {
       // skip index lines
     } else if (line.startsWith("new file") || line.startsWith("deleted file")) {
       // skip new file lines
     } else if (line.startsWith("\\ No newline")) {
       // skip no new line
     } else if (line.startsWith("---") || line.startsWith("+++")) {
       // skip --- +++ lines
     } else if (line.startsWith("diff")) {
       // skip diff lines
     } else {
       boolean gitLinkDiff =
           line.length() > 0 && line.substring(1).startsWith("Subproject commit");
       if (gitLinkDiff) {
         sb.append("<tr><th class='diff-line'></th><th class='diff-line'></th>");
         if (line.charAt(0) == '+') {
           sb.append("<th class='diff-state diff-state-add'></th><td class=\"diff-cell add2\">");
         } else {
           sb.append(
               "<th class='diff-state diff-state-sub'></th><td class=\"diff-cell remove2\">");
         }
         line = StringUtils.escapeForHtml(line.substring(1), false);
       }
       sb.append(line);
       if (gitLinkDiff) {
         sb.append("</td></tr>");
       }
       sb.append('\n');
     }
   }
   if (truncated) {
     sb.append(
         MessageFormat.format(
             "<div class='header'><div class='diffHeader'>{0}</div></div>",
             StringUtils.escapeForHtml(
                 getMsg("gb.diffTruncated", "Diff truncated after the above file"), false)));
     // List all files not shown. We can be sure we do have at least one path in skipped.
     sb.append(
         "<div class='diff'><table cellpadding='0'><tbody><tr><td class='diff-cell' colspan='4'>");
     String deletedSuffix =
         StringUtils.escapeForHtml(getMsg("gb.diffDeletedFileSkipped", "(deleted)"), false);
     boolean first = true;
     for (DiffEntry entry : skipped) {
       if (!first) {
         sb.append('\n');
       }
       if (ChangeType.DELETE.equals(entry.getChangeType())) {
         sb.append(
             "<span id=\"n"
                 + entry.getOldId().name()
                 + "\">"
                 + StringUtils.escapeForHtml(entry.getOldPath(), false)
                 + ' '
                 + deletedSuffix
                 + "</span>");
       } else {
         sb.append(
             "<span id=\"n"
                 + entry.getNewId().name()
                 + "\">"
                 + StringUtils.escapeForHtml(entry.getNewPath(), false)
                 + "</span>");
       }
       first = false;
     }
     skipped.clear();
     sb.append("</td></tr></tbody></table></div>");
   }
   return sb.toString();
 }
Ejemplo n.º 26
0
 /**
  * Determine the encoding of the commit message buffer.
  *
  * <p>Locates the "encoding" header (if present) and then returns the proper character set to
  * apply to this buffer to evaluate its contents as character data.
  *
  * <p>If no encoding header is present, {@link Constants#CHARSET} is assumed.
  *
  * @return the preferred encoding of {@link #getRawBuffer()}.
  */
 public final Charset getEncoding() {
   return RawParseUtils.parseEncoding(buffer);
 }
Ejemplo n.º 27
0
 private String readString(final int len) throws IOException {
   final byte[] raw = new byte[len];
   IO.readFully(rawIn, raw, 0, len);
   return RawParseUtils.decode(Constants.CHARSET, raw, 0, len);
 }
Ejemplo n.º 28
0
 public String getEntityContent() throws IOException {
   Preconditions.checkNotNull(response, "Response is not initialized.");
   Preconditions.checkNotNull(response.getEntity(), "Response.Entity is not initialized.");
   ByteBuffer buf = IO.readWholeStream(response.getEntity().getContent(), 1024);
   return RawParseUtils.decode(buf.array(), buf.arrayOffset(), buf.limit()).trim();
 }
Ejemplo n.º 29
0
 static int parse32(byte[] src, int pos) {
   return RawParseUtils.parseHexInt32(src, pos);
 }
Ejemplo n.º 30
0
 /**
  * Parse a configuration from a byte array.
  *
  * @param base the base configuration file
  * @param blob the byte array, should be UTF-8 encoded text.
  * @throws ConfigInvalidException the byte array is not a valid configuration format.
  */
 public BlobBasedConfig(Config base, final byte[] blob) throws ConfigInvalidException {
   super(base);
   fromText(RawParseUtils.decode(blob));
 }