Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. /*
  2. * Copyright (C) 2017, Markus Duft <markus.duft@ssi-schaefer.com>
  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.lfs;
  44. import static java.nio.charset.StandardCharsets.UTF_8;
  45. import static org.eclipse.jgit.lfs.Protocol.OPERATION_UPLOAD;
  46. import static org.eclipse.jgit.lfs.internal.LfsConnectionFactory.toRequest;
  47. import static org.eclipse.jgit.transport.http.HttpConnection.HTTP_OK;
  48. import static org.eclipse.jgit.util.HttpSupport.METHOD_POST;
  49. import static org.eclipse.jgit.util.HttpSupport.METHOD_PUT;
  50. import java.io.IOException;
  51. import java.io.InputStream;
  52. import java.io.InputStreamReader;
  53. import java.io.OutputStream;
  54. import java.io.PrintStream;
  55. import java.nio.file.Files;
  56. import java.nio.file.Path;
  57. import java.text.MessageFormat;
  58. import java.util.Collection;
  59. import java.util.HashMap;
  60. import java.util.List;
  61. import java.util.Map;
  62. import java.util.Set;
  63. import java.util.TreeSet;
  64. import org.eclipse.jgit.api.errors.AbortedByHookException;
  65. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  66. import org.eclipse.jgit.errors.MissingObjectException;
  67. import org.eclipse.jgit.hooks.PrePushHook;
  68. import org.eclipse.jgit.lfs.Protocol.ObjectInfo;
  69. import org.eclipse.jgit.lfs.errors.CorruptMediaFile;
  70. import org.eclipse.jgit.lfs.internal.LfsConnectionFactory;
  71. import org.eclipse.jgit.lfs.internal.LfsText;
  72. import org.eclipse.jgit.lib.AnyObjectId;
  73. import org.eclipse.jgit.lib.Constants;
  74. import org.eclipse.jgit.lib.ObjectId;
  75. import org.eclipse.jgit.lib.ObjectReader;
  76. import org.eclipse.jgit.lib.Ref;
  77. import org.eclipse.jgit.lib.RefDatabase;
  78. import org.eclipse.jgit.lib.Repository;
  79. import org.eclipse.jgit.revwalk.ObjectWalk;
  80. import org.eclipse.jgit.revwalk.RevObject;
  81. import org.eclipse.jgit.transport.RemoteRefUpdate;
  82. import org.eclipse.jgit.transport.http.HttpConnection;
  83. import com.google.gson.Gson;
  84. import com.google.gson.stream.JsonReader;
  85. /**
  86. * Pre-push hook that handles uploading LFS artefacts.
  87. *
  88. * @since 4.11
  89. */
  90. public class LfsPrePushHook extends PrePushHook {
  91. private static final String EMPTY = ""; //$NON-NLS-1$
  92. private Collection<RemoteRefUpdate> refs;
  93. /**
  94. * @param repo
  95. * the repository
  96. * @param outputStream
  97. * not used by this implementation
  98. */
  99. public LfsPrePushHook(Repository repo, PrintStream outputStream) {
  100. super(repo, outputStream);
  101. }
  102. @Override
  103. public void setRefs(Collection<RemoteRefUpdate> toRefs) {
  104. this.refs = toRefs;
  105. }
  106. @Override
  107. public String call() throws IOException, AbortedByHookException {
  108. Set<LfsPointer> toPush = findObjectsToPush();
  109. if (toPush.isEmpty()) {
  110. return EMPTY;
  111. }
  112. HttpConnection api = LfsConnectionFactory.getLfsConnection(
  113. getRepository(), METHOD_POST, OPERATION_UPLOAD);
  114. Map<String, LfsPointer> oid2ptr = requestBatchUpload(api, toPush);
  115. uploadContents(api, oid2ptr);
  116. return EMPTY;
  117. }
  118. private Set<LfsPointer> findObjectsToPush() throws IOException,
  119. MissingObjectException, IncorrectObjectTypeException {
  120. Set<LfsPointer> toPush = new TreeSet<>();
  121. try (ObjectWalk walk = new ObjectWalk(getRepository())) {
  122. for (RemoteRefUpdate up : refs) {
  123. walk.setRewriteParents(false);
  124. excludeRemoteRefs(walk);
  125. walk.markStart(walk.parseCommit(up.getNewObjectId()));
  126. while (walk.next() != null) {
  127. // walk all commits to populate objects
  128. }
  129. findLfsPointers(toPush, walk);
  130. }
  131. }
  132. return toPush;
  133. }
  134. private static void findLfsPointers(Set<LfsPointer> toPush, ObjectWalk walk)
  135. throws MissingObjectException, IncorrectObjectTypeException,
  136. IOException {
  137. RevObject obj;
  138. ObjectReader r = walk.getObjectReader();
  139. while ((obj = walk.nextObject()) != null) {
  140. if (obj.getType() == Constants.OBJ_BLOB
  141. && getObjectSize(r, obj) < LfsPointer.SIZE_THRESHOLD) {
  142. LfsPointer ptr = loadLfsPointer(r, obj);
  143. if (ptr != null) {
  144. toPush.add(ptr);
  145. }
  146. }
  147. }
  148. }
  149. private static long getObjectSize(ObjectReader r, RevObject obj)
  150. throws IOException {
  151. return r.getObjectSize(obj.getId(), Constants.OBJ_BLOB);
  152. }
  153. private static LfsPointer loadLfsPointer(ObjectReader r, AnyObjectId obj)
  154. throws IOException {
  155. try (InputStream is = r.open(obj, Constants.OBJ_BLOB).openStream()) {
  156. return LfsPointer.parseLfsPointer(is);
  157. }
  158. }
  159. private void excludeRemoteRefs(ObjectWalk walk) throws IOException {
  160. RefDatabase refDatabase = getRepository().getRefDatabase();
  161. Map<String, Ref> remoteRefs = refDatabase.getRefs(remote());
  162. for (Ref r : remoteRefs.values()) {
  163. ObjectId oid = r.getPeeledObjectId();
  164. if (oid == null) {
  165. oid = r.getObjectId();
  166. }
  167. if (oid == null) {
  168. // ignore (e.g. symbolic, ...)
  169. continue;
  170. }
  171. RevObject o = walk.parseAny(oid);
  172. if (o.getType() == Constants.OBJ_COMMIT
  173. || o.getType() == Constants.OBJ_TAG) {
  174. walk.markUninteresting(o);
  175. }
  176. }
  177. }
  178. private String remote() {
  179. String remoteName = getRemoteName() == null
  180. ? Constants.DEFAULT_REMOTE_NAME
  181. : getRemoteName();
  182. return Constants.R_REMOTES + remoteName;
  183. }
  184. private Map<String, LfsPointer> requestBatchUpload(HttpConnection api,
  185. Set<LfsPointer> toPush) throws IOException {
  186. LfsPointer[] res = toPush.toArray(new LfsPointer[toPush.size()]);
  187. Map<String, LfsPointer> oidStr2ptr = new HashMap<>();
  188. for (LfsPointer p : res) {
  189. oidStr2ptr.put(p.getOid().name(), p);
  190. }
  191. Gson gson = Protocol.gson();
  192. api.getOutputStream().write(
  193. gson.toJson(toRequest(OPERATION_UPLOAD, res)).getBytes(UTF_8));
  194. int responseCode = api.getResponseCode();
  195. if (responseCode != HTTP_OK) {
  196. throw new IOException(
  197. MessageFormat.format(LfsText.get().serverFailure,
  198. api.getURL(), Integer.valueOf(responseCode)));
  199. }
  200. return oidStr2ptr;
  201. }
  202. private void uploadContents(HttpConnection api,
  203. Map<String, LfsPointer> oid2ptr) throws IOException {
  204. try (JsonReader reader = new JsonReader(
  205. new InputStreamReader(api.getInputStream()))) {
  206. for (Protocol.ObjectInfo o : parseObjects(reader)) {
  207. if (o.actions == null) {
  208. continue;
  209. }
  210. LfsPointer ptr = oid2ptr.get(o.oid);
  211. if (ptr == null) {
  212. // received an object we didn't request
  213. continue;
  214. }
  215. Protocol.Action uploadAction = o.actions.get(OPERATION_UPLOAD);
  216. if (uploadAction == null || uploadAction.href == null) {
  217. continue;
  218. }
  219. Lfs lfs = new Lfs(getRepository());
  220. Path path = lfs.getMediaFile(ptr.getOid());
  221. if (!Files.exists(path)) {
  222. throw new IOException(MessageFormat
  223. .format(LfsText.get().missingLocalObject, path));
  224. }
  225. uploadFile(o, uploadAction, path);
  226. }
  227. }
  228. }
  229. private List<ObjectInfo> parseObjects(JsonReader reader) {
  230. Gson gson = new Gson();
  231. Protocol.Response resp = gson.fromJson(reader, Protocol.Response.class);
  232. return resp.objects;
  233. }
  234. private void uploadFile(Protocol.ObjectInfo o,
  235. Protocol.Action uploadAction, Path path)
  236. throws IOException, CorruptMediaFile {
  237. HttpConnection contentServer = LfsConnectionFactory
  238. .getLfsContentConnection(getRepository(), uploadAction,
  239. METHOD_PUT);
  240. contentServer.setDoOutput(true);
  241. try (OutputStream out = contentServer
  242. .getOutputStream()) {
  243. long size = Files.copy(path, out);
  244. if (size != o.size) {
  245. throw new CorruptMediaFile(path, o.size, size);
  246. }
  247. }
  248. int responseCode = contentServer.getResponseCode();
  249. if (responseCode != HTTP_OK) {
  250. throw new IOException(MessageFormat.format(
  251. LfsText.get().serverFailure, contentServer.getURL(),
  252. Integer.valueOf(responseCode)));
  253. }
  254. }
  255. }