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