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

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