Simplify the PackWriter.preparePack() API
[jgit.git] / org.spearce.jgit / src / org / spearce / jgit / transport / WalkPushConnection.java
blobacdb5b8bf908041f1f0ba4cb758ef6fff5b8603d
1 /*
2 * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
4 * All rights reserved.
6 * Redistribution and use in source and binary forms, with or
7 * without modification, are permitted provided that the following
8 * conditions are met:
10 * - Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
13 * - Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * - Neither the name of the Git Development Community nor the
19 * names of its contributors may be used to endorse or promote
20 * products derived from this software without specific prior
21 * written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
24 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
25 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
28 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
33 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
35 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 package org.spearce.jgit.transport;
40 import static org.spearce.jgit.transport.WalkRemoteObjectDatabase.ROOT_DIR;
42 import java.io.IOException;
43 import java.io.OutputStream;
44 import java.util.ArrayList;
45 import java.util.Collection;
46 import java.util.LinkedHashMap;
47 import java.util.List;
48 import java.util.Map;
49 import java.util.TreeMap;
51 import org.spearce.jgit.errors.TransportException;
52 import org.spearce.jgit.lib.AnyObjectId;
53 import org.spearce.jgit.lib.Constants;
54 import org.spearce.jgit.lib.ObjectId;
55 import org.spearce.jgit.lib.PackWriter;
56 import org.spearce.jgit.lib.ProgressMonitor;
57 import org.spearce.jgit.lib.Ref;
58 import org.spearce.jgit.lib.RefWriter;
59 import org.spearce.jgit.lib.Repository;
60 import org.spearce.jgit.lib.Ref.Storage;
61 import org.spearce.jgit.transport.RemoteRefUpdate.Status;
63 /**
64 * Generic push support for dumb transport protocols.
65 * <p>
66 * Since there are no Git-specific smarts on the remote side of the connection
67 * the client side must handle everything on its own. The generic push support
68 * requires being able to delete, create and overwrite files on the remote side,
69 * as well as create any missing directories (if necessary). Typically this can
70 * be handled through an FTP style protocol.
71 * <p>
72 * Objects not on the remote side are uploaded as pack files, using one pack
73 * file per invocation. This simplifies the implementation as only two data
74 * files need to be written to the remote repository.
75 * <p>
76 * Push support supplied by this class is not multiuser safe. Concurrent pushes
77 * to the same repository may yield an inconsistent reference database which may
78 * confuse fetch clients.
79 * <p>
80 * A single push is concurrently safe with multiple fetch requests, due to the
81 * careful order of operations used to update the repository. Clients fetching
82 * may receive transient failures due to short reads on certain files if the
83 * protocol does not support atomic file replacement.
85 * @see WalkRemoteObjectDatabase
87 class WalkPushConnection extends BaseConnection implements PushConnection {
88 /** The repository this transport pushes out of. */
89 private final Repository local;
91 /** Location of the remote repository we are writing to. */
92 private final URIish uri;
94 /** Database connection to the remote repository. */
95 private final WalkRemoteObjectDatabase dest;
97 /**
98 * Packs already known to reside in the remote repository.
99 * <p>
100 * This is a LinkedHashMap to maintain the original order.
102 private LinkedHashMap<String, String> packNames;
104 /** Complete listing of refs the remote will have after our push. */
105 private Map<String, Ref> newRefs;
108 * Updates which require altering the packed-refs file to complete.
109 * <p>
110 * If this collection is non-empty then any refs listed in {@link #newRefs}
111 * with a storage class of {@link Storage#PACKED} will be written.
113 private Collection<RemoteRefUpdate> packedRefUpdates;
115 WalkPushConnection(final WalkTransport walkTransport,
116 final WalkRemoteObjectDatabase w) {
117 local = walkTransport.local;
118 uri = walkTransport.getURI();
119 dest = w;
122 public void push(final ProgressMonitor monitor,
123 final Map<String, RemoteRefUpdate> refUpdates)
124 throws TransportException {
125 markStartedOperation();
126 packNames = null;
127 newRefs = new TreeMap<String, Ref>(getRefsMap());
128 packedRefUpdates = new ArrayList<RemoteRefUpdate>(refUpdates.size());
130 // Filter the commands and issue all deletes first. This way we
131 // can correctly handle a directory being cleared out and a new
132 // ref using the directory name being created.
134 final List<RemoteRefUpdate> updates = new ArrayList<RemoteRefUpdate>();
135 for (final RemoteRefUpdate u : refUpdates.values()) {
136 final String n = u.getRemoteName();
137 if (!n.startsWith("refs/") || !Repository.isValidRefName(n)) {
138 u.setStatus(Status.REJECTED_OTHER_REASON);
139 u.setMessage("funny refname");
140 continue;
143 if (AnyObjectId.equals(ObjectId.zeroId(), u.getNewObjectId()))
144 deleteCommand(u);
145 else
146 updates.add(u);
149 // If we have any updates we need to upload the objects first, to
150 // prevent creating refs pointing at non-existent data. Then we
151 // can update the refs, and the info-refs file for dumb transports.
153 if (!updates.isEmpty())
154 sendpack(updates, monitor);
155 for (final RemoteRefUpdate u : updates)
156 updateCommand(u);
158 // Is this a new repository? If so we should create additional
159 // metadata files so it is properly initialized during the push.
161 if (!updates.isEmpty() && isNewRepository())
162 createNewRepository(updates);
164 RefWriter refWriter = new RefWriter(newRefs.values()) {
165 @Override
166 protected void writeFile(String file, byte[] content)
167 throws IOException {
168 dest.writeFile(ROOT_DIR + file, content);
171 if (!packedRefUpdates.isEmpty()) {
172 try {
173 refWriter.writePackedRefs();
174 for (final RemoteRefUpdate u : packedRefUpdates)
175 u.setStatus(Status.OK);
176 } catch (IOException err) {
177 for (final RemoteRefUpdate u : packedRefUpdates) {
178 u.setStatus(Status.REJECTED_OTHER_REASON);
179 u.setMessage(err.getMessage());
181 throw new TransportException(uri, "failed updating refs", err);
185 try {
186 refWriter.writeInfoRefs();
187 } catch (IOException err) {
188 throw new TransportException(uri, "failed updating refs", err);
192 @Override
193 public void close() {
194 dest.close();
197 private void sendpack(final List<RemoteRefUpdate> updates,
198 final ProgressMonitor monitor) throws TransportException {
199 String pathPack = null;
200 String pathIdx = null;
202 try {
203 final PackWriter pw = new PackWriter(local, monitor);
204 final List<ObjectId> need = new ArrayList<ObjectId>();
205 final List<ObjectId> have = new ArrayList<ObjectId>();
206 for (final RemoteRefUpdate r : updates)
207 need.add(r.getNewObjectId());
208 for (final Ref r : getRefs()) {
209 have.add(r.getObjectId());
210 if (r.getPeeledObjectId() != null)
211 have.add(r.getPeeledObjectId());
213 pw.preparePack(need, have);
215 // We don't have to continue further if the pack will
216 // be an empty pack, as the remote has all objects it
217 // needs to complete this change.
219 if (pw.getObjectsNumber() == 0)
220 return;
222 packNames = new LinkedHashMap<String, String>();
223 for (final String n : dest.getPackNames())
224 packNames.put(n, n);
226 final String base = "pack-" + pw.computeName().name();
227 final String packName = base + ".pack";
228 pathPack = "pack/" + packName;
229 pathIdx = "pack/" + base + ".idx";
231 if (packNames.remove(packName) != null) {
232 // The remote already contains this pack. We should
233 // remove the index before overwriting to prevent bad
234 // offsets from appearing to clients.
236 dest.writeInfoPacks(packNames.keySet());
237 dest.deleteFile(pathIdx);
240 // Write the pack file, then the index, as readers look the
241 // other direction (index, then pack file).
243 final String wt = "Put " + base.substring(0, 12);
244 OutputStream os = dest.writeFile(pathPack, monitor, wt + "..pack");
245 try {
246 pw.writePack(os);
247 } finally {
248 os.close();
251 os = dest.writeFile(pathIdx, monitor, wt + "..idx");
252 try {
253 pw.writeIndex(os);
254 } finally {
255 os.close();
258 // Record the pack at the start of the pack info list. This
259 // way clients are likely to consult the newest pack first,
260 // and discover the most recent objects there.
262 final ArrayList<String> infoPacks = new ArrayList<String>();
263 infoPacks.add(packName);
264 infoPacks.addAll(packNames.keySet());
265 dest.writeInfoPacks(infoPacks);
267 } catch (IOException err) {
268 safeDelete(pathIdx);
269 safeDelete(pathPack);
271 throw new TransportException(uri, "cannot store objects", err);
275 private void safeDelete(final String path) {
276 if (path != null) {
277 try {
278 dest.deleteFile(path);
279 } catch (IOException cleanupFailure) {
280 // Ignore the deletion failure. We probably are
281 // already failing and were just trying to pick
282 // up after ourselves.
287 private void deleteCommand(final RemoteRefUpdate u) {
288 final Ref r = newRefs.remove(u.getRemoteName());
289 if (r == null) {
290 // Already gone.
292 u.setStatus(Status.OK);
293 return;
296 if (r.getStorage().isPacked())
297 packedRefUpdates.add(u);
299 if (r.getStorage().isLoose()) {
300 try {
301 dest.deleteRef(u.getRemoteName());
302 u.setStatus(Status.OK);
303 } catch (IOException e) {
304 u.setStatus(Status.REJECTED_OTHER_REASON);
305 u.setMessage(e.getMessage());
309 try {
310 dest.deleteRefLog(u.getRemoteName());
311 } catch (IOException e) {
312 u.setStatus(Status.REJECTED_OTHER_REASON);
313 u.setMessage(e.getMessage());
317 private void updateCommand(final RemoteRefUpdate u) {
318 try {
319 dest.writeRef(u.getRemoteName(), u.getNewObjectId());
320 newRefs.put(u.getRemoteName(), new Ref(Storage.LOOSE, u
321 .getRemoteName(), u.getNewObjectId()));
322 u.setStatus(Status.OK);
323 } catch (IOException e) {
324 u.setStatus(Status.REJECTED_OTHER_REASON);
325 u.setMessage(e.getMessage());
329 private boolean isNewRepository() {
330 return getRefsMap().isEmpty() && packNames != null
331 && packNames.isEmpty();
334 private void createNewRepository(final List<RemoteRefUpdate> updates)
335 throws TransportException {
336 try {
337 final String ref = "ref: " + pickHEAD(updates) + "\n";
338 final byte[] bytes = Constants.encode(ref);
339 dest.writeFile(ROOT_DIR + Constants.HEAD, bytes);
340 } catch (IOException e) {
341 throw new TransportException(uri, "cannot create HEAD", e);
344 try {
345 final String config = "[core]\n"
346 + "\trepositoryformatversion = 0\n";
347 final byte[] bytes = Constants.encode(config);
348 dest.writeFile(ROOT_DIR + "config", bytes);
349 } catch (IOException e) {
350 throw new TransportException(uri, "cannot create config", e);
354 private static String pickHEAD(final List<RemoteRefUpdate> updates) {
355 // Try to use master if the user is pushing that, it is the
356 // default branch and is likely what they want to remain as
357 // the default on the new remote.
359 for (final RemoteRefUpdate u : updates) {
360 final String n = u.getRemoteName();
361 if (n.equals(Constants.R_HEADS + Constants.MASTER))
362 return n;
365 // Pick any branch, under the assumption the user pushed only
366 // one to the remote side.
368 for (final RemoteRefUpdate u : updates) {
369 final String n = u.getRemoteName();
370 if (n.startsWith(Constants.R_HEADS))
371 return n;
373 return updates.get(0).getRemoteName();