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

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