1 /*
2 * Copyright (C) 2008-2010, 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 java.io.IOException;
47 import java.io.OutputStream;
48 import java.io.OutputStreamWriter;
49 import java.io.Writer;
50 import java.text.MessageFormat;
51 import java.util.HashSet;
52 import java.util.Map;
53 import java.util.Set;
54 import java.util.TreeMap;
55
56 import org.eclipse.jgit.internal.JGitText;
57 import org.eclipse.jgit.internal.storage.pack.PackWriter;
58 import org.eclipse.jgit.lib.AnyObjectId;
59 import org.eclipse.jgit.lib.Constants;
60 import org.eclipse.jgit.lib.ObjectId;
61 import org.eclipse.jgit.lib.ProgressMonitor;
62 import org.eclipse.jgit.lib.Ref;
63 import org.eclipse.jgit.lib.Repository;
64 import org.eclipse.jgit.revwalk.RevCommit;
65 import org.eclipse.jgit.storage.pack.PackConfig;
66
67 /**
68 * Creates a Git bundle file, for sneaker-net transport to another system.
69 * <p>
70 * Bundles generated by this class can be later read in from a file URI using
71 * the bundle transport, or from an application controlled buffer by the more
72 * generic {@link TransportBundleStream}.
73 * <p>
74 * Applications creating bundles need to call one or more <code>include</code>
75 * calls to reflect which objects should be available as refs in the bundle for
76 * the other side to fetch. At least one include is required to create a valid
77 * bundle file, and duplicate names are not permitted.
78 * <p>
79 * Optional <code>assume</code> calls can be made to declare commits which the
80 * recipient must have in order to fetch from the bundle file. Objects reachable
81 * from these assumed commits can be used as delta bases in order to reduce the
82 * overall bundle size.
83 */
84 public class BundleWriter {
85 private final Repository db;
86
87 private final Map<String, ObjectId> include;
88
89 private final Set<RevCommit> assume;
90
91 private final Set<ObjectId> tagTargets;
92
93 private PackConfig packConfig;
94
95 private ObjectCountCallback callback;
96
97 /**
98 * Create a writer for a bundle.
99 *
100 * @param repo
101 * repository where objects are stored.
102 */
103 public BundleWriter(final Repository repo) {
104 db = repo;
105 include = new TreeMap<String, ObjectId>();
106 assume = new HashSet<RevCommit>();
107 tagTargets = new HashSet<ObjectId>();
108 }
109
110 /**
111 * Set the configuration used by the pack generator.
112 *
113 * @param pc
114 * configuration controlling packing parameters. If null the
115 * source repository's settings will be used.
116 */
117 public void setPackConfig(PackConfig pc) {
118 this.packConfig = pc;
119 }
120
121 /**
122 * Include an object (and everything reachable from it) in the bundle.
123 *
124 * @param name
125 * name the recipient can discover this object as from the
126 * bundle's list of advertised refs . The name must be a valid
127 * ref format and must not have already been included in this
128 * bundle writer.
129 * @param id
130 * object to pack. Multiple refs may point to the same object.
131 */
132 public void include(final String name, final AnyObjectId id) {
133 boolean validRefName = Repository.isValidRefName(name) || Constants.HEAD.equals(name);
134 if (!validRefName)
135 throw new IllegalArgumentException(MessageFormat.format(JGitText.get().invalidRefName, name));
136 if (include.containsKey(name))
137 throw new IllegalStateException(JGitText.get().duplicateRef + name);
138 include.put(name, id.toObjectId());
139 }
140
141 /**
142 * Include a single ref (a name/object pair) in the bundle.
143 * <p>
144 * This is a utility function for:
145 * <code>include(r.getName(), r.getObjectId())</code>.
146 *
147 * @param r
148 * the ref to include.
149 */
150 public void include(final Ref r) {
151 include(r.getName(), r.getObjectId());
152
153 if (r.getPeeledObjectId() != null)
154 tagTargets.add(r.getPeeledObjectId());
155
156 else if (r.getObjectId() != null
157 && r.getName().startsWith(Constants.R_HEADS))
158 tagTargets.add(r.getObjectId());
159 }
160
161 /**
162 * Assume a commit is available on the recipient's side.
163 * <p>
164 * In order to fetch from a bundle the recipient must have any assumed
165 * commit. Each assumed commit is explicitly recorded in the bundle header
166 * to permit the recipient to validate it has these objects.
167 *
168 * @param c
169 * the commit to assume being available. This commit should be
170 * parsed and not disposed in order to maximize the amount of
171 * debugging information available in the bundle stream.
172 */
173 public void assume(final RevCommit c) {
174 if (c != null)
175 assume.add(c);
176 }
177
178 /**
179 * Generate and write the bundle to the output stream.
180 * <p>
181 * This method can only be called once per BundleWriter instance.
182 *
183 * @param monitor
184 * progress monitor to report bundle writing status to.
185 * @param os
186 * the stream the bundle is written to. The stream should be
187 * buffered by the caller. The caller is responsible for closing
188 * the stream.
189 * @throws IOException
190 * an error occurred reading a local object's data to include in
191 * the bundle, or writing compressed object data to the output
192 * stream.
193 * @throws WriteAbortedException
194 * the write operation is aborted by
195 * {@link ObjectCountCallback}.
196 */
197 public void writeBundle(ProgressMonitor monitor, OutputStream os)
198 throws IOException {
199 PackConfig pc = packConfig;
200 if (pc == null)
201 pc = new PackConfig(db);
202 try (PackWriter packWriter = new PackWriter(pc, db.newObjectReader())) {
203 packWriter.setObjectCountCallback(callback);
204
205 final HashSet<ObjectId> inc = new HashSet<ObjectId>();
206 final HashSet<ObjectId> exc = new HashSet<ObjectId>();
207 inc.addAll(include.values());
208 for (final RevCommit r : assume)
209 exc.add(r.getId());
210 packWriter.setIndexDisabled(true);
211 packWriter.setDeltaBaseAsOffset(true);
212 packWriter.setThin(exc.size() > 0);
213 packWriter.setReuseValidatingObjects(false);
214 if (exc.size() == 0)
215 packWriter.setTagTargets(tagTargets);
216 packWriter.preparePack(monitor, inc, exc);
217
218 final Writer w = new OutputStreamWriter(os, Constants.CHARSET);
219 w.write(TransportBundle.V2_BUNDLE_SIGNATURE);
220 w.write('\n');
221
222 final char[] tmp = new char[Constants.OBJECT_ID_STRING_LENGTH];
223 for (final RevCommit a : assume) {
224 w.write('-');
225 a.copyTo(tmp, w);
226 if (a.getRawBuffer() != null) {
227 w.write(' ');
228 w.write(a.getShortMessage());
229 }
230 w.write('\n');
231 }
232 for (final Map.Entry<String, ObjectId> e : include.entrySet()) {
233 e.getValue().copyTo(tmp, w);
234 w.write(' ');
235 w.write(e.getKey());
236 w.write('\n');
237 }
238
239 w.write('\n');
240 w.flush();
241 packWriter.writePack(monitor, monitor, os);
242 }
243 }
244
245 /**
246 * Set the {@link ObjectCountCallback}.
247 * <p>
248 * It should be set before calling
249 * {@link #writeBundle(ProgressMonitor, OutputStream)}.
250 * <p>
251 * This callback will be passed on to
252 * {@link PackWriter#setObjectCountCallback}.
253 *
254 * @param callback
255 * the callback to set
256 *
257 * @return this object for chaining.
258 * @since 4.1
259 */
260 public BundleWriter setObjectCountCallback(ObjectCountCallback callback) {
261 this.callback = callback;
262 return this;
263 }
264 }