View Javadoc
1   /*
2    * Copyright (C) 2011, GitHub Inc.
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  package org.eclipse.jgit.api;
44  
45  import java.io.File;
46  import java.io.FileInputStream;
47  import java.io.FileNotFoundException;
48  import java.io.IOException;
49  import java.io.InputStream;
50  import java.util.ArrayList;
51  import java.util.Collection;
52  import java.util.Collections;
53  
54  import org.eclipse.jgit.api.errors.GitAPIException;
55  import org.eclipse.jgit.api.errors.JGitInternalException;
56  import org.eclipse.jgit.blame.BlameGenerator;
57  import org.eclipse.jgit.blame.BlameResult;
58  import org.eclipse.jgit.diff.DiffAlgorithm;
59  import org.eclipse.jgit.diff.RawText;
60  import org.eclipse.jgit.diff.RawTextComparator;
61  import org.eclipse.jgit.dircache.DirCache;
62  import org.eclipse.jgit.lib.AnyObjectId;
63  import org.eclipse.jgit.lib.Constants;
64  import org.eclipse.jgit.lib.CoreConfig.AutoCRLF;
65  import org.eclipse.jgit.lib.ObjectId;
66  import org.eclipse.jgit.lib.Repository;
67  import org.eclipse.jgit.treewalk.WorkingTreeOptions;
68  import org.eclipse.jgit.util.IO;
69  import org.eclipse.jgit.util.io.AutoLFInputStream;
70  
71  /**
72   * Blame command for building a {@link org.eclipse.jgit.blame.BlameResult} for a
73   * file path.
74   */
75  public class BlameCommand extends GitCommand<BlameResult> {
76  
77  	private String path;
78  
79  	private DiffAlgorithm diffAlgorithm;
80  
81  	private RawTextComparator textComparator;
82  
83  	private ObjectId startCommit;
84  
85  	private Collection<ObjectId> reverseEndCommits;
86  
87  	private Boolean followFileRenames;
88  
89  	/**
90  	 * Constructor for BlameCommand
91  	 *
92  	 * @param repo
93  	 *            the {@link org.eclipse.jgit.lib.Repository}
94  	 */
95  	public BlameCommand(Repository repo) {
96  		super(repo);
97  	}
98  
99  	/**
100 	 * Set file path.
101 	 *
102 	 * @param filePath
103 	 *            file path (with <code>/</code> as separator)
104 	 * @return this command
105 	 */
106 	public BlameCommand setFilePath(String filePath) {
107 		this.path = filePath;
108 		return this;
109 	}
110 
111 	/**
112 	 * Set diff algorithm
113 	 *
114 	 * @param diffAlgorithm
115 	 *            a {@link org.eclipse.jgit.diff.DiffAlgorithm} object.
116 	 * @return this command
117 	 */
118 	public BlameCommand setDiffAlgorithm(DiffAlgorithm diffAlgorithm) {
119 		this.diffAlgorithm = diffAlgorithm;
120 		return this;
121 	}
122 
123 	/**
124 	 * Set raw text comparator
125 	 *
126 	 * @param textComparator
127 	 *            a {@link org.eclipse.jgit.diff.RawTextComparator}
128 	 * @return this command
129 	 */
130 	public BlameCommand setTextComparator(RawTextComparator textComparator) {
131 		this.textComparator = textComparator;
132 		return this;
133 	}
134 
135 	/**
136 	 * Set start commit id
137 	 *
138 	 * @param commit
139 	 *            id of a commit
140 	 * @return this command
141 	 */
142 	public BlameCommand setStartCommit(AnyObjectId commit) {
143 		this.startCommit = commit.toObjectId();
144 		return this;
145 	}
146 
147 	/**
148 	 * Enable (or disable) following file renames.
149 	 * <p>
150 	 * If true renames are followed using the standard FollowFilter behavior
151 	 * used by RevWalk (which matches {@code git log --follow} in the C
152 	 * implementation). This is not the same as copy/move detection as
153 	 * implemented by the C implementation's of {@code git blame -M -C}.
154 	 *
155 	 * @param follow
156 	 *            enable following.
157 	 * @return {@code this}
158 	 */
159 	public BlameCommand setFollowFileRenames(boolean follow) {
160 		followFileRenames = Boolean.valueOf(follow);
161 		return this;
162 	}
163 
164 	/**
165 	 * Configure the command to compute reverse blame (history of deletes).
166 	 *
167 	 * @param start
168 	 *            oldest commit to traverse from. The result file will be loaded
169 	 *            from this commit's tree.
170 	 * @param end
171 	 *            most recent commit to stop traversal at. Usually an active
172 	 *            branch tip, tag, or HEAD.
173 	 * @return {@code this}
174 	 * @throws java.io.IOException
175 	 *             the repository cannot be read.
176 	 */
177 	public BlameCommand reverse(AnyObjectId/../../../org/eclipse/jgit/lib/AnyObjectId.html#AnyObjectId">AnyObjectId start, AnyObjectId end)
178 			throws IOException {
179 		return reverse(start, Collections.singleton(end.toObjectId()));
180 	}
181 
182 	/**
183 	 * Configure the generator to compute reverse blame (history of deletes).
184 	 *
185 	 * @param start
186 	 *            oldest commit to traverse from. The result file will be loaded
187 	 *            from this commit's tree.
188 	 * @param end
189 	 *            most recent commits to stop traversal at. Usually an active
190 	 *            branch tip, tag, or HEAD.
191 	 * @return {@code this}
192 	 * @throws java.io.IOException
193 	 *             the repository cannot be read.
194 	 */
195 	public BlameCommand reverse(AnyObjectId start, Collection<ObjectId> end)
196 			throws IOException {
197 		startCommit = start.toObjectId();
198 		reverseEndCommits = new ArrayList<>(end);
199 		return this;
200 	}
201 
202 	/**
203 	 * {@inheritDoc}
204 	 * <p>
205 	 * Generate a list of lines with information about when the lines were
206 	 * introduced into the file path.
207 	 */
208 	@Override
209 	public BlameResult call() throws GitAPIException {
210 		checkCallable();
211 		try (BlameGeneratorator.html#BlameGenerator">BlameGenerator gen = new BlameGenerator(repo, path)) {
212 			if (diffAlgorithm != null)
213 				gen.setDiffAlgorithm(diffAlgorithm);
214 			if (textComparator != null)
215 				gen.setTextComparator(textComparator);
216 			if (followFileRenames != null)
217 				gen.setFollowFileRenames(followFileRenames.booleanValue());
218 
219 			if (reverseEndCommits != null)
220 				gen.reverse(startCommit, reverseEndCommits);
221 			else if (startCommit != null)
222 				gen.push(null, startCommit);
223 			else {
224 				gen.push(null, repo.resolve(Constants.HEAD));
225 				if (!repo.isBare()) {
226 					DirCache dc = repo.readDirCache();
227 					int entry = dc.findEntry(path);
228 					if (0 <= entry)
229 						gen.push(null, dc.getEntry(entry).getObjectId());
230 
231 					File inTree = new File(repo.getWorkTree(), path);
232 					if (repo.getFS().isFile(inTree)) {
233 						RawText rawText = getRawText(inTree);
234 						gen.push(null, rawText);
235 					}
236 				}
237 			}
238 			return gen.computeBlameResult();
239 		} catch (IOException e) {
240 			throw new JGitInternalException(e.getMessage(), e);
241 		}
242 	}
243 
244 	private RawText getRawText(File inTree) throws IOException,
245 			FileNotFoundException {
246 		RawText rawText;
247 
248 		WorkingTreeOptions workingTreeOptions = getRepository().getConfig()
249 				.get(WorkingTreeOptions.KEY);
250 		AutoCRLF autoCRLF = workingTreeOptions.getAutoCRLF();
251 		switch (autoCRLF) {
252 		case FALSE:
253 		case INPUT:
254 			// Git used the repo format on checkout, but other tools
255 			// may change the format to CRLF. We ignore that here.
256 			rawText = new RawText(inTree);
257 			break;
258 		case TRUE:
259 			try (AutoLFInputStreamtStream.html#AutoLFInputStream">AutoLFInputStream in = new AutoLFInputStream(
260 					new FileInputStream(inTree), true)) {
261 				// Canonicalization should lead to same or shorter length
262 				// (CRLF to LF), so the file size on disk is an upper size bound
263 				rawText = new RawText(toByteArray(in, (int) inTree.length()));
264 			}
265 			break;
266 		default:
267 			throw new IllegalArgumentException(
268 					"Unknown autocrlf option " + autoCRLF); //$NON-NLS-1$
269 		}
270 		return rawText;
271 	}
272 
273 	private static byte[] toByteArray(InputStream source, int upperSizeLimit)
274 			throws IOException {
275 		byte[] buffer = new byte[upperSizeLimit];
276 		try {
277 			int read = IO.readFully(source, buffer, 0);
278 			if (read == upperSizeLimit)
279 				return buffer;
280 			else {
281 				byte[] copy = new byte[read];
282 				System.arraycopy(buffer, 0, copy, 0, read);
283 				return copy;
284 			}
285 		} finally {
286 			source.close();
287 		}
288 	}
289 }