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