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 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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.Collection;
  54. import java.util.HashMap;
  55. import java.util.HashSet;
  56. import java.util.LinkedHashSet;
  57. import java.util.Map;
  58. import java.util.Set;
  59. import org.eclipse.jgit.lib.AnyObjectId;
  60. import org.eclipse.jgit.lib.Constants;
  61. import org.eclipse.jgit.lib.ObjectId;
  62. import org.eclipse.jgit.lib.Ref;
  63. import org.eclipse.jgit.lib.RefComparator;
  64. import org.eclipse.jgit.lib.Repository;
  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(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. private boolean useProtocolV2;
  158. /* only used in protocol v2 */
  159. private final Map<String, String> symrefs = new HashMap<>();
  160. /**
  161. * Initialize this advertiser with a repository for peeling tags.
  162. *
  163. * @param src
  164. * the repository to read from.
  165. */
  166. public void init(Repository src) {
  167. repository = src;
  168. }
  169. /**
  170. * @param b
  171. * true if this advertiser should advertise using the protocol
  172. * v2 format, false otherwise
  173. * @since 5.0
  174. */
  175. public void setUseProtocolV2(boolean b) {
  176. useProtocolV2 = b;
  177. }
  178. /**
  179. * Toggle tag peeling.
  180. * <p>
  181. * <p>
  182. * This method must be invoked prior to any of the following:
  183. * <ul>
  184. * <li>{@link #send(Map)}
  185. * </ul>
  186. *
  187. * @param deref
  188. * true to show the dereferenced value of a tag as the special
  189. * ref <code>$tag^{}</code> ; false to omit it from the output.
  190. */
  191. public void setDerefTags(boolean deref) {
  192. derefTags = deref;
  193. }
  194. /**
  195. * Add one protocol capability to the initial advertisement.
  196. * <p>
  197. * This method must be invoked prior to any of the following:
  198. * <ul>
  199. * <li>{@link #send(Map)}
  200. * <li>{@link #advertiseHave(AnyObjectId)}
  201. * </ul>
  202. *
  203. * @param name
  204. * the name of a single protocol capability supported by the
  205. * caller. The set of capabilities are sent to the client in the
  206. * advertisement, allowing the client to later selectively enable
  207. * features it recognizes.
  208. */
  209. public void advertiseCapability(String name) {
  210. capablities.add(name);
  211. }
  212. /**
  213. * Add one protocol capability with a value ({@code "name=value"}).
  214. *
  215. * @param name
  216. * name of the capability.
  217. * @param value
  218. * value. If null the capability will not be added.
  219. * @since 4.0
  220. */
  221. public void advertiseCapability(String name, String value) {
  222. if (value != null) {
  223. capablities.add(name + '=' + value);
  224. }
  225. }
  226. /**
  227. * Add a symbolic ref to capabilities.
  228. * <p>
  229. * This method must be invoked prior to any of the following:
  230. * <ul>
  231. * <li>{@link #send(Map)}
  232. * <li>{@link #advertiseHave(AnyObjectId)}
  233. * </ul>
  234. *
  235. * @param from
  236. * The symbolic ref, e.g. "HEAD"
  237. * @param to
  238. * The real ref it points to, e.g. "refs/heads/master"
  239. * @since 3.6
  240. */
  241. public void addSymref(String from, String to) {
  242. if (useProtocolV2) {
  243. symrefs.put(from, to);
  244. } else {
  245. advertiseCapability(OPTION_SYMREF, from + ':' + to);
  246. }
  247. }
  248. /**
  249. * Format an advertisement for the supplied refs.
  250. *
  251. * @param refs
  252. * zero or more refs to format for the client. The collection is
  253. * sorted before display if necessary, and therefore may appear
  254. * in any order.
  255. * @return set of ObjectIds that were advertised to the client.
  256. * @throws java.io.IOException
  257. * the underlying output stream failed to write out an
  258. * advertisement record.
  259. * @deprecated use {@link #send(Collection)} instead.
  260. */
  261. @Deprecated
  262. public Set<ObjectId> send(Map<String, Ref> refs) throws IOException {
  263. return send(refs.values());
  264. }
  265. /**
  266. * Format an advertisement for the supplied refs.
  267. *
  268. * @param refs
  269. * zero or more refs to format for the client. The collection is
  270. * sorted before display if necessary, and therefore may appear
  271. * in any order.
  272. * @return set of ObjectIds that were advertised to the client.
  273. * @throws java.io.IOException
  274. * the underlying output stream failed to write out an
  275. * advertisement record.
  276. * @since 5.0
  277. */
  278. public Set<ObjectId> send(Collection<Ref> refs) throws IOException {
  279. for (Ref ref : RefComparator.sort(refs)) {
  280. // TODO(jrn) revive the SortedMap optimization e.g. by introducing
  281. // SortedList
  282. ObjectId objectId = ref.getObjectId();
  283. if (objectId == null) {
  284. continue;
  285. }
  286. if (useProtocolV2) {
  287. String symrefPart = symrefs.containsKey(ref.getName())
  288. ? (" symref-target:" + symrefs.get(ref.getName())) //$NON-NLS-1$
  289. : ""; //$NON-NLS-1$
  290. String peelPart = ""; //$NON-NLS-1$
  291. if (derefTags) {
  292. if (!ref.isPeeled() && repository != null) {
  293. ref = repository.getRefDatabase().peel(ref);
  294. }
  295. ObjectId peeledObjectId = ref.getPeeledObjectId();
  296. if (peeledObjectId != null) {
  297. peelPart = " peeled:" + peeledObjectId.getName(); //$NON-NLS-1$
  298. }
  299. }
  300. writeOne(objectId.getName() + " " + ref.getName() + symrefPart //$NON-NLS-1$
  301. + peelPart + "\n"); //$NON-NLS-1$
  302. continue;
  303. }
  304. advertiseAny(objectId, ref.getName());
  305. if (!derefTags)
  306. continue;
  307. if (!ref.isPeeled()) {
  308. if (repository == null)
  309. continue;
  310. ref = repository.getRefDatabase().peel(ref);
  311. }
  312. if (ref.getPeeledObjectId() != null)
  313. advertiseAny(ref.getPeeledObjectId(), ref.getName() + "^{}"); //$NON-NLS-1$
  314. }
  315. return sent;
  316. }
  317. /**
  318. * Advertise one object is available using the magic {@code .have}.
  319. * <p>
  320. * The magic {@code .have} advertisement is not available for fetching by a
  321. * client, but can be used by a client when considering a delta base
  322. * candidate before transferring data in a push. Within the record created
  323. * by this method the ref name is simply the invalid string {@code .have}.
  324. *
  325. * @param id
  326. * identity of the object that is assumed to exist.
  327. * @throws java.io.IOException
  328. * the underlying output stream failed to write out an
  329. * advertisement record.
  330. */
  331. public void advertiseHave(AnyObjectId id) throws IOException {
  332. advertiseAnyOnce(id, ".have"); //$NON-NLS-1$
  333. }
  334. /**
  335. * Whether no advertisements have been sent yet.
  336. *
  337. * @return true if no advertisements have been sent yet.
  338. */
  339. public boolean isEmpty() {
  340. return first;
  341. }
  342. private void advertiseAnyOnce(AnyObjectId obj, String refName)
  343. throws IOException {
  344. if (!sent.contains(obj))
  345. advertiseAny(obj, refName);
  346. }
  347. private void advertiseAny(AnyObjectId obj, String refName)
  348. throws IOException {
  349. sent.add(obj.toObjectId());
  350. advertiseId(obj, refName);
  351. }
  352. /**
  353. * Advertise one object under a specific name.
  354. * <p>
  355. * If the advertised object is a tag, this method does not advertise the
  356. * peeled version of it.
  357. *
  358. * @param id
  359. * the object to advertise.
  360. * @param refName
  361. * name of the reference to advertise the object as, can be any
  362. * string not including the NUL byte.
  363. * @throws java.io.IOException
  364. * the underlying output stream failed to write out an
  365. * advertisement record.
  366. */
  367. public void advertiseId(AnyObjectId id, String refName)
  368. throws IOException {
  369. tmpLine.setLength(0);
  370. id.copyTo(tmpId, tmpLine);
  371. tmpLine.append(' ');
  372. tmpLine.append(refName);
  373. if (first) {
  374. first = false;
  375. if (!capablities.isEmpty()) {
  376. tmpLine.append('\0');
  377. for (String capName : capablities) {
  378. tmpLine.append(' ');
  379. tmpLine.append(capName);
  380. }
  381. tmpLine.append(' ');
  382. }
  383. }
  384. tmpLine.append('\n');
  385. writeOne(tmpLine);
  386. }
  387. /**
  388. * Write a single advertisement line.
  389. *
  390. * @param line
  391. * the advertisement line to be written. The line always ends
  392. * with LF. Never null or the empty string.
  393. * @throws java.io.IOException
  394. * the underlying output stream failed to write out an
  395. * advertisement record.
  396. */
  397. protected abstract void writeOne(CharSequence line) throws IOException;
  398. /**
  399. * Mark the end of the advertisements.
  400. *
  401. * @throws java.io.IOException
  402. * the underlying output stream failed to write out an
  403. * advertisement record.
  404. */
  405. protected abstract void end() throws IOException;
  406. }