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.

PatchsetReceivePack.java 43KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328
  1. /*
  2. * Copyright 2013 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 static org.eclipse.jgit.transport.BasePackPushConnection.CAPABILITY_SIDE_BAND_64K;
  18. import java.io.IOException;
  19. import java.text.MessageFormat;
  20. import java.util.ArrayList;
  21. import java.util.Arrays;
  22. import java.util.Collection;
  23. import java.util.LinkedHashMap;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.Set;
  27. import java.util.concurrent.TimeUnit;
  28. import java.util.regex.Matcher;
  29. import java.util.regex.Pattern;
  30. import org.eclipse.jgit.lib.AnyObjectId;
  31. import org.eclipse.jgit.lib.BatchRefUpdate;
  32. import org.eclipse.jgit.lib.NullProgressMonitor;
  33. import org.eclipse.jgit.lib.ObjectId;
  34. import org.eclipse.jgit.lib.PersonIdent;
  35. import org.eclipse.jgit.lib.ProgressMonitor;
  36. import org.eclipse.jgit.lib.Ref;
  37. import org.eclipse.jgit.lib.RefUpdate;
  38. import org.eclipse.jgit.lib.Repository;
  39. import org.eclipse.jgit.revwalk.RevCommit;
  40. import org.eclipse.jgit.revwalk.RevSort;
  41. import org.eclipse.jgit.revwalk.RevWalk;
  42. import org.eclipse.jgit.transport.ReceiveCommand;
  43. import org.eclipse.jgit.transport.ReceiveCommand.Result;
  44. import org.eclipse.jgit.transport.ReceiveCommand.Type;
  45. import org.eclipse.jgit.transport.ReceivePack;
  46. import org.slf4j.Logger;
  47. import org.slf4j.LoggerFactory;
  48. import com.gitblit.Constants;
  49. import com.gitblit.Keys;
  50. import com.gitblit.extensions.PatchsetHook;
  51. import com.gitblit.manager.IGitblit;
  52. import com.gitblit.models.RepositoryModel;
  53. import com.gitblit.models.TicketModel;
  54. import com.gitblit.models.TicketModel.Change;
  55. import com.gitblit.models.TicketModel.Field;
  56. import com.gitblit.models.TicketModel.Patchset;
  57. import com.gitblit.models.TicketModel.PatchsetType;
  58. import com.gitblit.models.TicketModel.Status;
  59. import com.gitblit.models.UserModel;
  60. import com.gitblit.tickets.BranchTicketService;
  61. import com.gitblit.tickets.ITicketService;
  62. import com.gitblit.tickets.TicketMilestone;
  63. import com.gitblit.tickets.TicketNotifier;
  64. import com.gitblit.utils.ArrayUtils;
  65. import com.gitblit.utils.DiffUtils;
  66. import com.gitblit.utils.DiffUtils.DiffStat;
  67. import com.gitblit.utils.JGitUtils;
  68. import com.gitblit.utils.JGitUtils.MergeResult;
  69. import com.gitblit.utils.JGitUtils.MergeStatus;
  70. import com.gitblit.utils.RefLogUtils;
  71. import com.gitblit.utils.StringUtils;
  72. import com.google.common.collect.Lists;
  73. /**
  74. * PatchsetReceivePack processes receive commands and allows for creating, updating,
  75. * and closing Gitblit tickets. It also executes Groovy pre- and post- receive
  76. * hooks.
  77. *
  78. * The patchset mechanism defined in this class is based on the ReceiveCommits class
  79. * from the Gerrit code review server.
  80. *
  81. * The general execution flow is:
  82. * <ol>
  83. * <li>onPreReceive()</li>
  84. * <li>executeCommands()</li>
  85. * <li>onPostReceive()</li>
  86. * </ol>
  87. *
  88. * @author Android Open Source Project
  89. * @author James Moger
  90. *
  91. */
  92. public class PatchsetReceivePack extends GitblitReceivePack {
  93. protected static final List<String> MAGIC_REFS = Arrays.asList(Constants.R_FOR, Constants.R_TICKET);
  94. protected static final Pattern NEW_PATCHSET =
  95. Pattern.compile("^refs/tickets/(?:[0-9a-zA-Z][0-9a-zA-Z]/)?([1-9][0-9]*)(?:/new)?$");
  96. private static final Logger LOGGER = LoggerFactory.getLogger(PatchsetReceivePack.class);
  97. protected final ITicketService ticketService;
  98. protected final TicketNotifier ticketNotifier;
  99. private boolean requireMergeablePatchset;
  100. public PatchsetReceivePack(IGitblit gitblit, Repository db, RepositoryModel repository, UserModel user) {
  101. super(gitblit, db, repository, user);
  102. this.ticketService = gitblit.getTicketService();
  103. this.ticketNotifier = ticketService.createNotifier();
  104. }
  105. /** Returns the patchset ref root from the ref */
  106. private String getPatchsetRef(String refName) {
  107. for (String patchRef : MAGIC_REFS) {
  108. if (refName.startsWith(patchRef)) {
  109. return patchRef;
  110. }
  111. }
  112. return null;
  113. }
  114. /** Checks if the supplied ref name is a patchset ref */
  115. private boolean isPatchsetRef(String refName) {
  116. return !StringUtils.isEmpty(getPatchsetRef(refName));
  117. }
  118. /** Checks if the supplied ref name is a change ref */
  119. private boolean isTicketRef(String refName) {
  120. return refName.startsWith(Constants.R_TICKETS_PATCHSETS);
  121. }
  122. /** Extracts the integration branch from the ref name */
  123. private String getIntegrationBranch(String refName) {
  124. String patchsetRef = getPatchsetRef(refName);
  125. String branch = refName.substring(patchsetRef.length());
  126. if (branch.indexOf('%') > -1) {
  127. branch = branch.substring(0, branch.indexOf('%'));
  128. }
  129. String defaultBranch = "master";
  130. try {
  131. defaultBranch = getRepository().getBranch();
  132. } catch (Exception e) {
  133. LOGGER.error("failed to determine default branch for " + repository.name, e);
  134. }
  135. if (!StringUtils.isEmpty(getRepositoryModel().mergeTo)) {
  136. // repository settings specifies a default integration branch
  137. defaultBranch = Repository.shortenRefName(getRepositoryModel().mergeTo);
  138. }
  139. long ticketId = 0L;
  140. try {
  141. ticketId = Long.parseLong(branch);
  142. } catch (Exception e) {
  143. // not a number
  144. }
  145. if (ticketId > 0 || branch.equalsIgnoreCase("default") || branch.equalsIgnoreCase("new")) {
  146. return defaultBranch;
  147. }
  148. return branch;
  149. }
  150. /** Extracts the ticket id from the ref name */
  151. private long getTicketId(String refName) {
  152. if (refName.indexOf('%') > -1) {
  153. refName = refName.substring(0, refName.indexOf('%'));
  154. }
  155. if (refName.startsWith(Constants.R_FOR)) {
  156. String ref = refName.substring(Constants.R_FOR.length());
  157. try {
  158. return Long.parseLong(ref);
  159. } catch (Exception e) {
  160. // not a number
  161. }
  162. } else if (refName.startsWith(Constants.R_TICKET) ||
  163. refName.startsWith(Constants.R_TICKETS_PATCHSETS)) {
  164. return PatchsetCommand.getTicketNumber(refName);
  165. }
  166. return 0L;
  167. }
  168. /** Returns true if the ref namespace exists */
  169. private boolean hasRefNamespace(String ref) {
  170. Map<String, Ref> blockingFors;
  171. try {
  172. blockingFors = getRepository().getRefDatabase().getRefs(ref);
  173. } catch (IOException err) {
  174. sendError("Cannot scan refs in {0}", repository.name);
  175. LOGGER.error("Error!", err);
  176. return true;
  177. }
  178. if (!blockingFors.isEmpty()) {
  179. sendError("{0} needs the following refs removed to receive patchsets: {1}",
  180. repository.name, blockingFors.keySet());
  181. return true;
  182. }
  183. return false;
  184. }
  185. /** Removes change ref receive commands */
  186. private List<ReceiveCommand> excludeTicketCommands(Collection<ReceiveCommand> commands) {
  187. List<ReceiveCommand> filtered = new ArrayList<ReceiveCommand>();
  188. for (ReceiveCommand cmd : commands) {
  189. if (!isTicketRef(cmd.getRefName())) {
  190. // this is not a ticket ref update
  191. filtered.add(cmd);
  192. }
  193. }
  194. return filtered;
  195. }
  196. /** Removes patchset receive commands for pre- and post- hook integrations */
  197. private List<ReceiveCommand> excludePatchsetCommands(Collection<ReceiveCommand> commands) {
  198. List<ReceiveCommand> filtered = new ArrayList<ReceiveCommand>();
  199. for (ReceiveCommand cmd : commands) {
  200. if (!isPatchsetRef(cmd.getRefName())) {
  201. // this is a non-patchset ref update
  202. filtered.add(cmd);
  203. }
  204. }
  205. return filtered;
  206. }
  207. /** Process receive commands EXCEPT for Patchset commands. */
  208. @Override
  209. public void onPreReceive(ReceivePack rp, Collection<ReceiveCommand> commands) {
  210. Collection<ReceiveCommand> filtered = excludePatchsetCommands(commands);
  211. super.onPreReceive(rp, filtered);
  212. }
  213. /** Process receive commands EXCEPT for Patchset commands. */
  214. @Override
  215. public void onPostReceive(ReceivePack rp, Collection<ReceiveCommand> commands) {
  216. Collection<ReceiveCommand> filtered = excludePatchsetCommands(commands);
  217. super.onPostReceive(rp, filtered);
  218. // send all queued ticket notifications after processing all patchsets
  219. ticketNotifier.sendAll();
  220. }
  221. @Override
  222. protected void validateCommands() {
  223. // workaround for JGit's awful scoping choices
  224. //
  225. // set the patchset refs to OK to bypass checks in the super implementation
  226. for (final ReceiveCommand cmd : filterCommands(Result.NOT_ATTEMPTED)) {
  227. if (isPatchsetRef(cmd.getRefName())) {
  228. if (cmd.getType() == ReceiveCommand.Type.CREATE) {
  229. cmd.setResult(Result.OK);
  230. }
  231. }
  232. }
  233. super.validateCommands();
  234. }
  235. /** Execute commands to update references. */
  236. @Override
  237. protected void executeCommands() {
  238. // we process patchsets unless the user is pushing something special
  239. boolean processPatchsets = true;
  240. for (ReceiveCommand cmd : filterCommands(Result.NOT_ATTEMPTED)) {
  241. if (ticketService instanceof BranchTicketService
  242. && BranchTicketService.BRANCH.equals(cmd.getRefName())) {
  243. // the user is pushing an update to the BranchTicketService data
  244. processPatchsets = false;
  245. }
  246. }
  247. // workaround for JGit's awful scoping choices
  248. //
  249. // reset the patchset refs to NOT_ATTEMPTED (see validateCommands)
  250. for (ReceiveCommand cmd : filterCommands(Result.OK)) {
  251. if (isPatchsetRef(cmd.getRefName())) {
  252. cmd.setResult(Result.NOT_ATTEMPTED);
  253. } else if (ticketService instanceof BranchTicketService
  254. && BranchTicketService.BRANCH.equals(cmd.getRefName())) {
  255. // the user is pushing an update to the BranchTicketService data
  256. processPatchsets = false;
  257. }
  258. }
  259. List<ReceiveCommand> toApply = filterCommands(Result.NOT_ATTEMPTED);
  260. if (toApply.isEmpty()) {
  261. return;
  262. }
  263. ProgressMonitor updating = NullProgressMonitor.INSTANCE;
  264. boolean sideBand = isCapabilityEnabled(CAPABILITY_SIDE_BAND_64K);
  265. if (sideBand) {
  266. SideBandProgressMonitor pm = new SideBandProgressMonitor(msgOut);
  267. pm.setDelayStart(250, TimeUnit.MILLISECONDS);
  268. updating = pm;
  269. }
  270. BatchRefUpdate batch = getRepository().getRefDatabase().newBatchUpdate();
  271. batch.setAllowNonFastForwards(isAllowNonFastForwards());
  272. batch.setRefLogIdent(getRefLogIdent());
  273. batch.setRefLogMessage("push", true);
  274. ReceiveCommand patchsetRefCmd = null;
  275. PatchsetCommand patchsetCmd = null;
  276. for (ReceiveCommand cmd : toApply) {
  277. if (Result.NOT_ATTEMPTED != cmd.getResult()) {
  278. // Already rejected by the core receive process.
  279. continue;
  280. }
  281. if (isPatchsetRef(cmd.getRefName()) && processPatchsets) {
  282. if (ticketService == null) {
  283. sendRejection(cmd, "Sorry, the ticket service is unavailable and can not accept patchsets at this time.");
  284. continue;
  285. }
  286. if (!ticketService.isReady()) {
  287. sendRejection(cmd, "Sorry, the ticket service can not accept patchsets at this time.");
  288. continue;
  289. }
  290. if (UserModel.ANONYMOUS.equals(user)) {
  291. // server allows anonymous pushes, but anonymous patchset
  292. // contributions are prohibited by design
  293. sendRejection(cmd, "Sorry, anonymous patchset contributions are prohibited.");
  294. continue;
  295. }
  296. final Matcher m = NEW_PATCHSET.matcher(cmd.getRefName());
  297. if (m.matches()) {
  298. // prohibit pushing directly to a patchset ref
  299. long id = getTicketId(cmd.getRefName());
  300. sendError("You may not directly push directly to a patchset ref!");
  301. sendError("Instead, please push to one the following:");
  302. sendError(" - {0}{1,number,0}", Constants.R_FOR, id);
  303. sendError(" - {0}{1,number,0}", Constants.R_TICKET, id);
  304. sendRejection(cmd, "protected ref");
  305. continue;
  306. }
  307. if (hasRefNamespace(Constants.R_FOR)) {
  308. // the refs/for/ namespace exists and it must not
  309. LOGGER.error("{} already has refs in the {} namespace",
  310. repository.name, Constants.R_FOR);
  311. sendRejection(cmd, "Sorry, a repository administrator will have to remove the {} namespace", Constants.R_FOR);
  312. continue;
  313. }
  314. if (cmd.getNewId().equals(ObjectId.zeroId())) {
  315. // ref deletion request
  316. if (cmd.getRefName().startsWith(Constants.R_TICKET)) {
  317. if (user.canDeleteRef(repository)) {
  318. batch.addCommand(cmd);
  319. } else {
  320. sendRejection(cmd, "Sorry, you do not have permission to delete {}", cmd.getRefName());
  321. }
  322. } else {
  323. sendRejection(cmd, "Sorry, you can not delete {}", cmd.getRefName());
  324. }
  325. continue;
  326. }
  327. if (patchsetRefCmd != null) {
  328. sendRejection(cmd, "You may only push one patchset at a time.");
  329. continue;
  330. }
  331. LOGGER.info(MessageFormat.format("Verifying {0} push ref \"{1}\" received from {2}",
  332. repository.name, cmd.getRefName(), user.username));
  333. // responsible verification
  334. String responsible = PatchsetCommand.getSingleOption(cmd, PatchsetCommand.RESPONSIBLE);
  335. if (!StringUtils.isEmpty(responsible)) {
  336. UserModel assignee = gitblit.getUserModel(responsible);
  337. if (assignee == null) {
  338. // no account by this name
  339. sendRejection(cmd, "{0} can not be assigned any tickets because there is no user account by that name", responsible);
  340. continue;
  341. } else if (!assignee.canPush(repository)) {
  342. // account does not have RW permissions
  343. sendRejection(cmd, "{0} ({1}) can not be assigned any tickets because the user does not have RW permissions for {2}",
  344. assignee.getDisplayName(), assignee.username, repository.name);
  345. continue;
  346. }
  347. }
  348. // milestone verification
  349. String milestone = PatchsetCommand.getSingleOption(cmd, PatchsetCommand.MILESTONE);
  350. if (!StringUtils.isEmpty(milestone)) {
  351. TicketMilestone milestoneModel = ticketService.getMilestone(repository, milestone);
  352. if (milestoneModel == null) {
  353. // milestone does not exist
  354. sendRejection(cmd, "Sorry, \"{0}\" is not a valid milestone!", milestone);
  355. continue;
  356. }
  357. }
  358. // watcher verification
  359. List<String> watchers = PatchsetCommand.getOptions(cmd, PatchsetCommand.WATCH);
  360. if (!ArrayUtils.isEmpty(watchers)) {
  361. boolean verified = true;
  362. for (String watcher : watchers) {
  363. UserModel user = gitblit.getUserModel(watcher);
  364. if (user == null) {
  365. // watcher does not exist
  366. sendRejection(cmd, "Sorry, \"{0}\" is not a valid username for the watch list!", watcher);
  367. verified = false;
  368. break;
  369. }
  370. }
  371. if (!verified) {
  372. continue;
  373. }
  374. }
  375. patchsetRefCmd = cmd;
  376. patchsetCmd = preparePatchset(cmd);
  377. if (patchsetCmd != null) {
  378. batch.addCommand(patchsetCmd);
  379. }
  380. continue;
  381. }
  382. batch.addCommand(cmd);
  383. }
  384. if (!batch.getCommands().isEmpty()) {
  385. try {
  386. batch.execute(getRevWalk(), updating);
  387. } catch (IOException err) {
  388. for (ReceiveCommand cmd : toApply) {
  389. if (cmd.getResult() == Result.NOT_ATTEMPTED) {
  390. sendRejection(cmd, "lock error: {0}", err.getMessage());
  391. LOGGER.error(MessageFormat.format("failed to lock {0}:{1}",
  392. repository.name, cmd.getRefName()), err);
  393. }
  394. }
  395. }
  396. }
  397. //
  398. // set the results into the patchset ref receive command
  399. //
  400. if (patchsetRefCmd != null && patchsetCmd != null) {
  401. if (!patchsetCmd.getResult().equals(Result.OK)) {
  402. // patchset command failed!
  403. LOGGER.error(patchsetCmd.getType() + " " + patchsetCmd.getRefName()
  404. + " " + patchsetCmd.getResult());
  405. patchsetRefCmd.setResult(patchsetCmd.getResult(), patchsetCmd.getMessage());
  406. } else {
  407. // all patchset commands were applied
  408. patchsetRefCmd.setResult(Result.OK);
  409. // update the ticket branch ref
  410. RefUpdate ru = updateRef(
  411. patchsetCmd.getTicketBranch(),
  412. patchsetCmd.getNewId(),
  413. patchsetCmd.getPatchsetType());
  414. updateReflog(ru);
  415. TicketModel ticket = processPatchset(patchsetCmd);
  416. if (ticket != null) {
  417. ticketNotifier.queueMailing(ticket);
  418. }
  419. }
  420. }
  421. //
  422. // if there are standard ref update receive commands that were
  423. // successfully processed, process referenced tickets, if any
  424. //
  425. List<ReceiveCommand> allUpdates = ReceiveCommand.filter(batch.getCommands(), Result.OK);
  426. List<ReceiveCommand> refUpdates = excludePatchsetCommands(allUpdates);
  427. List<ReceiveCommand> stdUpdates = excludeTicketCommands(refUpdates);
  428. if (!stdUpdates.isEmpty()) {
  429. int ticketsProcessed = 0;
  430. for (ReceiveCommand cmd : stdUpdates) {
  431. switch (cmd.getType()) {
  432. case CREATE:
  433. case UPDATE:
  434. case UPDATE_NONFASTFORWARD:
  435. if (cmd.getRefName().startsWith(Constants.R_HEADS)) {
  436. Collection<TicketModel> tickets = processMergedTickets(cmd);
  437. ticketsProcessed += tickets.size();
  438. for (TicketModel ticket : tickets) {
  439. ticketNotifier.queueMailing(ticket);
  440. }
  441. }
  442. break;
  443. default:
  444. break;
  445. }
  446. }
  447. if (ticketsProcessed == 1) {
  448. sendInfo("1 ticket updated");
  449. } else if (ticketsProcessed > 1) {
  450. sendInfo("{0} tickets updated", ticketsProcessed);
  451. }
  452. }
  453. // reset the ticket caches for the repository
  454. ticketService.resetCaches(repository);
  455. }
  456. /**
  457. * Prepares a patchset command.
  458. *
  459. * @param cmd
  460. * @return the patchset command
  461. */
  462. private PatchsetCommand preparePatchset(ReceiveCommand cmd) {
  463. String branch = getIntegrationBranch(cmd.getRefName());
  464. long number = getTicketId(cmd.getRefName());
  465. TicketModel ticket = null;
  466. if (number > 0 && ticketService.hasTicket(repository, number)) {
  467. ticket = ticketService.getTicket(repository, number);
  468. }
  469. if (ticket == null) {
  470. if (number > 0) {
  471. // requested ticket does not exist
  472. sendError("Sorry, {0} does not have ticket {1,number,0}!", repository.name, number);
  473. sendRejection(cmd, "Invalid ticket number");
  474. return null;
  475. }
  476. } else {
  477. if (ticket.isMerged()) {
  478. // ticket already merged & resolved
  479. Change mergeChange = null;
  480. for (Change change : ticket.changes) {
  481. if (change.isMerge()) {
  482. mergeChange = change;
  483. break;
  484. }
  485. }
  486. if (mergeChange != null) {
  487. sendError("Sorry, {0} already merged {1} from ticket {2,number,0} to {3}!",
  488. mergeChange.author, mergeChange.patchset, number, ticket.mergeTo);
  489. }
  490. sendRejection(cmd, "Ticket {0,number,0} already resolved", number);
  491. return null;
  492. } else if (!StringUtils.isEmpty(ticket.mergeTo)) {
  493. // ticket specifies integration branch
  494. branch = ticket.mergeTo;
  495. }
  496. }
  497. final int shortCommitIdLen = settings.getInteger(Keys.web.shortCommitIdLength, 6);
  498. final String shortTipId = cmd.getNewId().getName().substring(0, shortCommitIdLen);
  499. final RevCommit tipCommit = JGitUtils.getCommit(getRepository(), cmd.getNewId().getName());
  500. final String forBranch = branch;
  501. RevCommit mergeBase = null;
  502. Ref forBranchRef = getAdvertisedRefs().get(Constants.R_HEADS + forBranch);
  503. if (forBranchRef == null || forBranchRef.getObjectId() == null) {
  504. // unknown integration branch
  505. sendError("Sorry, there is no integration branch named ''{0}''.", forBranch);
  506. sendRejection(cmd, "Invalid integration branch specified");
  507. return null;
  508. } else {
  509. // determine the merge base for the patchset on the integration branch
  510. String base = JGitUtils.getMergeBase(getRepository(), forBranchRef.getObjectId(), tipCommit.getId());
  511. if (StringUtils.isEmpty(base)) {
  512. sendError("");
  513. sendError("There is no common ancestry between {0} and {1}.", forBranch, shortTipId);
  514. sendError("Please reconsider your proposed integration branch, {0}.", forBranch);
  515. sendError("");
  516. sendRejection(cmd, "no merge base for patchset and {0}", forBranch);
  517. return null;
  518. }
  519. mergeBase = JGitUtils.getCommit(getRepository(), base);
  520. }
  521. // ensure that the patchset can be cleanly merged right now
  522. MergeStatus status = JGitUtils.canMerge(getRepository(), tipCommit.getName(), forBranch);
  523. switch (status) {
  524. case ALREADY_MERGED:
  525. sendError("");
  526. sendError("You have already merged this patchset.", forBranch);
  527. sendError("");
  528. sendRejection(cmd, "everything up-to-date");
  529. return null;
  530. case MERGEABLE:
  531. break;
  532. default:
  533. if (ticket == null || requireMergeablePatchset) {
  534. sendError("");
  535. sendError("Your patchset can not be cleanly merged into {0}.", forBranch);
  536. sendError("Please rebase your patchset and push again.");
  537. sendError("NOTE:", number);
  538. sendError("You should push your rebase to refs/for/{0,number,0}", number);
  539. sendError("");
  540. sendError(" git push origin HEAD:refs/for/{0,number,0}", number);
  541. sendError("");
  542. sendRejection(cmd, "patchset not mergeable");
  543. return null;
  544. }
  545. }
  546. // check to see if this commit is already linked to a ticket
  547. long id = identifyTicket(tipCommit, false);
  548. if (id > 0) {
  549. sendError("{0} has already been pushed to ticket {1,number,0}.", shortTipId, id);
  550. sendRejection(cmd, "everything up-to-date");
  551. return null;
  552. }
  553. PatchsetCommand psCmd;
  554. if (ticket == null) {
  555. /*
  556. * NEW TICKET
  557. */
  558. Patchset patchset = newPatchset(null, mergeBase.getName(), tipCommit.getName());
  559. int minLength = 10;
  560. int maxLength = 100;
  561. String minTitle = MessageFormat.format(" minimum length of a title is {0} characters.", minLength);
  562. String maxTitle = MessageFormat.format(" maximum length of a title is {0} characters.", maxLength);
  563. if (patchset.commits > 1) {
  564. sendError("");
  565. sendError("You may not create a ''{0}'' branch proposal ticket from {1} commits!",
  566. forBranch, patchset.commits);
  567. sendError("");
  568. // display an ellipsized log of the commits being pushed
  569. RevWalk walk = getRevWalk();
  570. walk.reset();
  571. walk.sort(RevSort.TOPO);
  572. int boundary = 3;
  573. int count = 0;
  574. try {
  575. walk.markStart(tipCommit);
  576. walk.markUninteresting(mergeBase);
  577. for (;;) {
  578. RevCommit c = walk.next();
  579. if (c == null) {
  580. break;
  581. }
  582. if (count < boundary || count >= (patchset.commits - boundary)) {
  583. walk.parseBody(c);
  584. sendError(" {0} {1}", c.getName().substring(0, shortCommitIdLen),
  585. StringUtils.trimString(c.getShortMessage(), 60));
  586. } else if (count == boundary) {
  587. sendError(" ... more commits ...");
  588. }
  589. count++;
  590. }
  591. } catch (IOException e) {
  592. // Should never happen, the core receive process would have
  593. // identified the missing object earlier before we got control.
  594. LOGGER.error("failed to get commit count", e);
  595. } finally {
  596. walk.close();
  597. }
  598. sendError("");
  599. sendError("Possible Solutions:");
  600. sendError("");
  601. int solution = 1;
  602. String forSpec = cmd.getRefName().substring(Constants.R_FOR.length());
  603. if (forSpec.equals("default") || forSpec.equals("new")) {
  604. try {
  605. // determine other possible integration targets
  606. List<String> bases = Lists.newArrayList();
  607. for (Ref ref : getRepository().getRefDatabase().getRefs(Constants.R_HEADS).values()) {
  608. if (!ref.getName().startsWith(Constants.R_TICKET)
  609. && !ref.getName().equals(forBranchRef.getName())) {
  610. if (JGitUtils.isMergedInto(getRepository(), ref.getObjectId(), tipCommit)) {
  611. bases.add(Repository.shortenRefName(ref.getName()));
  612. }
  613. }
  614. }
  615. if (!bases.isEmpty()) {
  616. if (bases.size() == 1) {
  617. // suggest possible integration targets
  618. String base = bases.get(0);
  619. sendError("{0}. Propose this change for the ''{1}'' branch.", solution++, base);
  620. sendError("");
  621. sendError(" git push origin HEAD:refs/for/{0}", base);
  622. sendError(" pt propose {0}", base);
  623. sendError("");
  624. } else {
  625. // suggest possible integration targets
  626. sendError("{0}. Propose this change for a different branch.", solution++);
  627. sendError("");
  628. for (String base : bases) {
  629. sendError(" git push origin HEAD:refs/for/{0}", base);
  630. sendError(" pt propose {0}", base);
  631. sendError("");
  632. }
  633. }
  634. }
  635. } catch (IOException e) {
  636. LOGGER.error(null, e);
  637. }
  638. }
  639. sendError("{0}. Squash your changes into a single commit with a meaningful message.", solution++);
  640. sendError("");
  641. sendError("{0}. Open a ticket for your changes and then push your {1} commits to the ticket.",
  642. solution++, patchset.commits);
  643. sendError("");
  644. sendError(" git push origin HEAD:refs/for/{id}");
  645. sendError(" pt propose {id}");
  646. sendError("");
  647. sendRejection(cmd, "too many commits");
  648. return null;
  649. }
  650. // require a reasonable title/subject
  651. String title = tipCommit.getFullMessage().trim().split("\n")[0];
  652. if (title.length() < minLength) {
  653. // reject, title too short
  654. sendError("");
  655. sendError("Please supply a longer title in your commit message!");
  656. sendError("");
  657. sendError(minTitle);
  658. sendError(maxTitle);
  659. sendError("");
  660. sendRejection(cmd, "ticket title is too short [{0}/{1}]", title.length(), maxLength);
  661. return null;
  662. }
  663. if (title.length() > maxLength) {
  664. // reject, title too long
  665. sendError("");
  666. sendError("Please supply a more concise title in your commit message!");
  667. sendError("");
  668. sendError(minTitle);
  669. sendError(maxTitle);
  670. sendError("");
  671. sendRejection(cmd, "ticket title is too long [{0}/{1}]", title.length(), maxLength);
  672. return null;
  673. }
  674. // assign new id
  675. long ticketId = ticketService.assignNewId(repository);
  676. // create the patchset command
  677. psCmd = new PatchsetCommand(user.username, patchset);
  678. psCmd.newTicket(tipCommit, forBranch, ticketId, cmd.getRefName());
  679. } else {
  680. /*
  681. * EXISTING TICKET
  682. */
  683. Patchset patchset = newPatchset(ticket, mergeBase.getName(), tipCommit.getName());
  684. psCmd = new PatchsetCommand(user.username, patchset);
  685. psCmd.updateTicket(tipCommit, forBranch, ticket, cmd.getRefName());
  686. }
  687. // confirm user can push the patchset
  688. boolean pushPermitted = ticket == null
  689. || !ticket.hasPatchsets()
  690. || ticket.isAuthor(user.username)
  691. || ticket.isPatchsetAuthor(user.username)
  692. || ticket.isResponsible(user.username)
  693. || user.canPush(repository);
  694. switch (psCmd.getPatchsetType()) {
  695. case Proposal:
  696. // proposals (first patchset) are always acceptable
  697. break;
  698. case FastForward:
  699. // patchset updates must be permitted
  700. if (!pushPermitted) {
  701. // reject
  702. sendError("");
  703. sendError("To push a patchset to this ticket one of the following must be true:");
  704. sendError(" 1. you created the ticket");
  705. sendError(" 2. you created the first patchset");
  706. sendError(" 3. you are specified as responsible for the ticket");
  707. sendError(" 4. you have push (RW) permissions to {0}", repository.name);
  708. sendError("");
  709. sendRejection(cmd, "not permitted to push to ticket {0,number,0}", ticket.number);
  710. return null;
  711. }
  712. break;
  713. default:
  714. // non-fast-forward push
  715. if (!pushPermitted) {
  716. // reject
  717. sendRejection(cmd, "non-fast-forward ({0})", psCmd.getPatchsetType());
  718. return null;
  719. }
  720. break;
  721. }
  722. return psCmd;
  723. }
  724. /**
  725. * Creates or updates an ticket with the specified patchset.
  726. *
  727. * @param cmd
  728. * @return a ticket if the creation or update was successful
  729. */
  730. private TicketModel processPatchset(PatchsetCommand cmd) {
  731. Change change = cmd.getChange();
  732. if (cmd.isNewTicket()) {
  733. // create the ticket object
  734. TicketModel ticket = ticketService.createTicket(repository, cmd.getTicketId(), change);
  735. if (ticket != null) {
  736. sendInfo("");
  737. sendHeader("#{0,number,0}: {1}", ticket.number, StringUtils.trimString(ticket.title, Constants.LEN_SHORTLOG));
  738. sendInfo("created proposal ticket from patchset");
  739. sendInfo(ticketService.getTicketUrl(ticket));
  740. sendInfo("");
  741. // log the new patch ref
  742. RefLogUtils.updateRefLog(user, getRepository(),
  743. Arrays.asList(new ReceiveCommand(cmd.getOldId(), cmd.getNewId(), cmd.getRefName())));
  744. // call any patchset hooks
  745. for (PatchsetHook hook : gitblit.getExtensions(PatchsetHook.class)) {
  746. try {
  747. hook.onNewPatchset(ticket);
  748. } catch (Exception e) {
  749. LOGGER.error("Failed to execute extension", e);
  750. }
  751. }
  752. return ticket;
  753. } else {
  754. sendError("FAILED to create ticket");
  755. }
  756. } else {
  757. // update an existing ticket
  758. TicketModel ticket = ticketService.updateTicket(repository, cmd.getTicketId(), change);
  759. if (ticket != null) {
  760. sendInfo("");
  761. sendHeader("#{0,number,0}: {1}", ticket.number, StringUtils.trimString(ticket.title, Constants.LEN_SHORTLOG));
  762. if (change.patchset.rev == 1) {
  763. // new patchset
  764. sendInfo("uploaded patchset {0} ({1})", change.patchset.number, change.patchset.type.toString());
  765. } else {
  766. // updated patchset
  767. sendInfo("added {0} {1} to patchset {2}",
  768. change.patchset.added,
  769. change.patchset.added == 1 ? "commit" : "commits",
  770. change.patchset.number);
  771. }
  772. sendInfo(ticketService.getTicketUrl(ticket));
  773. sendInfo("");
  774. // log the new patchset ref
  775. RefLogUtils.updateRefLog(user, getRepository(),
  776. Arrays.asList(new ReceiveCommand(cmd.getOldId(), cmd.getNewId(), cmd.getRefName())));
  777. // call any patchset hooks
  778. final boolean isNewPatchset = change.patchset.rev == 1;
  779. for (PatchsetHook hook : gitblit.getExtensions(PatchsetHook.class)) {
  780. try {
  781. if (isNewPatchset) {
  782. hook.onNewPatchset(ticket);
  783. } else {
  784. hook.onUpdatePatchset(ticket);
  785. }
  786. } catch (Exception e) {
  787. LOGGER.error("Failed to execute extension", e);
  788. }
  789. }
  790. // return the updated ticket
  791. return ticket;
  792. } else {
  793. sendError("FAILED to upload {0} for ticket {1,number,0}", change.patchset, cmd.getTicketId());
  794. }
  795. }
  796. return null;
  797. }
  798. /**
  799. * Automatically closes open tickets that have been merged to their integration
  800. * branch by a client.
  801. *
  802. * @param cmd
  803. */
  804. private Collection<TicketModel> processMergedTickets(ReceiveCommand cmd) {
  805. Map<Long, TicketModel> mergedTickets = new LinkedHashMap<Long, TicketModel>();
  806. final RevWalk rw = getRevWalk();
  807. try {
  808. rw.reset();
  809. rw.markStart(rw.parseCommit(cmd.getNewId()));
  810. if (!ObjectId.zeroId().equals(cmd.getOldId())) {
  811. rw.markUninteresting(rw.parseCommit(cmd.getOldId()));
  812. }
  813. RevCommit c;
  814. while ((c = rw.next()) != null) {
  815. rw.parseBody(c);
  816. long ticketNumber = identifyTicket(c, true);
  817. if (ticketNumber == 0L || mergedTickets.containsKey(ticketNumber)) {
  818. continue;
  819. }
  820. TicketModel ticket = ticketService.getTicket(repository, ticketNumber);
  821. if (ticket == null) {
  822. continue;
  823. }
  824. String integrationBranch;
  825. if (StringUtils.isEmpty(ticket.mergeTo)) {
  826. // unspecified integration branch
  827. integrationBranch = null;
  828. } else {
  829. // specified integration branch
  830. integrationBranch = Constants.R_HEADS + ticket.mergeTo;
  831. }
  832. // ticket must be open and, if specified, the ref must match the integration branch
  833. if (ticket.isClosed() || (integrationBranch != null && !integrationBranch.equals(cmd.getRefName()))) {
  834. continue;
  835. }
  836. String baseRef = PatchsetCommand.getBasePatchsetBranch(ticket.number);
  837. boolean knownPatchset = false;
  838. Set<Ref> refs = getRepository().getAllRefsByPeeledObjectId().get(c.getId());
  839. if (refs != null) {
  840. for (Ref ref : refs) {
  841. if (ref.getName().startsWith(baseRef)) {
  842. knownPatchset = true;
  843. break;
  844. }
  845. }
  846. }
  847. String mergeSha = c.getName();
  848. String mergeTo = Repository.shortenRefName(cmd.getRefName());
  849. Change change;
  850. Patchset patchset;
  851. if (knownPatchset) {
  852. // identify merged patchset by the patchset tip
  853. patchset = null;
  854. for (Patchset ps : ticket.getPatchsets()) {
  855. if (ps.tip.equals(mergeSha)) {
  856. patchset = ps;
  857. break;
  858. }
  859. }
  860. if (patchset == null) {
  861. // should not happen - unless ticket has been hacked
  862. sendError("Failed to find the patchset for {0} in ticket {1,number,0}?!",
  863. mergeSha, ticket.number);
  864. continue;
  865. }
  866. // create a new change
  867. change = new Change(user.username);
  868. } else {
  869. // new patchset pushed by user
  870. String base = cmd.getOldId().getName();
  871. patchset = newPatchset(ticket, base, mergeSha);
  872. PatchsetCommand psCmd = new PatchsetCommand(user.username, patchset);
  873. psCmd.updateTicket(c, mergeTo, ticket, null);
  874. // create a ticket patchset ref
  875. updateRef(psCmd.getPatchsetBranch(), c.getId(), patchset.type);
  876. RefUpdate ru = updateRef(psCmd.getTicketBranch(), c.getId(), patchset.type);
  877. updateReflog(ru);
  878. // create a change from the patchset command
  879. change = psCmd.getChange();
  880. }
  881. // set the common change data about the merge
  882. change.setField(Field.status, Status.Merged);
  883. change.setField(Field.mergeSha, mergeSha);
  884. change.setField(Field.mergeTo, mergeTo);
  885. if (StringUtils.isEmpty(ticket.responsible)) {
  886. // unassigned tickets are assigned to the closer
  887. change.setField(Field.responsible, user.username);
  888. }
  889. ticket = ticketService.updateTicket(repository, ticket.number, change);
  890. if (ticket != null) {
  891. sendInfo("");
  892. sendHeader("#{0,number,0}: {1}", ticket.number, StringUtils.trimString(ticket.title, Constants.LEN_SHORTLOG));
  893. sendInfo("closed by push of {0} to {1}", patchset, mergeTo);
  894. sendInfo(ticketService.getTicketUrl(ticket));
  895. sendInfo("");
  896. mergedTickets.put(ticket.number, ticket);
  897. } else {
  898. String shortid = mergeSha.substring(0, settings.getInteger(Keys.web.shortCommitIdLength, 6));
  899. sendError("FAILED to close ticket {0,number,0} by push of {1}", ticketNumber, shortid);
  900. }
  901. }
  902. } catch (IOException e) {
  903. LOGGER.error("Can't scan for changes to close", e);
  904. } finally {
  905. rw.reset();
  906. }
  907. return mergedTickets.values();
  908. }
  909. /**
  910. * Try to identify a ticket id from the commit.
  911. *
  912. * @param commit
  913. * @param parseMessage
  914. * @return a ticket id or 0
  915. */
  916. private long identifyTicket(RevCommit commit, boolean parseMessage) {
  917. // try lookup by change ref
  918. Map<AnyObjectId, Set<Ref>> map = getRepository().getAllRefsByPeeledObjectId();
  919. Set<Ref> refs = map.get(commit.getId());
  920. if (!ArrayUtils.isEmpty(refs)) {
  921. for (Ref ref : refs) {
  922. long number = PatchsetCommand.getTicketNumber(ref.getName());
  923. if (number > 0) {
  924. return number;
  925. }
  926. }
  927. }
  928. if (parseMessage) {
  929. // parse commit message looking for fixes/closes #n
  930. String dx = "(?:fixes|closes)[\\s-]+#?(\\d+)";
  931. String x = settings.getString(Keys.tickets.closeOnPushCommitMessageRegex, dx);
  932. if (StringUtils.isEmpty(x)) {
  933. x = dx;
  934. }
  935. try {
  936. Pattern p = Pattern.compile(x, Pattern.CASE_INSENSITIVE);
  937. Matcher m = p.matcher(commit.getFullMessage());
  938. while (m.find()) {
  939. String val = m.group(1);
  940. return Long.parseLong(val);
  941. }
  942. } catch (Exception e) {
  943. LOGGER.error(String.format("Failed to parse \"%s\" in commit %s", x, commit.getName()), e);
  944. }
  945. }
  946. return 0L;
  947. }
  948. private int countCommits(String baseId, String tipId) {
  949. int count = 0;
  950. RevWalk walk = getRevWalk();
  951. walk.reset();
  952. walk.sort(RevSort.TOPO);
  953. walk.sort(RevSort.REVERSE, true);
  954. try {
  955. RevCommit tip = walk.parseCommit(getRepository().resolve(tipId));
  956. RevCommit base = walk.parseCommit(getRepository().resolve(baseId));
  957. walk.markStart(tip);
  958. walk.markUninteresting(base);
  959. for (;;) {
  960. RevCommit c = walk.next();
  961. if (c == null) {
  962. break;
  963. }
  964. count++;
  965. }
  966. } catch (IOException e) {
  967. // Should never happen, the core receive process would have
  968. // identified the missing object earlier before we got control.
  969. LOGGER.error("failed to get commit count", e);
  970. return 0;
  971. } finally {
  972. walk.close();
  973. }
  974. return count;
  975. }
  976. /**
  977. * Creates a new patchset with metadata.
  978. *
  979. * @param ticket
  980. * @param mergeBase
  981. * @param tip
  982. */
  983. private Patchset newPatchset(TicketModel ticket, String mergeBase, String tip) {
  984. int totalCommits = countCommits(mergeBase, tip);
  985. Patchset newPatchset = new Patchset();
  986. newPatchset.tip = tip;
  987. newPatchset.base = mergeBase;
  988. newPatchset.commits = totalCommits;
  989. Patchset currPatchset = ticket == null ? null : ticket.getCurrentPatchset();
  990. if (currPatchset == null) {
  991. /*
  992. * PROPOSAL PATCHSET
  993. * patchset 1, rev 1
  994. */
  995. newPatchset.number = 1;
  996. newPatchset.rev = 1;
  997. newPatchset.type = PatchsetType.Proposal;
  998. // diffstat from merge base
  999. DiffStat diffStat = DiffUtils.getDiffStat(getRepository(), mergeBase, tip);
  1000. newPatchset.insertions = diffStat.getInsertions();
  1001. newPatchset.deletions = diffStat.getDeletions();
  1002. } else {
  1003. /*
  1004. * PATCHSET UPDATE
  1005. */
  1006. int added = totalCommits - currPatchset.commits;
  1007. boolean ff = JGitUtils.isMergedInto(getRepository(), currPatchset.tip, tip);
  1008. boolean squash = added < 0;
  1009. boolean rebase = !currPatchset.base.equals(mergeBase);
  1010. // determine type, number and rev of the patchset
  1011. if (ff) {
  1012. /*
  1013. * FAST-FORWARD
  1014. * patchset number preserved, rev incremented
  1015. */
  1016. boolean merged = JGitUtils.isMergedInto(getRepository(), currPatchset.tip, ticket.mergeTo);
  1017. if (merged) {
  1018. // current patchset was already merged
  1019. // new patchset, mark as rebase
  1020. newPatchset.type = PatchsetType.Rebase;
  1021. newPatchset.number = currPatchset.number + 1;
  1022. newPatchset.rev = 1;
  1023. // diffstat from parent
  1024. DiffStat diffStat = DiffUtils.getDiffStat(getRepository(), mergeBase, tip);
  1025. newPatchset.insertions = diffStat.getInsertions();
  1026. newPatchset.deletions = diffStat.getDeletions();
  1027. } else {
  1028. // FF update to patchset
  1029. newPatchset.type = PatchsetType.FastForward;
  1030. newPatchset.number = currPatchset.number;
  1031. newPatchset.rev = currPatchset.rev + 1;
  1032. newPatchset.parent = currPatchset.tip;
  1033. // diffstat from parent
  1034. DiffStat diffStat = DiffUtils.getDiffStat(getRepository(), currPatchset.tip, tip);
  1035. newPatchset.insertions = diffStat.getInsertions();
  1036. newPatchset.deletions = diffStat.getDeletions();
  1037. }
  1038. } else {
  1039. /*
  1040. * NON-FAST-FORWARD
  1041. * new patchset, rev 1
  1042. */
  1043. if (rebase && squash) {
  1044. newPatchset.type = PatchsetType.Rebase_Squash;
  1045. newPatchset.number = currPatchset.number + 1;
  1046. newPatchset.rev = 1;
  1047. } else if (squash) {
  1048. newPatchset.type = PatchsetType.Squash;
  1049. newPatchset.number = currPatchset.number + 1;
  1050. newPatchset.rev = 1;
  1051. } else if (rebase) {
  1052. newPatchset.type = PatchsetType.Rebase;
  1053. newPatchset.number = currPatchset.number + 1;
  1054. newPatchset.rev = 1;
  1055. } else {
  1056. newPatchset.type = PatchsetType.Amend;
  1057. newPatchset.number = currPatchset.number + 1;
  1058. newPatchset.rev = 1;
  1059. }
  1060. // diffstat from merge base
  1061. DiffStat diffStat = DiffUtils.getDiffStat(getRepository(), mergeBase, tip);
  1062. newPatchset.insertions = diffStat.getInsertions();
  1063. newPatchset.deletions = diffStat.getDeletions();
  1064. }
  1065. if (added > 0) {
  1066. // ignore squash (negative add)
  1067. newPatchset.added = added;
  1068. }
  1069. }
  1070. return newPatchset;
  1071. }
  1072. private RefUpdate updateRef(String ref, ObjectId newId, PatchsetType type) {
  1073. ObjectId ticketRefId = ObjectId.zeroId();
  1074. try {
  1075. ticketRefId = getRepository().resolve(ref);
  1076. } catch (Exception e) {
  1077. // ignore
  1078. }
  1079. try {
  1080. RefUpdate ru = getRepository().updateRef(ref, false);
  1081. ru.setRefLogIdent(getRefLogIdent());
  1082. switch (type) {
  1083. case Amend:
  1084. case Rebase:
  1085. case Rebase_Squash:
  1086. case Squash:
  1087. ru.setForceUpdate(true);
  1088. break;
  1089. default:
  1090. break;
  1091. }
  1092. ru.setExpectedOldObjectId(ticketRefId);
  1093. ru.setNewObjectId(newId);
  1094. RefUpdate.Result result = ru.update(getRevWalk());
  1095. if (result == RefUpdate.Result.LOCK_FAILURE) {
  1096. sendError("Failed to obtain lock when updating {0}:{1}", repository.name, ref);
  1097. sendError("Perhaps an administrator should remove {0}/{1}.lock?", getRepository().getDirectory(), ref);
  1098. return null;
  1099. }
  1100. return ru;
  1101. } catch (IOException e) {
  1102. LOGGER.error("failed to update ref " + ref, e);
  1103. sendError("There was an error updating ref {0}:{1}", repository.name, ref);
  1104. }
  1105. return null;
  1106. }
  1107. private void updateReflog(RefUpdate ru) {
  1108. if (ru == null) {
  1109. return;
  1110. }
  1111. ReceiveCommand.Type type = null;
  1112. switch (ru.getResult()) {
  1113. case NEW:
  1114. type = Type.CREATE;
  1115. break;
  1116. case FAST_FORWARD:
  1117. type = Type.UPDATE;
  1118. break;
  1119. case FORCED:
  1120. type = Type.UPDATE_NONFASTFORWARD;
  1121. break;
  1122. default:
  1123. LOGGER.error(MessageFormat.format("unexpected ref update type {0} for {1}",
  1124. ru.getResult(), ru.getName()));
  1125. return;
  1126. }
  1127. ReceiveCommand cmd = new ReceiveCommand(ru.getOldObjectId(), ru.getNewObjectId(), ru.getName(), type);
  1128. RefLogUtils.updateRefLog(user, getRepository(), Arrays.asList(cmd));
  1129. }
  1130. /**
  1131. * Merge the specified patchset to the integration branch.
  1132. *
  1133. * @param ticket
  1134. * @param patchset
  1135. * @return true, if successful
  1136. */
  1137. public MergeStatus merge(TicketModel ticket) {
  1138. PersonIdent committer = new PersonIdent(user.getDisplayName(), StringUtils.isEmpty(user.emailAddress) ? (user.username + "@gitblit") : user.emailAddress);
  1139. Patchset patchset = ticket.getCurrentPatchset();
  1140. String message = MessageFormat.format("Merged #{0,number,0} \"{1}\"", ticket.number, ticket.title);
  1141. Ref oldRef = null;
  1142. try {
  1143. oldRef = getRepository().getRef(ticket.mergeTo);
  1144. } catch (IOException e) {
  1145. LOGGER.error("failed to get ref for " + ticket.mergeTo, e);
  1146. }
  1147. MergeResult mergeResult = JGitUtils.merge(
  1148. getRepository(),
  1149. patchset.tip,
  1150. ticket.mergeTo,
  1151. committer,
  1152. message);
  1153. if (StringUtils.isEmpty(mergeResult.sha)) {
  1154. LOGGER.error("FAILED to merge {} to {} ({})", new Object [] { patchset, ticket.mergeTo, mergeResult.status.name() });
  1155. return mergeResult.status;
  1156. }
  1157. Change change = new Change(user.username);
  1158. change.setField(Field.status, Status.Merged);
  1159. change.setField(Field.mergeSha, mergeResult.sha);
  1160. change.setField(Field.mergeTo, ticket.mergeTo);
  1161. if (StringUtils.isEmpty(ticket.responsible)) {
  1162. // unassigned tickets are assigned to the closer
  1163. change.setField(Field.responsible, user.username);
  1164. }
  1165. long ticketId = ticket.number;
  1166. ticket = ticketService.updateTicket(repository, ticket.number, change);
  1167. if (ticket != null) {
  1168. ticketNotifier.queueMailing(ticket);
  1169. if (oldRef != null) {
  1170. ReceiveCommand cmd = new ReceiveCommand(oldRef.getObjectId(),
  1171. ObjectId.fromString(mergeResult.sha), oldRef.getName());
  1172. cmd.setResult(Result.OK);
  1173. List<ReceiveCommand> commands = Arrays.asList(cmd);
  1174. logRefChange(commands);
  1175. updateIncrementalPushTags(commands);
  1176. updateGitblitRefLog(commands);
  1177. }
  1178. // call patchset hooks
  1179. for (PatchsetHook hook : gitblit.getExtensions(PatchsetHook.class)) {
  1180. try {
  1181. hook.onMergePatchset(ticket);
  1182. } catch (Exception e) {
  1183. LOGGER.error("Failed to execute extension", e);
  1184. }
  1185. }
  1186. return mergeResult.status;
  1187. } else {
  1188. LOGGER.error("FAILED to resolve ticket {} by merge from web ui", ticketId);
  1189. }
  1190. return mergeResult.status;
  1191. }
  1192. public void sendAll() {
  1193. ticketNotifier.sendAll();
  1194. }
  1195. }