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 org.eclipse.jgit.lib.Constants.CHARSET;
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 				// successfully parsed as non-comment line
141 				// mark this line as a comment explicitly
142 				line.setAction(Action.COMMENT);
143 				// use the read line as comment string
144 				line.setComment(commentString);
145 			}
146 		} catch (Exception e) {
147 			// parsing as non-comment line failed
148 			line = null;
149 		} finally {
150 			if (line == null)
151 				line = new RebaseTodoLine(commentString);
152 			r.add(line);
153 		}
154 	}
155 
156 	/**
157 	 * Skip leading space, tab, CR and LF characters
158 	 *
159 	 * @param buf
160 	 * @param tokenBegin
161 	 * @param lineEnd
162 	 * @return the token within the range of the given {@code buf} that doesn't
163 	 *         need to be skipped, {@code -1} if no such token found within the
164 	 *         range (i.e. empty line)
165 	 */
166 	private static int nextParsableToken(byte[] buf, int tokenBegin, int lineEnd) {
167 		while (tokenBegin <= lineEnd
168 				&& (buf[tokenBegin] == ' ' || buf[tokenBegin] == '\t' || buf[tokenBegin] == '\r'))
169 			tokenBegin++;
170 		if (tokenBegin > lineEnd)
171 			return -1;
172 		return tokenBegin;
173 	}
174 
175 	private static RebaseTodoLine parseLine(byte[] buf, int tokenBegin,
176 			int lineEnd) {
177 		RebaseTodoLine.Action action = null;
178 		AbbreviatedObjectId commit = null;
179 
180 		int nextSpace = RawParseUtils.next(buf, tokenBegin, ' ');
181 		int tokenCount = 0;
182 		while (tokenCount < 3 && nextSpace < lineEnd) {
183 			switch (tokenCount) {
184 			case 0:
185 				String actionToken = new String(buf, tokenBegin,
186 						nextSpace - tokenBegin - 1, CHARSET);
187 				tokenBegin = nextSpace;
188 				action = RebaseTodoLine.Action.parse(actionToken);
189 				if (action == null)
190 					return null; // parsing failed
191 				break;
192 			case 1:
193 				nextSpace = RawParseUtils.next(buf, tokenBegin, ' ');
194 				String commitToken = new String(buf, tokenBegin,
195 						nextSpace - tokenBegin - 1, CHARSET);
196 				tokenBegin = nextSpace;
197 				commit = AbbreviatedObjectId.fromString(commitToken);
198 				break;
199 			case 2:
200 				return new RebaseTodoLine(action, commit,
201 						RawParseUtils.decode(buf, tokenBegin, 1 + lineEnd));
202 			}
203 			tokenCount++;
204 		}
205 		if (tokenCount == 2)
206 			return new RebaseTodoLine(action, commit, ""); //$NON-NLS-1$
207 		return null;
208 	}
209 
210 	/**
211 	 * Write a file formatted like a git-rebase-todo file.
212 	 *
213 	 * @param path
214 	 *            path to the file relative to the repository's git-dir. E.g.
215 	 *            "rebase-merge/git-rebase-todo" or "rebase-append/done"
216 	 * @param steps
217 	 *            the steps to be written
218 	 * @param append
219 	 *            whether to append to an existing file or to write a new file
220 	 * @throws java.io.IOException
221 	 */
222 	public void writeRebaseTodoFile(String path, List<RebaseTodoLine> steps,
223 			boolean append) throws IOException {
224 		try (OutputStream fw = new BufferedOutputStream(new FileOutputStream(
225 				new File(repo.getDirectory(), path), append))) {
226 			StringBuilder sb = new StringBuilder();
227 			for (RebaseTodoLine step : steps) {
228 				sb.setLength(0);
229 				if (RebaseTodoLine.Action.COMMENT.equals(step.action))
230 					sb.append(step.getComment());
231 				else {
232 					sb.append(step.getAction().toToken());
233 					sb.append(" "); //$NON-NLS-1$
234 					sb.append(step.getCommit().name());
235 					sb.append(" "); //$NON-NLS-1$
236 					sb.append(step.getShortMessage().trim());
237 				}
238 				sb.append('\n');
239 				fw.write(Constants.encode(sb.toString()));
240 			}
241 		}
242 	}
243 }