2 * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
6 * Redistribution and use in source and binary forms, with or
7 * without modification, are permitted provided that the following
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
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
;
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
;
64 * Generic push support for dumb transport protocols.
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.
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.
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.
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
;
98 * Packs already known to reside in the remote repository.
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.
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 Transport t
= (Transport
)walkTransport
;
123 public void push(final ProgressMonitor monitor
,
124 final Map
<String
, RemoteRefUpdate
> refUpdates
)
125 throws TransportException
{
126 markStartedOperation();
128 newRefs
= new TreeMap
<String
, Ref
>(getRefsMap());
129 packedRefUpdates
= new ArrayList
<RemoteRefUpdate
>(refUpdates
.size());
131 // Filter the commands and issue all deletes first. This way we
132 // can correctly handle a directory being cleared out and a new
133 // ref using the directory name being created.
135 final List
<RemoteRefUpdate
> updates
= new ArrayList
<RemoteRefUpdate
>();
136 for (final RemoteRefUpdate u
: refUpdates
.values()) {
137 final String n
= u
.getRemoteName();
138 if (!n
.startsWith("refs/") || !Repository
.isValidRefName(n
)) {
139 u
.setStatus(Status
.REJECTED_OTHER_REASON
);
140 u
.setMessage("funny refname");
144 if (AnyObjectId
.equals(ObjectId
.zeroId(), u
.getNewObjectId()))
150 // If we have any updates we need to upload the objects first, to
151 // prevent creating refs pointing at non-existent data. Then we
152 // can update the refs, and the info-refs file for dumb transports.
154 if (!updates
.isEmpty())
155 sendpack(updates
, monitor
);
156 for (final RemoteRefUpdate u
: updates
)
159 // Is this a new repository? If so we should create additional
160 // metadata files so it is properly initialized during the push.
162 if (!updates
.isEmpty() && isNewRepository())
163 createNewRepository(updates
);
165 RefWriter refWriter
= new RefWriter(newRefs
.values()) {
167 protected void writeFile(String file
, byte[] content
)
169 dest
.writeFile(ROOT_DIR
+ file
, content
);
172 if (!packedRefUpdates
.isEmpty()) {
174 refWriter
.writePackedRefs();
175 for (final RemoteRefUpdate u
: packedRefUpdates
)
176 u
.setStatus(Status
.OK
);
177 } catch (IOException err
) {
178 for (final RemoteRefUpdate u
: packedRefUpdates
) {
179 u
.setStatus(Status
.REJECTED_OTHER_REASON
);
180 u
.setMessage(err
.getMessage());
182 throw new TransportException(uri
, "failed updating refs", err
);
187 refWriter
.writeInfoRefs();
188 } catch (IOException err
) {
189 throw new TransportException(uri
, "failed updating refs", err
);
194 public void close() {
198 private void sendpack(final List
<RemoteRefUpdate
> updates
,
199 final ProgressMonitor monitor
) throws TransportException
{
200 String pathPack
= null;
201 String pathIdx
= null;
204 final PackWriter pw
= new PackWriter(local
, monitor
);
205 final List
<ObjectId
> need
= new ArrayList
<ObjectId
>();
206 final List
<ObjectId
> have
= new ArrayList
<ObjectId
>();
207 for (final RemoteRefUpdate r
: updates
)
208 need
.add(r
.getNewObjectId());
209 for (final Ref r
: getRefs()) {
210 have
.add(r
.getObjectId());
211 if (r
.getPeeledObjectId() != null)
212 have
.add(r
.getPeeledObjectId());
214 pw
.preparePack(need
, have
);
216 // We don't have to continue further if the pack will
217 // be an empty pack, as the remote has all objects it
218 // needs to complete this change.
220 if (pw
.getObjectsNumber() == 0)
223 packNames
= new LinkedHashMap
<String
, String
>();
224 for (final String n
: dest
.getPackNames())
227 final String base
= "pack-" + pw
.computeName().name();
228 final String packName
= base
+ ".pack";
229 pathPack
= "pack/" + packName
;
230 pathIdx
= "pack/" + base
+ ".idx";
232 if (packNames
.remove(packName
) != null) {
233 // The remote already contains this pack. We should
234 // remove the index before overwriting to prevent bad
235 // offsets from appearing to clients.
237 dest
.writeInfoPacks(packNames
.keySet());
238 dest
.deleteFile(pathIdx
);
241 // Write the pack file, then the index, as readers look the
242 // other direction (index, then pack file).
244 final String wt
= "Put " + base
.substring(0, 12);
245 OutputStream os
= dest
.writeFile(pathPack
, monitor
, wt
+ "..pack");
252 os
= dest
.writeFile(pathIdx
, monitor
, wt
+ "..idx");
259 // Record the pack at the start of the pack info list. This
260 // way clients are likely to consult the newest pack first,
261 // and discover the most recent objects there.
263 final ArrayList
<String
> infoPacks
= new ArrayList
<String
>();
264 infoPacks
.add(packName
);
265 infoPacks
.addAll(packNames
.keySet());
266 dest
.writeInfoPacks(infoPacks
);
268 } catch (IOException err
) {
270 safeDelete(pathPack
);
272 throw new TransportException(uri
, "cannot store objects", err
);
276 private void safeDelete(final String path
) {
279 dest
.deleteFile(path
);
280 } catch (IOException cleanupFailure
) {
281 // Ignore the deletion failure. We probably are
282 // already failing and were just trying to pick
283 // up after ourselves.
288 private void deleteCommand(final RemoteRefUpdate u
) {
289 final Ref r
= newRefs
.remove(u
.getRemoteName());
293 u
.setStatus(Status
.OK
);
297 if (r
.getStorage().isPacked())
298 packedRefUpdates
.add(u
);
300 if (r
.getStorage().isLoose()) {
302 dest
.deleteRef(u
.getRemoteName());
303 u
.setStatus(Status
.OK
);
304 } catch (IOException e
) {
305 u
.setStatus(Status
.REJECTED_OTHER_REASON
);
306 u
.setMessage(e
.getMessage());
311 dest
.deleteRefLog(u
.getRemoteName());
312 } catch (IOException e
) {
313 u
.setStatus(Status
.REJECTED_OTHER_REASON
);
314 u
.setMessage(e
.getMessage());
318 private void updateCommand(final RemoteRefUpdate u
) {
320 dest
.writeRef(u
.getRemoteName(), u
.getNewObjectId());
321 newRefs
.put(u
.getRemoteName(), new Ref(Storage
.LOOSE
, u
322 .getRemoteName(), u
.getNewObjectId()));
323 u
.setStatus(Status
.OK
);
324 } catch (IOException e
) {
325 u
.setStatus(Status
.REJECTED_OTHER_REASON
);
326 u
.setMessage(e
.getMessage());
330 private boolean isNewRepository() {
331 return getRefsMap().isEmpty() && packNames
!= null
332 && packNames
.isEmpty();
335 private void createNewRepository(final List
<RemoteRefUpdate
> updates
)
336 throws TransportException
{
338 final String ref
= "ref: " + pickHEAD(updates
) + "\n";
339 final byte[] bytes
= Constants
.encode(ref
);
340 dest
.writeFile(ROOT_DIR
+ Constants
.HEAD
, bytes
);
341 } catch (IOException e
) {
342 throw new TransportException(uri
, "cannot create HEAD", e
);
346 final String config
= "[core]\n"
347 + "\trepositoryformatversion = 0\n";
348 final byte[] bytes
= Constants
.encode(config
);
349 dest
.writeFile(ROOT_DIR
+ "config", bytes
);
350 } catch (IOException e
) {
351 throw new TransportException(uri
, "cannot create config", e
);
355 private static String
pickHEAD(final List
<RemoteRefUpdate
> updates
) {
356 // Try to use master if the user is pushing that, it is the
357 // default branch and is likely what they want to remain as
358 // the default on the new remote.
360 for (final RemoteRefUpdate u
: updates
) {
361 final String n
= u
.getRemoteName();
362 if (n
.equals(Constants
.R_HEADS
+ Constants
.MASTER
))
366 // Pick any branch, under the assumption the user pushed only
367 // one to the remote side.
369 for (final RemoteRefUpdate u
: updates
) {
370 final String n
= u
.getRemoteName();
371 if (n
.startsWith(Constants
.R_HEADS
))
374 return updates
.get(0).getRemoteName();