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 BlameResult} for a file path.
73   */
74  public class BlameCommand extends GitCommand<BlameResult> {
75  
76  	private String path;
77  
78  	private DiffAlgorithm diffAlgorithm;
79  
80  	private RawTextComparator textComparator;
81  
82  	private ObjectId startCommit;
83  
84  	private Collection<ObjectId> reverseEndCommits;
85  
86  	private Boolean followFileRenames;
87  
88  	/**
89  	 * @param repo
90  	 */
91  	public BlameCommand(Repository repo) {
92  		super(repo);
93  	}
94  
95  	/**
96  	 * Set file path.
97  	 *
98  	 * @param filePath
99  	 *            file path (with <code>/</code> as separator)
100 	 * @return this command
101 	 */
102 	public BlameCommand setFilePath(String filePath) {
103 		this.path = filePath;
104 		return this;
105 	}
106 
107 	/**
108 	 * Set diff algorithm
109 	 *
110 	 * @param diffAlgorithm
111 	 * @return this command
112 	 */
113 	public BlameCommand setDiffAlgorithm(DiffAlgorithm diffAlgorithm) {
114 		this.diffAlgorithm = diffAlgorithm;
115 		return this;
116 	}
117 
118 	/**
119 	 * Set raw text comparator
120 	 *
121 	 * @param textComparator
122 	 * @return this command
123 	 */
124 	public BlameCommand setTextComparator(RawTextComparator textComparator) {
125 		this.textComparator = textComparator;
126 		return this;
127 	}
128 
129 	/**
130 	 * Set start commit id
131 	 *
132 	 * @param commit
133 	 * @return this command
134 	 */
135 	public BlameCommand setStartCommit(AnyObjectId commit) {
136 		this.startCommit = commit.toObjectId();
137 		return this;
138 	}
139 
140 	/**
141 	 * Enable (or disable) following file renames.
142 	 * <p>
143 	 * If true renames are followed using the standard FollowFilter behavior
144 	 * used by RevWalk (which matches {@code git log --follow} in the C
145 	 * implementation). This is not the same as copy/move detection as
146 	 * implemented by the C implementation's of {@code git blame -M -C}.
147 	 *
148 	 * @param follow
149 	 *            enable following.
150 	 * @return {@code this}
151 	 */
152 	public BlameCommand setFollowFileRenames(boolean follow) {
153 		followFileRenames = Boolean.valueOf(follow);
154 		return this;
155 	}
156 
157 	/**
158 	 * Configure the command to compute reverse blame (history of deletes).
159 	 *
160 	 * @param start
161 	 *            oldest commit to traverse from. The result file will be loaded
162 	 *            from this commit's tree.
163 	 * @param end
164 	 *            most recent commit to stop traversal at. Usually an active
165 	 *            branch tip, tag, or HEAD.
166 	 * @return {@code this}
167 	 * @throws IOException
168 	 *             the repository cannot be read.
169 	 */
170 	public BlameCommand reverse(AnyObjectId start, AnyObjectId end)
171 			throws IOException {
172 		return reverse(start, Collections.singleton(end.toObjectId()));
173 	}
174 
175 	/**
176 	 * Configure the generator to compute reverse blame (history of deletes).
177 	 *
178 	 * @param start
179 	 *            oldest commit to traverse from. The result file will be loaded
180 	 *            from this commit's tree.
181 	 * @param end
182 	 *            most recent commits to stop traversal at. Usually an active
183 	 *            branch tip, tag, or HEAD.
184 	 * @return {@code this}
185 	 * @throws IOException
186 	 *             the repository cannot be read.
187 	 */
188 	public BlameCommand reverse(AnyObjectId start, Collection<ObjectId> end)
189 			throws IOException {
190 		startCommit = start.toObjectId();
191 		reverseEndCommits = new ArrayList<>(end);
192 		return this;
193 	}
194 
195 	/**
196 	 * Generate a list of lines with information about when the lines were
197 	 * introduced into the file path.
198 	 *
199 	 * @return list of lines
200 	 */
201 	@Override
202 	public BlameResult call() throws GitAPIException {
203 		checkCallable();
204 		try (BlameGenerator gen = new BlameGenerator(repo, path)) {
205 			if (diffAlgorithm != null)
206 				gen.setDiffAlgorithm(diffAlgorithm);
207 			if (textComparator != null)
208 				gen.setTextComparator(textComparator);
209 			if (followFileRenames != null)
210 				gen.setFollowFileRenames(followFileRenames.booleanValue());
211 
212 			if (reverseEndCommits != null)
213 				gen.reverse(startCommit, reverseEndCommits);
214 			else if (startCommit != null)
215 				gen.push(null, startCommit);
216 			else {
217 				gen.push(null, repo.resolve(Constants.HEAD));
218 				if (!repo.isBare()) {
219 					DirCache dc = repo.readDirCache();
220 					int entry = dc.findEntry(path);
221 					if (0 <= entry)
222 						gen.push(null, dc.getEntry(entry).getObjectId());
223 
224 					File inTree = new File(repo.getWorkTree(), path);
225 					if (repo.getFS().isFile(inTree)) {
226 						RawText rawText = getRawText(inTree);
227 						gen.push(null, rawText);
228 					}
229 				}
230 			}
231 			return gen.computeBlameResult();
232 		} catch (IOException e) {
233 			throw new JGitInternalException(e.getMessage(), e);
234 		}
235 	}
236 
237 	private RawText getRawText(File inTree) throws IOException,
238 			FileNotFoundException {
239 		RawText rawText;
240 
241 		WorkingTreeOptions workingTreeOptions = getRepository().getConfig()
242 				.get(WorkingTreeOptions.KEY);
243 		AutoCRLF autoCRLF = workingTreeOptions.getAutoCRLF();
244 		switch (autoCRLF) {
245 		case FALSE:
246 		case INPUT:
247 			// Git used the repo format on checkout, but other tools
248 			// may change the format to CRLF. We ignore that here.
249 			rawText = new RawText(inTree);
250 			break;
251 		case TRUE:
252 			try (AutoLFInputStream in = new AutoLFInputStream(
253 					new FileInputStream(inTree), true)) {
254 				// Canonicalization should lead to same or shorter length
255 				// (CRLF to LF), so the file size on disk is an upper size bound
256 				rawText = new RawText(toByteArray(in, (int) inTree.length()));
257 			}
258 			break;
259 		default:
260 			throw new IllegalArgumentException(
261 					"Unknown autocrlf option " + autoCRLF); //$NON-NLS-1$
262 		}
263 		return rawText;
264 	}
265 
266 	private static byte[] toByteArray(InputStream source, int upperSizeLimit)
267 			throws IOException {
268 		byte[] buffer = new byte[upperSizeLimit];
269 		try {
270 			int read = IO.readFully(source, buffer, 0);
271 			if (read == upperSizeLimit)
272 				return buffer;
273 			else {
274 				byte[] copy = new byte[read];
275 				System.arraycopy(buffer, 0, copy, 0, read);
276 				return copy;
277 			}
278 		} finally {
279 			source.close();
280 		}
281 	}
282 }