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

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