View Javadoc
1   /*
2    * Copyright (C) 2013, Christian Halstrick <christian.halstrick@sap.com>
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  
44  package org.eclipse.jgit.lib;
45  
46  import static java.nio.charset.StandardCharsets.UTF_8;
47  
48  import java.io.BufferedOutputStream;
49  import java.io.File;
50  import java.io.FileOutputStream;
51  import java.io.IOException;
52  import java.io.OutputStream;
53  import java.util.LinkedList;
54  import java.util.List;
55  
56  import org.eclipse.jgit.lib.RebaseTodoLine.Action;
57  import org.eclipse.jgit.util.IO;
58  import org.eclipse.jgit.util.RawParseUtils;
59  
60  /**
61   * Offers methods to read and write files formatted like the git-rebase-todo
62   * file
63   *
64   * @since 3.2
65   */
66  public class RebaseTodoFile {
67  	private Repository repo;
68  
69  	/**
70  	 * Constructor for RebaseTodoFile.
71  	 *
72  	 * @param repo
73  	 *            a {@link org.eclipse.jgit.lib.Repository} object.
74  	 */
75  	public RebaseTodoFile(Repository repo) {
76  		this.repo = repo;
77  	}
78  
79  	/**
80  	 * Read a file formatted like the git-rebase-todo file. The "done" file is
81  	 * also formatted like the git-rebase-todo file. These files can be found in
82  	 * .git/rebase-merge/ or .git/rebase-append/ folders.
83  	 *
84  	 * @param path
85  	 *            path to the file relative to the repository's git-dir. E.g.
86  	 *            "rebase-merge/git-rebase-todo" or "rebase-append/done"
87  	 * @param includeComments
88  	 *            <code>true</code> if also comments should be reported
89  	 * @return the list of steps
90  	 * @throws java.io.IOException
91  	 */
92  	public List<RebaseTodoLine> readRebaseTodo(String path,
93  			boolean includeComments) throws IOException {
94  		byte[] buf = IO.readFully(new File(repo.getDirectory(), path));
95  		int ptr = 0;
96  		int tokenBegin = 0;
97  		List<RebaseTodoLine> r = new LinkedList<>();
98  		while (ptr < buf.length) {
99  			tokenBegin = ptr;
100 			ptr = RawParseUtils.nextLF(buf, ptr);
101 			int lineStart = tokenBegin;
102 			int lineEnd = ptr - 2;
103 			if (lineEnd >= 0 && buf[lineEnd] == '\r')
104 				lineEnd--;
105 			// Handle comments
106 			if (buf[tokenBegin] == '#') {
107 				if (includeComments)
108 					parseComments(buf, tokenBegin, r, lineEnd);
109 			} else {
110 				// skip leading spaces+tabs+cr
111 				tokenBegin = nextParsableToken(buf, tokenBegin, lineEnd);
112 				// Handle empty lines (maybe empty after skipping leading
113 				// whitespace)
114 				if (tokenBegin == -1) {
115 					if (includeComments)
116 						r.add(new RebaseTodoLine(RawParseUtils.decode(buf,
117 								lineStart, 1 + lineEnd)));
118 					continue;
119 				}
120 				RebaseTodoLine line = parseLine(buf, tokenBegin, lineEnd);
121 				if (line == null)
122 					continue;
123 				r.add(line);
124 			}
125 		}
126 		return r;
127 	}
128 
129 	private static void parseComments(byte[] buf, int tokenBegin,
130 			List<RebaseTodoLine> r, int lineEnd) {
131 		RebaseTodoLine line = null;
132 		String commentString = RawParseUtils.decode(buf,
133 				tokenBegin, lineEnd + 1);
134 		try {
135 			int skip = tokenBegin + 1; // skip '#'
136 			skip = nextParsableToken(buf, skip, lineEnd);
137 			if (skip != -1) {
138 				// try to parse the line as non-comment
139 				line = parseLine(buf, skip, lineEnd);
140 				if (line != null) {
141 					// successfully parsed as non-comment line
142 					// mark this line as a comment explicitly
143 					line.setAction(Action.COMMENT);
144 					// use the read line as comment string
145 					line.setComment(commentString);
146 				}
147 			}
148 		} catch (Exception e) {
149 			// parsing as non-comment line failed
150 			line = null;
151 		} finally {
152 			if (line == null)
153 				line = new RebaseTodoLine(commentString);
154 			r.add(line);
155 		}
156 	}
157 
158 	/**
159 	 * Skip leading space, tab, CR and LF characters
160 	 *
161 	 * @param buf
162 	 * @param tokenBegin
163 	 * @param lineEnd
164 	 * @return the token within the range of the given {@code buf} that doesn't
165 	 *         need to be skipped, {@code -1} if no such token found within the
166 	 *         range (i.e. empty line)
167 	 */
168 	private static int nextParsableToken(byte[] buf, int tokenBegin, int lineEnd) {
169 		while (tokenBegin <= lineEnd
170 				&& (buf[tokenBegin] == ' ' || buf[tokenBegin] == '\t' || buf[tokenBegin] == '\r'))
171 			tokenBegin++;
172 		if (tokenBegin > lineEnd)
173 			return -1;
174 		return tokenBegin;
175 	}
176 
177 	private static RebaseTodoLine parseLine(byte[] buf, int tokenBegin,
178 			int lineEnd) {
179 		RebaseTodoLine.Action action = null;
180 		AbbreviatedObjectId commit = null;
181 
182 		int nextSpace = RawParseUtils.next(buf, tokenBegin, ' ');
183 		int tokenCount = 0;
184 		while (tokenCount < 3 && nextSpace <= lineEnd) {
185 			switch (tokenCount) {
186 			case 0:
187 				String actionToken = new String(buf, tokenBegin,
188 						nextSpace - tokenBegin - 1, UTF_8);
189 				tokenBegin = nextSpace;
190 				action = RebaseTodoLine.Action.parse(actionToken);
191 				if (action == null)
192 					return null; // parsing failed
193 				break;
194 			case 1:
195 				nextSpace = RawParseUtils.next(buf, tokenBegin, ' ');
196 				String commitToken;
197 				if (nextSpace > lineEnd + 1) {
198 					commitToken = new String(buf, tokenBegin,
199 							lineEnd - tokenBegin + 1, UTF_8);
200 				} else {
201 					commitToken = new String(buf, tokenBegin,
202 							nextSpace - tokenBegin - 1, UTF_8);
203 				}
204 				tokenBegin = nextSpace;
205 				commit = AbbreviatedObjectId.fromString(commitToken);
206 				break;
207 			case 2:
208 				return new RebaseTodoLine(action, commit,
209 						RawParseUtils.decode(buf, tokenBegin, 1 + lineEnd));
210 			}
211 			tokenCount++;
212 		}
213 		if (tokenCount == 2)
214 			return new RebaseTodoLine(action, commit, ""); //$NON-NLS-1$
215 		return null;
216 	}
217 
218 	/**
219 	 * Write a file formatted like a git-rebase-todo file.
220 	 *
221 	 * @param path
222 	 *            path to the file relative to the repository's git-dir. E.g.
223 	 *            "rebase-merge/git-rebase-todo" or "rebase-append/done"
224 	 * @param steps
225 	 *            the steps to be written
226 	 * @param append
227 	 *            whether to append to an existing file or to write a new file
228 	 * @throws java.io.IOException
229 	 */
230 	public void writeRebaseTodoFile(String path, List<RebaseTodoLine> steps,
231 			boolean append) throws IOException {
232 		try (OutputStream fw = new BufferedOutputStream(new FileOutputStream(
233 				new File(repo.getDirectory(), path), append))) {
234 			StringBuilder sb = new StringBuilder();
235 			for (RebaseTodoLine step : steps) {
236 				sb.setLength(0);
237 				if (RebaseTodoLine.Action.COMMENT.equals(step.action))
238 					sb.append(step.getComment());
239 				else {
240 					sb.append(step.getAction().toToken());
241 					sb.append(" "); //$NON-NLS-1$
242 					sb.append(step.getCommit().name());
243 					sb.append(" "); //$NON-NLS-1$
244 					sb.append(step.getShortMessage().trim());
245 				}
246 				sb.append('\n');
247 				fw.write(Constants.encode(sb.toString()));
248 			}
249 		}
250 	}
251 }