Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

ReceiveHook.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. /*
  2. * Copyright 2011 gitblit.com.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.gitblit.git;
  17. import groovy.lang.Binding;
  18. import groovy.util.GroovyScriptEngine;
  19. import java.io.File;
  20. import java.io.IOException;
  21. import java.text.MessageFormat;
  22. import java.util.Collection;
  23. import java.util.LinkedHashSet;
  24. import java.util.List;
  25. import java.util.Set;
  26. import org.eclipse.jgit.lib.PersonIdent;
  27. import org.eclipse.jgit.revwalk.RevCommit;
  28. import org.eclipse.jgit.transport.PostReceiveHook;
  29. import org.eclipse.jgit.transport.PreReceiveHook;
  30. import org.eclipse.jgit.transport.ReceiveCommand;
  31. import org.eclipse.jgit.transport.ReceiveCommand.Result;
  32. import org.eclipse.jgit.transport.ReceivePack;
  33. import org.slf4j.Logger;
  34. import org.slf4j.LoggerFactory;
  35. import com.gitblit.Constants.AccessRestrictionType;
  36. import com.gitblit.GitBlit;
  37. import com.gitblit.Keys;
  38. import com.gitblit.client.Translation;
  39. import com.gitblit.models.RepositoryModel;
  40. import com.gitblit.models.UserModel;
  41. import com.gitblit.utils.ClientLogger;
  42. import com.gitblit.utils.JGitUtils;
  43. import com.gitblit.utils.PushLogUtils;
  44. import com.gitblit.utils.StringUtils;
  45. /**
  46. * The Gitblit receive hook allows for special processing on push events.
  47. * That might include rejecting writes to specific branches or executing a
  48. * script.
  49. *
  50. * @author James Moger
  51. *
  52. */
  53. public class ReceiveHook implements PreReceiveHook, PostReceiveHook {
  54. protected final Logger logger = LoggerFactory.getLogger(ReceiveHook.class);
  55. protected UserModel user;
  56. protected RepositoryModel repository;
  57. protected String gitblitUrl;
  58. private GroovyScriptEngine gse;
  59. private File groovyDir;
  60. public ReceiveHook() {
  61. groovyDir = GitBlit.getGroovyScriptsFolder();
  62. try {
  63. // set Grape root
  64. File grapeRoot = GitBlit.getFileOrFolder(Keys.groovy.grapeFolder, "${baseFolder}/groovy/grape").getAbsoluteFile();
  65. grapeRoot.mkdirs();
  66. System.setProperty("grape.root", grapeRoot.getAbsolutePath());
  67. gse = new GroovyScriptEngine(groovyDir.getAbsolutePath());
  68. } catch (IOException e) {
  69. //throw new ServletException("Failed to instantiate Groovy Script Engine!", e);
  70. }
  71. }
  72. /**
  73. * Instrumentation point where the incoming push event has been parsed,
  74. * validated, objects created BUT refs have not been updated. You might
  75. * use this to enforce a branch-write permissions model.
  76. */
  77. @Override
  78. public void onPreReceive(ReceivePack rp, Collection<ReceiveCommand> commands) {
  79. if (repository.isFrozen) {
  80. // repository is frozen/readonly
  81. String reason = MessageFormat.format("Gitblit does not allow pushes to \"{0}\" because it is frozen!", repository.name);
  82. logger.warn(reason);
  83. for (ReceiveCommand cmd : commands) {
  84. cmd.setResult(Result.REJECTED_OTHER_REASON, reason);
  85. }
  86. return;
  87. }
  88. if (!repository.isBare) {
  89. // repository has a working copy
  90. String reason = MessageFormat.format("Gitblit does not allow pushes to \"{0}\" because it has a working copy!", repository.name);
  91. logger.warn(reason);
  92. for (ReceiveCommand cmd : commands) {
  93. cmd.setResult(Result.REJECTED_OTHER_REASON, reason);
  94. }
  95. return;
  96. }
  97. if (!user.canPush(repository)) {
  98. // user does not have push permissions
  99. String reason = MessageFormat.format("User \"{0}\" does not have push permissions for \"{1}\"!", user.username, repository.name);
  100. logger.warn(reason);
  101. for (ReceiveCommand cmd : commands) {
  102. cmd.setResult(Result.REJECTED_OTHER_REASON, reason);
  103. }
  104. return;
  105. }
  106. if (repository.accessRestriction.atLeast(AccessRestrictionType.PUSH) && repository.verifyCommitter) {
  107. // enforce committer verification
  108. if (StringUtils.isEmpty(user.emailAddress)) {
  109. // emit warning if user does not have an email address
  110. logger.warn(MessageFormat.format("Consider setting an email address for {0} ({1}) to improve committer verification.", user.getDisplayName(), user.username));
  111. }
  112. // Optionally enforce that the committer of the left parent chain
  113. // match the account being used to push the commits.
  114. //
  115. // This requires all merge commits are executed with the "--no-ff"
  116. // option to force a merge commit even if fast-forward is possible.
  117. // This ensures that the chain of left parents has the commit
  118. // identity of the merging user.
  119. boolean allRejected = false;
  120. for (ReceiveCommand cmd : commands) {
  121. try {
  122. List<RevCommit> commits = JGitUtils.getRevLog(rp.getRepository(), cmd.getOldId().name(), cmd.getNewId().name());
  123. for (RevCommit commit : commits) {
  124. PersonIdent committer = commit.getCommitterIdent();
  125. if (!user.is(committer.getName(), committer.getEmailAddress())) {
  126. String reason;
  127. if (StringUtils.isEmpty(user.emailAddress)) {
  128. // account does not have en email address
  129. reason = MessageFormat.format("{0} by {1} <{2}> was not committed by {3} ({4})", commit.getId().name(), committer.getName(), StringUtils.isEmpty(committer.getEmailAddress()) ? "?":committer.getEmailAddress(), user.getDisplayName(), user.username);
  130. } else {
  131. // account has an email address
  132. reason = MessageFormat.format("{0} by {1} <{2}> was not committed by {3} ({4}) <{5}>", commit.getId().name(), committer.getName(), StringUtils.isEmpty(committer.getEmailAddress()) ? "?":committer.getEmailAddress(), user.getDisplayName(), user.username, user.emailAddress);
  133. }
  134. logger.warn(reason);
  135. cmd.setResult(Result.REJECTED_OTHER_REASON, reason);
  136. allRejected &= true;
  137. break;
  138. } else {
  139. allRejected = false;
  140. }
  141. }
  142. } catch (Exception e) {
  143. logger.error("Failed to verify commits were made by pushing user", e);
  144. }
  145. }
  146. if (allRejected) {
  147. // all ref updates rejected, abort
  148. return;
  149. }
  150. }
  151. Set<String> scripts = new LinkedHashSet<String>();
  152. scripts.addAll(GitBlit.self().getPreReceiveScriptsInherited(repository));
  153. scripts.addAll(repository.preReceiveScripts);
  154. runGroovy(repository, user, commands, rp, scripts);
  155. for (ReceiveCommand cmd : commands) {
  156. if (!Result.NOT_ATTEMPTED.equals(cmd.getResult())) {
  157. logger.warn(MessageFormat.format("{0} {1} because \"{2}\"", cmd.getNewId()
  158. .getName(), cmd.getResult(), cmd.getMessage()));
  159. }
  160. }
  161. }
  162. /**
  163. * Instrumentation point where the incoming push has been applied to the
  164. * repository. This is the point where we would trigger a Jenkins build
  165. * or send an email.
  166. */
  167. @Override
  168. public void onPostReceive(ReceivePack rp, Collection<ReceiveCommand> commands) {
  169. if (commands.size() == 0) {
  170. logger.debug("skipping post-receive hooks, no refs created, updated, or removed");
  171. return;
  172. }
  173. // log ref changes
  174. for (ReceiveCommand cmd : commands) {
  175. if (Result.OK.equals(cmd.getResult())) {
  176. // add some logging for important ref changes
  177. switch (cmd.getType()) {
  178. case DELETE:
  179. logger.info(MessageFormat.format("{0} DELETED {1} in {2} ({3})", user.username, cmd.getRefName(), repository.name, cmd.getOldId().name()));
  180. break;
  181. case CREATE:
  182. logger.info(MessageFormat.format("{0} CREATED {1} in {2}", user.username, cmd.getRefName(), repository.name));
  183. break;
  184. case UPDATE:
  185. logger.info(MessageFormat.format("{0} UPDATED {1} in {2} (from {3} to {4})", user.username, cmd.getRefName(), repository.name, cmd.getOldId().name(), cmd.getNewId().name()));
  186. break;
  187. case UPDATE_NONFASTFORWARD:
  188. logger.info(MessageFormat.format("{0} UPDATED NON-FAST-FORWARD {1} in {2} (from {3} to {4})", user.username, cmd.getRefName(), repository.name, cmd.getOldId().name(), cmd.getNewId().name()));
  189. break;
  190. default:
  191. break;
  192. }
  193. }
  194. }
  195. if (repository.useIncrementalPushTags) {
  196. // tag each pushed branch tip
  197. String emailAddress = user.emailAddress == null ? rp.getRefLogIdent().getEmailAddress() : user.emailAddress;
  198. PersonIdent userIdent = new PersonIdent(user.getDisplayName(), emailAddress);
  199. for (ReceiveCommand cmd : commands) {
  200. if (!cmd.getRefName().startsWith("refs/heads/")) {
  201. // only tag branch ref changes
  202. continue;
  203. }
  204. if (!ReceiveCommand.Type.DELETE.equals(cmd.getType())
  205. && ReceiveCommand.Result.OK.equals(cmd.getResult())) {
  206. String objectId = cmd.getNewId().getName();
  207. String branch = cmd.getRefName().substring("refs/heads/".length());
  208. // get translation based on the server's locale setting
  209. String template = Translation.get("gb.incrementalPushTagMessage");
  210. String msg = MessageFormat.format(template, branch);
  211. String prefix;
  212. if (StringUtils.isEmpty(repository.incrementalPushTagPrefix)) {
  213. prefix = GitBlit.getString(Keys.git.defaultIncrementalPushTagPrefix, "r");
  214. } else {
  215. prefix = repository.incrementalPushTagPrefix;
  216. }
  217. JGitUtils.createIncrementalRevisionTag(
  218. rp.getRepository(),
  219. objectId,
  220. userIdent,
  221. prefix,
  222. "0",
  223. msg);
  224. }
  225. }
  226. }
  227. // update push log
  228. try {
  229. PushLogUtils.updatePushLog(user, rp.getRepository(), commands);
  230. logger.debug(MessageFormat.format("{0} push log updated", repository.name));
  231. } catch (Exception e) {
  232. logger.error(MessageFormat.format("Failed to update {0} pushlog", repository.name), e);
  233. }
  234. // run Groovy hook scripts
  235. Set<String> scripts = new LinkedHashSet<String>();
  236. scripts.addAll(GitBlit.self().getPostReceiveScriptsInherited(repository));
  237. scripts.addAll(repository.postReceiveScripts);
  238. runGroovy(repository, user, commands, rp, scripts);
  239. }
  240. /**
  241. * Runs the specified Groovy hook scripts.
  242. *
  243. * @param repository
  244. * @param user
  245. * @param commands
  246. * @param scripts
  247. */
  248. protected void runGroovy(RepositoryModel repository, UserModel user,
  249. Collection<ReceiveCommand> commands, ReceivePack rp, Set<String> scripts) {
  250. if (scripts == null || scripts.size() == 0) {
  251. // no Groovy scripts to execute
  252. return;
  253. }
  254. Binding binding = new Binding();
  255. binding.setVariable("gitblit", GitBlit.self());
  256. binding.setVariable("repository", repository);
  257. binding.setVariable("receivePack", rp);
  258. binding.setVariable("user", user);
  259. binding.setVariable("commands", commands);
  260. binding.setVariable("url", gitblitUrl);
  261. binding.setVariable("logger", logger);
  262. binding.setVariable("clientLogger", new ClientLogger(rp));
  263. for (String script : scripts) {
  264. if (StringUtils.isEmpty(script)) {
  265. continue;
  266. }
  267. // allow script to be specified without .groovy extension
  268. // this is easier to read in the settings
  269. File file = new File(groovyDir, script);
  270. if (!file.exists() && !script.toLowerCase().endsWith(".groovy")) {
  271. file = new File(groovyDir, script + ".groovy");
  272. if (file.exists()) {
  273. script = file.getName();
  274. }
  275. }
  276. try {
  277. Object result = gse.run(script, binding);
  278. if (result instanceof Boolean) {
  279. if (!((Boolean) result)) {
  280. logger.error(MessageFormat.format(
  281. "Groovy script {0} has failed! Hook scripts aborted.", script));
  282. break;
  283. }
  284. }
  285. } catch (Exception e) {
  286. logger.error(
  287. MessageFormat.format("Failed to execute Groovy script {0}", script), e);
  288. }
  289. }
  290. }
  291. }