PatchIdDiffFormatter.java

  1. /*
  2.  * Copyright (C) 2011, Stefan Lay <stefan.lay@.com> 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.diff;

  11. import java.io.IOException;
  12. import java.io.OutputStream;
  13. import java.security.DigestOutputStream;
  14. import java.security.MessageDigest;

  15. import org.eclipse.jgit.lib.Constants;
  16. import org.eclipse.jgit.lib.ObjectId;
  17. import org.eclipse.jgit.util.io.NullOutputStream;

  18. /**
  19.  * A DiffFormatter used to calculate the patch-id of the diff.
  20.  */
  21. public class PatchIdDiffFormatter extends DiffFormatter {

  22.     private final MessageDigest digest;

  23.     /**
  24.      * Initialize a formatter to compute a patch id.
  25.      */
  26.     public PatchIdDiffFormatter() {
  27.         super(new DigestOutputStream(NullOutputStream.INSTANCE,
  28.                 Constants.newMessageDigest()));
  29.         digest = ((DigestOutputStream) getOutputStream()).getMessageDigest();
  30.     }

  31.     /**
  32.      * Should be called after having called one of the format methods
  33.      *
  34.      * @return the patch id calculated for the provided diff.
  35.      */
  36.     public ObjectId getCalulatedPatchId() {
  37.         return ObjectId.fromRaw(digest.digest());
  38.     }

  39.     /** {@inheritDoc} */
  40.     @Override
  41.     protected void writeHunkHeader(int aStartLine, int aEndLine,
  42.             int bStartLine, int bEndLine) throws IOException {
  43.         // The hunk header is not taken into account for patch id calculation
  44.     }

  45.     /** {@inheritDoc} */
  46.     @Override
  47.     protected void formatIndexLine(OutputStream o, DiffEntry ent)
  48.             throws IOException {
  49.         // The index line is not taken into account for patch id calculation
  50.     }
  51. }