You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RefAdvertiser.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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. package org.eclipse.jgit.transport;
  44. import static java.nio.charset.StandardCharsets.UTF_8;
  45. import static org.eclipse.jgit.lib.Constants.OBJECT_ID_STRING_LENGTH;
  46. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SYMREF;
  47. import java.io.IOException;
  48. import java.nio.ByteBuffer;
  49. import java.nio.CharBuffer;
  50. import java.nio.charset.CharacterCodingException;
  51. import java.nio.charset.CharsetEncoder;
  52. import java.nio.charset.CoderResult;
  53. import java.util.HashSet;
  54. import java.util.LinkedHashSet;
  55. import java.util.Map;
  56. import java.util.Set;
  57. import java.util.SortedMap;
  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.Ref;
  62. import org.eclipse.jgit.lib.RefComparator;
  63. import org.eclipse.jgit.lib.Repository;
  64. import org.eclipse.jgit.util.RefMap;
  65. /** Support for the start of {@link UploadPack} and {@link ReceivePack}. */
  66. public abstract class RefAdvertiser {
  67. /** Advertiser which frames lines in a {@link PacketLineOut} format. */
  68. public static class PacketLineOutRefAdvertiser extends RefAdvertiser {
  69. private final CharsetEncoder utf8 = UTF_8.newEncoder();
  70. private final PacketLineOut pckOut;
  71. private byte[] binArr = new byte[256];
  72. private ByteBuffer binBuf = ByteBuffer.wrap(binArr);
  73. private char[] chArr = new char[256];
  74. private CharBuffer chBuf = CharBuffer.wrap(chArr);
  75. /**
  76. * Create a new advertiser for the supplied stream.
  77. *
  78. * @param out
  79. * the output stream.
  80. */
  81. public PacketLineOutRefAdvertiser(PacketLineOut out) {
  82. pckOut = out;
  83. }
  84. @Override
  85. public void advertiseId(AnyObjectId id, String refName)
  86. throws IOException {
  87. id.copyTo(binArr, 0);
  88. binArr[OBJECT_ID_STRING_LENGTH] = ' ';
  89. binBuf.position(OBJECT_ID_STRING_LENGTH + 1);
  90. append(refName);
  91. if (first) {
  92. first = false;
  93. if (!capablities.isEmpty()) {
  94. append('\0');
  95. for (String cap : capablities) {
  96. append(' ');
  97. append(cap);
  98. }
  99. }
  100. }
  101. append('\n');
  102. pckOut.writePacket(binArr, 0, binBuf.position());
  103. }
  104. private void append(String str) throws CharacterCodingException {
  105. int n = str.length();
  106. if (n > chArr.length) {
  107. chArr = new char[n + 256];
  108. chBuf = CharBuffer.wrap(chArr);
  109. }
  110. str.getChars(0, n, chArr, 0);
  111. chBuf.position(0).limit(n);
  112. utf8.reset();
  113. for (;;) {
  114. CoderResult cr = utf8.encode(chBuf, binBuf, true);
  115. if (cr.isOverflow()) {
  116. grow();
  117. } else if (cr.isUnderflow()) {
  118. break;
  119. } else {
  120. cr.throwException();
  121. }
  122. }
  123. }
  124. private void append(int b) {
  125. if (!binBuf.hasRemaining()) {
  126. grow();
  127. }
  128. binBuf.put((byte) b);
  129. }
  130. private void grow() {
  131. int cnt = binBuf.position();
  132. byte[] tmp = new byte[binArr.length << 1];
  133. System.arraycopy(binArr, 0, tmp, 0, cnt);
  134. binArr = tmp;
  135. binBuf = ByteBuffer.wrap(binArr);
  136. binBuf.position(cnt);
  137. }
  138. @Override
  139. protected void writeOne(final CharSequence line) throws IOException {
  140. pckOut.writeString(line.toString());
  141. }
  142. @Override
  143. protected void end() throws IOException {
  144. pckOut.end();
  145. }
  146. }
  147. private final StringBuilder tmpLine = new StringBuilder(100);
  148. private final char[] tmpId = new char[Constants.OBJECT_ID_STRING_LENGTH];
  149. final Set<String> capablities = new LinkedHashSet<String>();
  150. private final Set<ObjectId> sent = new HashSet<ObjectId>();
  151. private Repository repository;
  152. private boolean derefTags;
  153. boolean first = true;
  154. /**
  155. * Initialize this advertiser with a repository for peeling tags.
  156. *
  157. * @param src
  158. * the repository to read from.
  159. */
  160. public void init(Repository src) {
  161. repository = src;
  162. }
  163. /**
  164. * Toggle tag peeling.
  165. * <p>
  166. * <p>
  167. * This method must be invoked prior to any of the following:
  168. * <ul>
  169. * <li>{@link #send(Map)}
  170. * </ul>
  171. *
  172. * @param deref
  173. * true to show the dereferenced value of a tag as the special
  174. * ref <code>$tag^{}</code> ; false to omit it from the output.
  175. */
  176. public void setDerefTags(final boolean deref) {
  177. derefTags = deref;
  178. }
  179. /**
  180. * Add one protocol capability to the initial advertisement.
  181. * <p>
  182. * This method must be invoked prior to any of the following:
  183. * <ul>
  184. * <li>{@link #send(Map)}
  185. * <li>{@link #advertiseHave(AnyObjectId)}
  186. * </ul>
  187. *
  188. * @param name
  189. * the name of a single protocol capability supported by the
  190. * caller. The set of capabilities are sent to the client in the
  191. * advertisement, allowing the client to later selectively enable
  192. * features it recognizes.
  193. */
  194. public void advertiseCapability(String name) {
  195. capablities.add(name);
  196. }
  197. /**
  198. * Add one protocol capability with a value ({@code "name=value"}).
  199. *
  200. * @param name
  201. * name of the capability.
  202. * @param value
  203. * value. If null the capability will not be added.
  204. * @since 4.0
  205. */
  206. public void advertiseCapability(String name, String value) {
  207. if (value != null) {
  208. capablities.add(name + '=' + value);
  209. }
  210. }
  211. /**
  212. * Add a symbolic ref to capabilities.
  213. * <p>
  214. * This method must be invoked prior to any of the following:
  215. * <ul>
  216. * <li>{@link #send(Map)}
  217. * <li>{@link #advertiseHave(AnyObjectId)}
  218. * </ul>
  219. *
  220. * @param from
  221. * The symbolic ref, e.g. "HEAD"
  222. * @param to
  223. * The real ref it points to, e.g. "refs/heads/master"
  224. *
  225. * @since 3.6
  226. */
  227. public void addSymref(String from, String to) {
  228. advertiseCapability(OPTION_SYMREF, from + ':' + to);
  229. }
  230. /**
  231. * Format an advertisement for the supplied refs.
  232. *
  233. * @param refs
  234. * zero or more refs to format for the client. The collection is
  235. * sorted before display if necessary, and therefore may appear
  236. * in any order.
  237. * @return set of ObjectIds that were advertised to the client.
  238. * @throws IOException
  239. * the underlying output stream failed to write out an
  240. * advertisement record.
  241. */
  242. public Set<ObjectId> send(Map<String, Ref> refs) throws IOException {
  243. for (Ref ref : getSortedRefs(refs)) {
  244. if (ref.getObjectId() == null)
  245. continue;
  246. advertiseAny(ref.getObjectId(), ref.getName());
  247. if (!derefTags)
  248. continue;
  249. if (!ref.isPeeled()) {
  250. if (repository == null)
  251. continue;
  252. ref = repository.peel(ref);
  253. }
  254. if (ref.getPeeledObjectId() != null)
  255. advertiseAny(ref.getPeeledObjectId(), ref.getName() + "^{}"); //$NON-NLS-1$
  256. }
  257. return sent;
  258. }
  259. private Iterable<Ref> getSortedRefs(Map<String, Ref> all) {
  260. if (all instanceof RefMap
  261. || (all instanceof SortedMap && ((SortedMap) all).comparator() == null))
  262. return all.values();
  263. return RefComparator.sort(all.values());
  264. }
  265. /**
  266. * Advertise one object is available using the magic {@code .have}.
  267. * <p>
  268. * The magic {@code .have} advertisement is not available for fetching by a
  269. * client, but can be used by a client when considering a delta base
  270. * candidate before transferring data in a push. Within the record created
  271. * by this method the ref name is simply the invalid string {@code .have}.
  272. *
  273. * @param id
  274. * identity of the object that is assumed to exist.
  275. * @throws IOException
  276. * the underlying output stream failed to write out an
  277. * advertisement record.
  278. */
  279. public void advertiseHave(AnyObjectId id) throws IOException {
  280. advertiseAnyOnce(id, ".have"); //$NON-NLS-1$
  281. }
  282. /** @return true if no advertisements have been sent yet. */
  283. public boolean isEmpty() {
  284. return first;
  285. }
  286. private void advertiseAnyOnce(AnyObjectId obj, final String refName)
  287. throws IOException {
  288. if (!sent.contains(obj))
  289. advertiseAny(obj, refName);
  290. }
  291. private void advertiseAny(AnyObjectId obj, final String refName)
  292. throws IOException {
  293. sent.add(obj.toObjectId());
  294. advertiseId(obj, refName);
  295. }
  296. /**
  297. * Advertise one object under a specific name.
  298. * <p>
  299. * If the advertised object is a tag, this method does not advertise the
  300. * peeled version of it.
  301. *
  302. * @param id
  303. * the object to advertise.
  304. * @param refName
  305. * name of the reference to advertise the object as, can be any
  306. * string not including the NUL byte.
  307. * @throws IOException
  308. * the underlying output stream failed to write out an
  309. * advertisement record.
  310. */
  311. public void advertiseId(final AnyObjectId id, final String refName)
  312. throws IOException {
  313. tmpLine.setLength(0);
  314. id.copyTo(tmpId, tmpLine);
  315. tmpLine.append(' ');
  316. tmpLine.append(refName);
  317. if (first) {
  318. first = false;
  319. if (!capablities.isEmpty()) {
  320. tmpLine.append('\0');
  321. for (final String capName : capablities) {
  322. tmpLine.append(' ');
  323. tmpLine.append(capName);
  324. }
  325. tmpLine.append(' ');
  326. }
  327. }
  328. tmpLine.append('\n');
  329. writeOne(tmpLine);
  330. }
  331. /**
  332. * Write a single advertisement line.
  333. *
  334. * @param line
  335. * the advertisement line to be written. The line always ends
  336. * with LF. Never null or the empty string.
  337. * @throws IOException
  338. * the underlying output stream failed to write out an
  339. * advertisement record.
  340. */
  341. protected abstract void writeOne(CharSequence line) throws IOException;
  342. /**
  343. * Mark the end of the advertisements.
  344. *
  345. * @throws IOException
  346. * the underlying output stream failed to write out an
  347. * advertisement record.
  348. */
  349. protected abstract void end() throws IOException;
  350. }