View Javadoc
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  
12  import java.io.IOException;
13  import java.io.OutputStream;
14  import java.security.DigestOutputStream;
15  import java.security.MessageDigest;
16  
17  import org.eclipse.jgit.lib.Constants;
18  import org.eclipse.jgit.lib.ObjectId;
19  import org.eclipse.jgit.util.io.NullOutputStream;
20  
21  /**
22   * A DiffFormatter used to calculate the patch-id of the diff.
23   */
24  public class PatchIdDiffFormatter extends DiffFormatter {
25  
26  	private final MessageDigest digest;
27  
28  	/**
29  	 * Initialize a formatter to compute a patch id.
30  	 */
31  	public PatchIdDiffFormatter() {
32  		super(new DigestOutputStream(NullOutputStream.INSTANCE,
33  				Constants.newMessageDigest()));
34  		digest = ((DigestOutputStream) getOutputStream()).getMessageDigest();
35  	}
36  
37  	/**
38  	 * Should be called after having called one of the format methods
39  	 *
40  	 * @return the patch id calculated for the provided diff.
41  	 */
42  	public ObjectId getCalulatedPatchId() {
43  		return ObjectId.fromRaw(digest.digest());
44  	}
45  
46  	/** {@inheritDoc} */
47  	@Override
48  	protected void writeHunkHeader(int aStartLine, int aEndLine,
49  			int bStartLine, int bEndLine) throws IOException {
50  		// The hunk header is not taken into account for patch id calculation
51  	}
52  
53  	/** {@inheritDoc} */
54  	@Override
55  	protected void formatIndexLine(OutputStream o, DiffEntry ent)
56  			throws IOException {
57  		// The index line is not taken into account for patch id calculation
58  	}
59  }