View Javadoc
1   /*
2    * Copyright (C) 2008, Google 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  
44  package org.eclipse.jgit.transport;
45  
46  import static org.eclipse.jgit.transport.ReceiveCommand.Result.NOT_ATTEMPTED;
47  import static org.eclipse.jgit.transport.ReceiveCommand.Result.REJECTED_OTHER_REASON;
48  
49  import java.io.IOException;
50  import java.text.MessageFormat;
51  import java.util.ArrayList;
52  import java.util.Collection;
53  import java.util.List;
54  
55  import org.eclipse.jgit.internal.JGitText;
56  import org.eclipse.jgit.lib.AnyObjectId;
57  import org.eclipse.jgit.lib.ObjectId;
58  import org.eclipse.jgit.lib.Ref;
59  import org.eclipse.jgit.lib.RefUpdate;
60  import org.eclipse.jgit.revwalk.RevCommit;
61  import org.eclipse.jgit.revwalk.RevObject;
62  import org.eclipse.jgit.revwalk.RevWalk;
63  
64  /**
65   * A command being processed by {@link BaseReceivePack}.
66   * <p>
67   * This command instance roughly translates to the server side representation of
68   * the {@link RemoteRefUpdate} created by the client.
69   */
70  public class ReceiveCommand {
71  	/** Type of operation requested. */
72  	public static enum Type {
73  		/** Create a new ref; the ref must not already exist. */
74  		CREATE,
75  
76  		/**
77  		 * Update an existing ref with a fast-forward update.
78  		 * <p>
79  		 * During a fast-forward update no changes will be lost; only new
80  		 * commits are inserted into the ref.
81  		 */
82  		UPDATE,
83  
84  		/**
85  		 * Update an existing ref by potentially discarding objects.
86  		 * <p>
87  		 * The current value of the ref is not fully reachable from the new
88  		 * value of the ref, so a successful command may result in one or more
89  		 * objects becoming unreachable.
90  		 */
91  		UPDATE_NONFASTFORWARD,
92  
93  		/** Delete an existing ref; the ref should already exist. */
94  		DELETE;
95  	}
96  
97  	/** Result of the update command. */
98  	public static enum Result {
99  		/** The command has not yet been attempted by the server. */
100 		NOT_ATTEMPTED,
101 
102 		/** The server is configured to deny creation of this ref. */
103 		REJECTED_NOCREATE,
104 
105 		/** The server is configured to deny deletion of this ref. */
106 		REJECTED_NODELETE,
107 
108 		/** The update is a non-fast-forward update and isn't permitted. */
109 		REJECTED_NONFASTFORWARD,
110 
111 		/** The update affects <code>HEAD</code> and cannot be permitted. */
112 		REJECTED_CURRENT_BRANCH,
113 
114 		/**
115 		 * One or more objects aren't in the repository.
116 		 * <p>
117 		 * This is severe indication of either repository corruption on the
118 		 * server side, or a bug in the client wherein the client did not supply
119 		 * all required objects during the pack transfer.
120 		 */
121 		REJECTED_MISSING_OBJECT,
122 
123 		/** Other failure; see {@link ReceiveCommand#getMessage()}. */
124 		REJECTED_OTHER_REASON,
125 
126 		/** The ref could not be locked and updated atomically; try again. */
127 		LOCK_FAILURE,
128 
129 		/** The change was completed successfully. */
130 		OK;
131 	}
132 
133 	/**
134 	 * Filter a collection of commands according to result.
135 	 *
136 	 * @param in
137 	 *            commands to filter.
138 	 * @param want
139 	 *            desired status to filter by.
140 	 * @return a copy of the command list containing only those commands with
141 	 *         the desired status.
142 	 * @since 4.2
143 	 */
144 	public static List<ReceiveCommand> filter(Iterable<ReceiveCommand> in,
145 			Result want) {
146 		List<ReceiveCommand> r;
147 		if (in instanceof Collection)
148 			r = new ArrayList<>(((Collection<?>) in).size());
149 		else
150 			r = new ArrayList<>();
151 		for (ReceiveCommand cmd : in) {
152 			if (cmd.getResult() == want)
153 				r.add(cmd);
154 		}
155 		return r;
156 	}
157 
158 	/**
159 	 * Filter a list of commands according to result.
160 	 *
161 	 * @param commands
162 	 *            commands to filter.
163 	 * @param want
164 	 *            desired status to filter by.
165 	 * @return a copy of the command list containing only those commands with
166 	 *         the desired status.
167 	 * @since 2.0
168 	 */
169 	public static List<ReceiveCommand> filter(List<ReceiveCommand> commands,
170 			Result want) {
171 		return filter((Iterable<ReceiveCommand>) commands, want);
172 	}
173 
174 	/**
175 	 * Set unprocessed commands as failed due to transaction aborted.
176 	 * <p>
177 	 * If a command is still {@link Result#NOT_ATTEMPTED} it will be set to
178 	 * {@link Result#REJECTED_OTHER_REASON}.
179 	 *
180 	 * @param commands
181 	 *            commands to mark as failed.
182 	 * @since 4.2
183 	 */
184 	public static void abort(Iterable<ReceiveCommand> commands) {
185 		for (ReceiveCommand c : commands) {
186 			if (c.getResult() == NOT_ATTEMPTED) {
187 				c.setResult(REJECTED_OTHER_REASON,
188 						JGitText.get().transactionAborted);
189 			}
190 		}
191 	}
192 
193 	private final ObjectId oldId;
194 
195 	private final ObjectId newId;
196 
197 	private final String name;
198 
199 	private Type type;
200 
201 	private Ref ref;
202 
203 	private Result status = Result.NOT_ATTEMPTED;
204 
205 	private String message;
206 
207 	private boolean typeIsCorrect;
208 
209 	/**
210 	 * Create a new command for {@link BaseReceivePack}.
211 	 *
212 	 * @param oldId
213 	 *            the old object id; must not be null. Use
214 	 *            {@link ObjectId#zeroId()} to indicate a ref creation.
215 	 * @param newId
216 	 *            the new object id; must not be null. Use
217 	 *            {@link ObjectId#zeroId()} to indicate a ref deletion.
218 	 * @param name
219 	 *            name of the ref being affected.
220 	 */
221 	public ReceiveCommand(final ObjectId oldId, final ObjectId newId,
222 			final String name) {
223 		this.oldId = oldId;
224 		this.newId = newId;
225 		this.name = name;
226 
227 		type = Type.UPDATE;
228 		if (ObjectId.zeroId().equals(oldId))
229 			type = Type.CREATE;
230 		if (ObjectId.zeroId().equals(newId))
231 			type = Type.DELETE;
232 	}
233 
234 	/**
235 	 * Create a new command for {@link BaseReceivePack}.
236 	 *
237 	 * @param oldId
238 	 *            the old object id; must not be null. Use
239 	 *            {@link ObjectId#zeroId()} to indicate a ref creation.
240 	 * @param newId
241 	 *            the new object id; must not be null. Use
242 	 *            {@link ObjectId#zeroId()} to indicate a ref deletion.
243 	 * @param name
244 	 *            name of the ref being affected.
245 	 * @param type
246 	 *            type of the command.
247 	 * @since 2.0
248 	 */
249 	public ReceiveCommand(final ObjectId oldId, final ObjectId newId,
250 			final String name, final Type type) {
251 		this.oldId = oldId;
252 		this.newId = newId;
253 		this.name = name;
254 		this.type = type;
255 	}
256 
257 	/** @return the old value the client thinks the ref has. */
258 	public ObjectId getOldId() {
259 		return oldId;
260 	}
261 
262 	/** @return the requested new value for this ref. */
263 	public ObjectId getNewId() {
264 		return newId;
265 	}
266 
267 	/** @return the name of the ref being updated. */
268 	public String getRefName() {
269 		return name;
270 	}
271 
272 	/** @return the type of this command; see {@link Type}. */
273 	public Type getType() {
274 		return type;
275 	}
276 
277 	/** @return the ref, if this was advertised by the connection. */
278 	public Ref getRef() {
279 		return ref;
280 	}
281 
282 	/** @return the current status code of this command. */
283 	public Result getResult() {
284 		return status;
285 	}
286 
287 	/** @return the message associated with a failure status. */
288 	public String getMessage() {
289 		return message;
290 	}
291 
292 	/**
293 	 * Set the status of this command.
294 	 *
295 	 * @param s
296 	 *            the new status code for this command.
297 	 */
298 	public void setResult(final Result s) {
299 		setResult(s, null);
300 	}
301 
302 	/**
303 	 * Set the status of this command.
304 	 *
305 	 * @param s
306 	 *            new status code for this command.
307 	 * @param m
308 	 *            optional message explaining the new status.
309 	 */
310 	public void setResult(final Result s, final String m) {
311 		status = s;
312 		message = m;
313 	}
314 
315 	/**
316 	 * Update the type of this command by checking for fast-forward.
317 	 * <p>
318 	 * If the command's current type is UPDATE, a merge test will be performed
319 	 * using the supplied RevWalk to determine if {@link #getOldId()} is fully
320 	 * merged into {@link #getNewId()}. If some commits are not merged the
321 	 * update type is changed to {@link Type#UPDATE_NONFASTFORWARD}.
322 	 *
323 	 * @param walk
324 	 *            an instance to perform the merge test with. The caller must
325 	 *            allocate and release this object.
326 	 * @throws IOException
327 	 *             either oldId or newId is not accessible in the repository
328 	 *             used by the RevWalk. This usually indicates data corruption,
329 	 *             and the command cannot be processed.
330 	 */
331 	public void updateType(RevWalk walk) throws IOException {
332 		if (typeIsCorrect)
333 			return;
334 		if (type == Type.UPDATE && !AnyObjectId.equals(oldId, newId)) {
335 			RevObject o = walk.parseAny(oldId);
336 			RevObject n = walk.parseAny(newId);
337 			if (!(o instanceof RevCommit)
338 					|| !(n instanceof RevCommit)
339 					|| !walk.isMergedInto((RevCommit) o, (RevCommit) n))
340 				setType(Type.UPDATE_NONFASTFORWARD);
341 		}
342 		typeIsCorrect = true;
343 	}
344 
345 	/**
346 	 * Execute this command during a receive-pack session.
347 	 * <p>
348 	 * Sets the status of the command as a side effect.
349 	 *
350 	 * @param rp
351 	 *            receive-pack session.
352 	 * @since 2.0
353 	 */
354 	public void execute(final BaseReceivePack rp) {
355 		try {
356 			final RefUpdate ru = rp.getRepository().updateRef(getRefName());
357 			ru.setRefLogIdent(rp.getRefLogIdent());
358 			switch (getType()) {
359 			case DELETE:
360 				if (!ObjectId.zeroId().equals(getOldId())) {
361 					// We can only do a CAS style delete if the client
362 					// didn't bork its delete request by sending the
363 					// wrong zero id rather than the advertised one.
364 					//
365 					ru.setExpectedOldObjectId(getOldId());
366 				}
367 				ru.setForceUpdate(true);
368 				setResult(ru.delete(rp.getRevWalk()));
369 				break;
370 
371 			case CREATE:
372 			case UPDATE:
373 			case UPDATE_NONFASTFORWARD:
374 				ru.setForceUpdate(rp.isAllowNonFastForwards());
375 				ru.setExpectedOldObjectId(getOldId());
376 				ru.setNewObjectId(getNewId());
377 				ru.setRefLogMessage("push", true); //$NON-NLS-1$
378 				setResult(ru.update(rp.getRevWalk()));
379 				break;
380 			}
381 		} catch (IOException err) {
382 			reject(err);
383 		}
384 	}
385 
386 	void setRef(final Ref r) {
387 		ref = r;
388 	}
389 
390 	void setType(final Type t) {
391 		type = t;
392 	}
393 
394 	void setTypeFastForwardUpdate() {
395 		type = Type.UPDATE;
396 		typeIsCorrect = true;
397 	}
398 
399 	/**
400 	 * Set the result of this command.
401 	 *
402 	 * @param r
403 	 *            the new result code for this command.
404 	 */
405 	public void setResult(RefUpdate.Result r) {
406 		switch (r) {
407 		case NOT_ATTEMPTED:
408 			setResult(Result.NOT_ATTEMPTED);
409 			break;
410 
411 		case LOCK_FAILURE:
412 		case IO_FAILURE:
413 			setResult(Result.LOCK_FAILURE);
414 			break;
415 
416 		case NO_CHANGE:
417 		case NEW:
418 		case FORCED:
419 		case FAST_FORWARD:
420 			setResult(Result.OK);
421 			break;
422 
423 		case REJECTED:
424 			setResult(Result.REJECTED_NONFASTFORWARD);
425 			break;
426 
427 		case REJECTED_CURRENT_BRANCH:
428 			setResult(Result.REJECTED_CURRENT_BRANCH);
429 			break;
430 
431 		default:
432 			setResult(Result.REJECTED_OTHER_REASON, r.name());
433 			break;
434 		}
435 	}
436 
437 	void reject(IOException err) {
438 		setResult(Result.REJECTED_OTHER_REASON, MessageFormat.format(
439 				JGitText.get().lockError, err.getMessage()));
440 	}
441 
442 	@SuppressWarnings("nls")
443 	@Override
444 	public String toString() {
445 		return getType().name() + ": " + getOldId().name() + " "
446 				+ getNewId().name() + " " + getRefName();
447 	}
448 }