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.

LfsPrePushHook.java 7.8KB

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