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 44KB

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