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.

IssueUtils.java 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. /*
  2. * Copyright 2012 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.utils;
  17. import java.io.IOException;
  18. import java.text.MessageFormat;
  19. import java.util.ArrayList;
  20. import java.util.Collection;
  21. import java.util.Collections;
  22. import java.util.HashMap;
  23. import java.util.HashSet;
  24. import java.util.Iterator;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.Set;
  28. import java.util.TreeSet;
  29. import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
  30. import org.eclipse.jgit.api.errors.JGitInternalException;
  31. import org.eclipse.jgit.dircache.DirCache;
  32. import org.eclipse.jgit.dircache.DirCacheBuilder;
  33. import org.eclipse.jgit.dircache.DirCacheEntry;
  34. import org.eclipse.jgit.internal.JGitText;
  35. import org.eclipse.jgit.lib.CommitBuilder;
  36. import org.eclipse.jgit.lib.Constants;
  37. import org.eclipse.jgit.lib.FileMode;
  38. import org.eclipse.jgit.lib.ObjectId;
  39. import org.eclipse.jgit.lib.ObjectInserter;
  40. import org.eclipse.jgit.lib.PersonIdent;
  41. import org.eclipse.jgit.lib.RefUpdate;
  42. import org.eclipse.jgit.lib.RefUpdate.Result;
  43. import org.eclipse.jgit.lib.Repository;
  44. import org.eclipse.jgit.revwalk.RevCommit;
  45. import org.eclipse.jgit.revwalk.RevTree;
  46. import org.eclipse.jgit.revwalk.RevWalk;
  47. import org.eclipse.jgit.treewalk.CanonicalTreeParser;
  48. import org.eclipse.jgit.treewalk.TreeWalk;
  49. import org.eclipse.jgit.treewalk.filter.AndTreeFilter;
  50. import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
  51. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  52. import org.slf4j.Logger;
  53. import org.slf4j.LoggerFactory;
  54. import com.gitblit.models.IssueModel;
  55. import com.gitblit.models.IssueModel.Attachment;
  56. import com.gitblit.models.IssueModel.Change;
  57. import com.gitblit.models.IssueModel.Field;
  58. import com.gitblit.models.IssueModel.Status;
  59. import com.gitblit.models.RefModel;
  60. import com.gitblit.utils.JsonUtils.ExcludeField;
  61. import com.google.gson.Gson;
  62. import com.google.gson.reflect.TypeToken;
  63. /**
  64. * Utility class for reading Gitblit issues.
  65. *
  66. * @author James Moger
  67. *
  68. */
  69. public class IssueUtils {
  70. public static interface IssueFilter {
  71. public abstract boolean accept(IssueModel issue);
  72. }
  73. public static final String GB_ISSUES = "refs/gitblit/issues";
  74. static final Logger LOGGER = LoggerFactory.getLogger(IssueUtils.class);
  75. /**
  76. * Log an error message and exception.
  77. *
  78. * @param t
  79. * @param repository
  80. * if repository is not null it MUST be the {0} parameter in the
  81. * pattern.
  82. * @param pattern
  83. * @param objects
  84. */
  85. private static void error(Throwable t, Repository repository, String pattern, Object... objects) {
  86. List<Object> parameters = new ArrayList<Object>();
  87. if (objects != null && objects.length > 0) {
  88. for (Object o : objects) {
  89. parameters.add(o);
  90. }
  91. }
  92. if (repository != null) {
  93. parameters.add(0, repository.getDirectory().getAbsolutePath());
  94. }
  95. LOGGER.error(MessageFormat.format(pattern, parameters.toArray()), t);
  96. }
  97. /**
  98. * Returns a RefModel for the gb-issues branch in the repository. If the
  99. * branch can not be found, null is returned.
  100. *
  101. * @param repository
  102. * @return a refmodel for the gb-issues branch or null
  103. */
  104. public static RefModel getIssuesBranch(Repository repository) {
  105. List<RefModel> refs = JGitUtils.getRefs(repository, com.gitblit.Constants.R_GITBLIT);
  106. for (RefModel ref : refs) {
  107. if (ref.reference.getName().equals(GB_ISSUES)) {
  108. return ref;
  109. }
  110. }
  111. return null;
  112. }
  113. /**
  114. * Returns all the issues in the repository. Querying issues from the
  115. * repository requires deserializing all changes for all issues. This is an
  116. * expensive process and not recommended. Issues should be indexed by Lucene
  117. * and queries should be executed against that index.
  118. *
  119. * @param repository
  120. * @param filter
  121. * optional issue filter to only return matching results
  122. * @return a list of issues
  123. */
  124. public static List<IssueModel> getIssues(Repository repository, IssueFilter filter) {
  125. List<IssueModel> list = new ArrayList<IssueModel>();
  126. RefModel issuesBranch = getIssuesBranch(repository);
  127. if (issuesBranch == null) {
  128. return list;
  129. }
  130. // Collect the set of all issue paths
  131. Set<String> issuePaths = new HashSet<String>();
  132. final TreeWalk tw = new TreeWalk(repository);
  133. try {
  134. RevCommit head = JGitUtils.getCommit(repository, GB_ISSUES);
  135. tw.addTree(head.getTree());
  136. tw.setRecursive(false);
  137. while (tw.next()) {
  138. if (tw.getDepth() < 2 && tw.isSubtree()) {
  139. tw.enterSubtree();
  140. if (tw.getDepth() == 2) {
  141. issuePaths.add(tw.getPathString());
  142. }
  143. }
  144. }
  145. } catch (IOException e) {
  146. error(e, repository, "{0} failed to query issues");
  147. } finally {
  148. tw.release();
  149. }
  150. // Build each issue and optionally filter out unwanted issues
  151. for (String issuePath : issuePaths) {
  152. RevWalk rw = new RevWalk(repository);
  153. try {
  154. RevCommit start = rw.parseCommit(repository.resolve(GB_ISSUES));
  155. rw.markStart(start);
  156. } catch (Exception e) {
  157. error(e, repository, "Failed to find {1} in {0}", GB_ISSUES);
  158. }
  159. TreeFilter treeFilter = AndTreeFilter.create(
  160. PathFilterGroup.createFromStrings(issuePath), TreeFilter.ANY_DIFF);
  161. rw.setTreeFilter(treeFilter);
  162. Iterator<RevCommit> revlog = rw.iterator();
  163. List<RevCommit> commits = new ArrayList<RevCommit>();
  164. while (revlog.hasNext()) {
  165. commits.add(revlog.next());
  166. }
  167. // release the revwalk
  168. rw.release();
  169. if (commits.size() == 0) {
  170. LOGGER.warn("Failed to find changes for issue " + issuePath);
  171. continue;
  172. }
  173. // sort by commit order, first commit first
  174. Collections.reverse(commits);
  175. StringBuilder sb = new StringBuilder("[");
  176. boolean first = true;
  177. for (RevCommit commit : commits) {
  178. if (!first) {
  179. sb.append(',');
  180. }
  181. String message = commit.getFullMessage();
  182. // commit message is formatted: C ISSUEID\n\nJSON
  183. // C is an single char commit code
  184. // ISSUEID is an SHA-1 hash
  185. String json = message.substring(43);
  186. sb.append(json);
  187. first = false;
  188. }
  189. sb.append(']');
  190. // Deserialize the JSON array as a Collection<Change>, this seems
  191. // slightly faster than deserializing each change by itself.
  192. Collection<Change> changes = JsonUtils.fromJsonString(sb.toString(),
  193. new TypeToken<Collection<Change>>() {
  194. }.getType());
  195. // create an issue object form the changes
  196. IssueModel issue = buildIssue(changes, true);
  197. // add the issue, conditionally, to the list
  198. if (filter == null) {
  199. list.add(issue);
  200. } else {
  201. if (filter.accept(issue)) {
  202. list.add(issue);
  203. }
  204. }
  205. }
  206. // sort the issues by creation
  207. Collections.sort(list);
  208. return list;
  209. }
  210. /**
  211. * Retrieves the specified issue from the repository with all changes
  212. * applied to build the effective issue.
  213. *
  214. * @param repository
  215. * @param issueId
  216. * @return an issue, if it exists, otherwise null
  217. */
  218. public static IssueModel getIssue(Repository repository, String issueId) {
  219. return getIssue(repository, issueId, true);
  220. }
  221. /**
  222. * Retrieves the specified issue from the repository.
  223. *
  224. * @param repository
  225. * @param issueId
  226. * @param effective
  227. * if true, the effective issue is built by processing comment
  228. * changes, deletions, etc. if false, the raw issue is built
  229. * without consideration for comment changes, deletions, etc.
  230. * @return an issue, if it exists, otherwise null
  231. */
  232. public static IssueModel getIssue(Repository repository, String issueId, boolean effective) {
  233. RefModel issuesBranch = getIssuesBranch(repository);
  234. if (issuesBranch == null) {
  235. return null;
  236. }
  237. if (StringUtils.isEmpty(issueId)) {
  238. return null;
  239. }
  240. String issuePath = getIssuePath(issueId);
  241. // Collect all changes as JSON array from commit messages
  242. List<RevCommit> commits = JGitUtils.getRevLog(repository, GB_ISSUES, issuePath, 0, -1);
  243. // sort by commit order, first commit first
  244. Collections.reverse(commits);
  245. StringBuilder sb = new StringBuilder("[");
  246. boolean first = true;
  247. for (RevCommit commit : commits) {
  248. if (!first) {
  249. sb.append(',');
  250. }
  251. String message = commit.getFullMessage();
  252. // commit message is formatted: C ISSUEID\n\nJSON
  253. // C is an single char commit code
  254. // ISSUEID is an SHA-1 hash
  255. String json = message.substring(43);
  256. sb.append(json);
  257. first = false;
  258. }
  259. sb.append(']');
  260. // Deserialize the JSON array as a Collection<Change>, this seems
  261. // slightly faster than deserializing each change by itself.
  262. Collection<Change> changes = JsonUtils.fromJsonString(sb.toString(),
  263. new TypeToken<Collection<Change>>() {
  264. }.getType());
  265. // create an issue object and apply the changes to it
  266. IssueModel issue = buildIssue(changes, effective);
  267. return issue;
  268. }
  269. /**
  270. * Builds an issue from a set of changes.
  271. *
  272. * @param changes
  273. * @param effective
  274. * if true, the effective issue is built which accounts for
  275. * comment changes, comment deletions, etc. if false, the raw
  276. * issue is built.
  277. * @return an issue
  278. */
  279. private static IssueModel buildIssue(Collection<Change> changes, boolean effective) {
  280. IssueModel issue;
  281. if (effective) {
  282. List<Change> effectiveChanges = new ArrayList<Change>();
  283. Map<String, Change> comments = new HashMap<String, Change>();
  284. for (Change change : changes) {
  285. if (change.comment != null) {
  286. if (comments.containsKey(change.comment.id)) {
  287. Change original = comments.get(change.comment.id);
  288. Change clone = DeepCopier.copy(original);
  289. clone.comment.text = change.comment.text;
  290. clone.comment.deleted = change.comment.deleted;
  291. int idx = effectiveChanges.indexOf(original);
  292. effectiveChanges.remove(original);
  293. effectiveChanges.add(idx, clone);
  294. comments.put(clone.comment.id, clone);
  295. } else {
  296. effectiveChanges.add(change);
  297. comments.put(change.comment.id, change);
  298. }
  299. } else {
  300. effectiveChanges.add(change);
  301. }
  302. }
  303. // effective issue
  304. issue = new IssueModel();
  305. for (Change change : effectiveChanges) {
  306. issue.applyChange(change);
  307. }
  308. } else {
  309. // raw issue
  310. issue = new IssueModel();
  311. for (Change change : changes) {
  312. issue.applyChange(change);
  313. }
  314. }
  315. return issue;
  316. }
  317. /**
  318. * Retrieves the specified attachment from an issue.
  319. *
  320. * @param repository
  321. * @param issueId
  322. * @param filename
  323. * @return an attachment, if found, null otherwise
  324. */
  325. public static Attachment getIssueAttachment(Repository repository, String issueId,
  326. String filename) {
  327. RefModel issuesBranch = getIssuesBranch(repository);
  328. if (issuesBranch == null) {
  329. return null;
  330. }
  331. if (StringUtils.isEmpty(issueId)) {
  332. return null;
  333. }
  334. // deserialize the issue model so that we have the attachment metadata
  335. IssueModel issue = getIssue(repository, issueId, true);
  336. Attachment attachment = issue.getAttachment(filename);
  337. // attachment not found
  338. if (attachment == null) {
  339. return null;
  340. }
  341. // retrieve the attachment content
  342. String issuePath = getIssuePath(issueId);
  343. RevTree tree = JGitUtils.getCommit(repository, GB_ISSUES).getTree();
  344. byte[] content = JGitUtils
  345. .getByteContent(repository, tree, issuePath + "/" + attachment.id, false);
  346. attachment.content = content;
  347. attachment.size = content.length;
  348. return attachment;
  349. }
  350. /**
  351. * Creates an issue in the gb-issues branch of the repository. The branch is
  352. * automatically created if it does not already exist. Your change must
  353. * include an author, summary, and description, at a minimum. If your change
  354. * does not have those minimum requirements a RuntimeException will be
  355. * thrown.
  356. *
  357. * @param repository
  358. * @param change
  359. * @return true if successful
  360. */
  361. public static IssueModel createIssue(Repository repository, Change change) {
  362. RefModel issuesBranch = getIssuesBranch(repository);
  363. if (issuesBranch == null) {
  364. JGitUtils.createOrphanBranch(repository, GB_ISSUES, null);
  365. }
  366. if (StringUtils.isEmpty(change.author)) {
  367. throw new RuntimeException("Must specify a change author!");
  368. }
  369. if (!change.hasField(Field.Summary)) {
  370. throw new RuntimeException("Must specify a summary!");
  371. }
  372. if (!change.hasField(Field.Description)) {
  373. throw new RuntimeException("Must specify a description!");
  374. }
  375. change.setField(Field.Reporter, change.author);
  376. String issueId = StringUtils.getSHA1(change.created.toString() + change.author
  377. + change.getString(Field.Summary) + change.getField(Field.Description));
  378. change.setField(Field.Id, issueId);
  379. change.code = '+';
  380. boolean success = commit(repository, issueId, change);
  381. if (success) {
  382. return getIssue(repository, issueId, false);
  383. }
  384. return null;
  385. }
  386. /**
  387. * Updates an issue in the gb-issues branch of the repository.
  388. *
  389. * @param repository
  390. * @param issueId
  391. * @param change
  392. * @return true if successful
  393. */
  394. public static boolean updateIssue(Repository repository, String issueId, Change change) {
  395. boolean success = false;
  396. RefModel issuesBranch = getIssuesBranch(repository);
  397. if (issuesBranch == null) {
  398. throw new RuntimeException("gb-issues branch does not exist!");
  399. }
  400. if (change == null) {
  401. throw new RuntimeException("change can not be null!");
  402. }
  403. if (StringUtils.isEmpty(change.author)) {
  404. throw new RuntimeException("must specify a change author!");
  405. }
  406. // determine update code
  407. // default update code is '=' for a general change
  408. change.code = '=';
  409. if (change.hasField(Field.Status)) {
  410. Status status = Status.fromObject(change.getField(Field.Status));
  411. if (status.isClosed()) {
  412. // someone closed the issue
  413. change.code = 'x';
  414. }
  415. }
  416. success = commit(repository, issueId, change);
  417. return success;
  418. }
  419. /**
  420. * Deletes an issue from the repository.
  421. *
  422. * @param repository
  423. * @param issueId
  424. * @return true if successful
  425. */
  426. public static boolean deleteIssue(Repository repository, String issueId, String author) {
  427. boolean success = false;
  428. RefModel issuesBranch = getIssuesBranch(repository);
  429. if (issuesBranch == null) {
  430. throw new RuntimeException(GB_ISSUES + " does not exist!");
  431. }
  432. if (StringUtils.isEmpty(issueId)) {
  433. throw new RuntimeException("must specify an issue id!");
  434. }
  435. String issuePath = getIssuePath(issueId);
  436. String message = "- " + issueId;
  437. try {
  438. ObjectId headId = repository.resolve(GB_ISSUES + "^{commit}");
  439. ObjectInserter odi = repository.newObjectInserter();
  440. try {
  441. // Create the in-memory index of the new/updated issue
  442. DirCache index = DirCache.newInCore();
  443. DirCacheBuilder dcBuilder = index.builder();
  444. // Traverse HEAD to add all other paths
  445. TreeWalk treeWalk = new TreeWalk(repository);
  446. int hIdx = -1;
  447. if (headId != null)
  448. hIdx = treeWalk.addTree(new RevWalk(repository).parseTree(headId));
  449. treeWalk.setRecursive(true);
  450. while (treeWalk.next()) {
  451. String path = treeWalk.getPathString();
  452. CanonicalTreeParser hTree = null;
  453. if (hIdx != -1)
  454. hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
  455. if (!path.startsWith(issuePath)) {
  456. // add entries from HEAD for all other paths
  457. if (hTree != null) {
  458. // create a new DirCacheEntry with data retrieved
  459. // from HEAD
  460. final DirCacheEntry dcEntry = new DirCacheEntry(path);
  461. dcEntry.setObjectId(hTree.getEntryObjectId());
  462. dcEntry.setFileMode(hTree.getEntryFileMode());
  463. // add to temporary in-core index
  464. dcBuilder.add(dcEntry);
  465. }
  466. }
  467. }
  468. // release the treewalk
  469. treeWalk.release();
  470. // finish temporary in-core index used for this commit
  471. dcBuilder.finish();
  472. ObjectId indexTreeId = index.writeTree(odi);
  473. // Create a commit object
  474. PersonIdent ident = new PersonIdent(author, "gitblit@localhost");
  475. CommitBuilder commit = new CommitBuilder();
  476. commit.setAuthor(ident);
  477. commit.setCommitter(ident);
  478. commit.setEncoding(Constants.CHARACTER_ENCODING);
  479. commit.setMessage(message);
  480. commit.setParentId(headId);
  481. commit.setTreeId(indexTreeId);
  482. // Insert the commit into the repository
  483. ObjectId commitId = odi.insert(commit);
  484. odi.flush();
  485. RevWalk revWalk = new RevWalk(repository);
  486. try {
  487. RevCommit revCommit = revWalk.parseCommit(commitId);
  488. RefUpdate ru = repository.updateRef(GB_ISSUES);
  489. ru.setNewObjectId(commitId);
  490. ru.setExpectedOldObjectId(headId);
  491. ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
  492. Result rc = ru.forceUpdate();
  493. switch (rc) {
  494. case NEW:
  495. case FORCED:
  496. case FAST_FORWARD:
  497. success = true;
  498. break;
  499. case REJECTED:
  500. case LOCK_FAILURE:
  501. throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD,
  502. ru.getRef(), rc);
  503. default:
  504. throw new JGitInternalException(MessageFormat.format(
  505. JGitText.get().updatingRefFailed, GB_ISSUES, commitId.toString(),
  506. rc));
  507. }
  508. } finally {
  509. revWalk.release();
  510. }
  511. } finally {
  512. odi.release();
  513. }
  514. } catch (Throwable t) {
  515. error(t, repository, "Failed to delete issue {1} to {0}", issueId);
  516. }
  517. return success;
  518. }
  519. /**
  520. * Changes the text of an issue comment.
  521. *
  522. * @param repository
  523. * @param issue
  524. * @param change
  525. * the change with the comment to change
  526. * @param author
  527. * the author of the revision
  528. * @param comment
  529. * the revised comment
  530. * @return true, if the change was successful
  531. */
  532. public static boolean changeComment(Repository repository, IssueModel issue, Change change,
  533. String author, String comment) {
  534. Change revision = new Change(author);
  535. revision.comment(comment);
  536. revision.comment.id = change.comment.id;
  537. return updateIssue(repository, issue.id, revision);
  538. }
  539. /**
  540. * Deletes a comment from an issue.
  541. *
  542. * @param repository
  543. * @param issue
  544. * @param change
  545. * the change with the comment to delete
  546. * @param author
  547. * @return true, if the deletion was successful
  548. */
  549. public static boolean deleteComment(Repository repository, IssueModel issue, Change change,
  550. String author) {
  551. Change deletion = new Change(author);
  552. deletion.comment(change.comment.text);
  553. deletion.comment.id = change.comment.id;
  554. deletion.comment.deleted = true;
  555. return updateIssue(repository, issue.id, deletion);
  556. }
  557. /**
  558. * Commit a change to the repository. Each issue is composed on changes.
  559. * Issues are built from applying the changes in the order they were
  560. * committed to the repository. The changes are actually specified in the
  561. * commit messages and not in the RevTrees which allows for clean,
  562. * distributed merging.
  563. *
  564. * @param repository
  565. * @param issueId
  566. * @param change
  567. * @return true, if the change was committed
  568. */
  569. private static boolean commit(Repository repository, String issueId, Change change) {
  570. boolean success = false;
  571. try {
  572. // assign ids to new attachments
  573. // attachments are stored by an SHA1 id
  574. if (change.hasAttachments()) {
  575. for (Attachment attachment : change.attachments) {
  576. if (!ArrayUtils.isEmpty(attachment.content)) {
  577. byte[] prefix = (change.created.toString() + change.author).getBytes();
  578. byte[] bytes = new byte[prefix.length + attachment.content.length];
  579. System.arraycopy(prefix, 0, bytes, 0, prefix.length);
  580. System.arraycopy(attachment.content, 0, bytes, prefix.length,
  581. attachment.content.length);
  582. attachment.id = "attachment-" + StringUtils.getSHA1(bytes);
  583. }
  584. }
  585. }
  586. // serialize the change as json
  587. // exclude any attachment from json serialization
  588. Gson gson = JsonUtils.gson(new ExcludeField(
  589. "com.gitblit.models.IssueModel$Attachment.content"));
  590. String json = gson.toJson(change);
  591. // include the json change in the commit message
  592. String issuePath = getIssuePath(issueId);
  593. String message = change.code + " " + issueId + "\n\n" + json;
  594. // Create a commit file. This is required for a proper commit and
  595. // ensures we can retrieve the commit log of the issue path.
  596. //
  597. // This file is NOT serialized as part of the Change object.
  598. switch (change.code) {
  599. case '+': {
  600. // New Issue.
  601. Attachment placeholder = new Attachment("issue");
  602. placeholder.id = placeholder.name;
  603. placeholder.content = "DO NOT REMOVE".getBytes(Constants.CHARACTER_ENCODING);
  604. change.addAttachment(placeholder);
  605. break;
  606. }
  607. default: {
  608. // Update Issue.
  609. String changeId = StringUtils.getSHA1(json);
  610. Attachment placeholder = new Attachment("change-" + changeId);
  611. placeholder.id = placeholder.name;
  612. placeholder.content = "REMOVABLE".getBytes(Constants.CHARACTER_ENCODING);
  613. change.addAttachment(placeholder);
  614. break;
  615. }
  616. }
  617. ObjectId headId = repository.resolve(GB_ISSUES + "^{commit}");
  618. ObjectInserter odi = repository.newObjectInserter();
  619. try {
  620. // Create the in-memory index of the new/updated issue
  621. DirCache index = createIndex(repository, headId, issuePath, change);
  622. ObjectId indexTreeId = index.writeTree(odi);
  623. // Create a commit object
  624. PersonIdent ident = new PersonIdent(change.author, "gitblit@localhost");
  625. CommitBuilder commit = new CommitBuilder();
  626. commit.setAuthor(ident);
  627. commit.setCommitter(ident);
  628. commit.setEncoding(Constants.CHARACTER_ENCODING);
  629. commit.setMessage(message);
  630. commit.setParentId(headId);
  631. commit.setTreeId(indexTreeId);
  632. // Insert the commit into the repository
  633. ObjectId commitId = odi.insert(commit);
  634. odi.flush();
  635. RevWalk revWalk = new RevWalk(repository);
  636. try {
  637. RevCommit revCommit = revWalk.parseCommit(commitId);
  638. RefUpdate ru = repository.updateRef(GB_ISSUES);
  639. ru.setNewObjectId(commitId);
  640. ru.setExpectedOldObjectId(headId);
  641. ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
  642. Result rc = ru.forceUpdate();
  643. switch (rc) {
  644. case NEW:
  645. case FORCED:
  646. case FAST_FORWARD:
  647. success = true;
  648. break;
  649. case REJECTED:
  650. case LOCK_FAILURE:
  651. throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD,
  652. ru.getRef(), rc);
  653. default:
  654. throw new JGitInternalException(MessageFormat.format(
  655. JGitText.get().updatingRefFailed, GB_ISSUES, commitId.toString(),
  656. rc));
  657. }
  658. } finally {
  659. revWalk.release();
  660. }
  661. } finally {
  662. odi.release();
  663. }
  664. } catch (Throwable t) {
  665. error(t, repository, "Failed to commit issue {1} to {0}", issueId);
  666. }
  667. return success;
  668. }
  669. /**
  670. * Returns the issue path. This follows the same scheme as Git's object
  671. * store path where the first two characters of the hash id are the root
  672. * folder with the remaining characters as a subfolder within that folder.
  673. *
  674. * @param issueId
  675. * @return the root path of the issue content on the gb-issues branch
  676. */
  677. static String getIssuePath(String issueId) {
  678. return issueId.substring(0, 2) + "/" + issueId.substring(2);
  679. }
  680. /**
  681. * Creates an in-memory index of the issue change.
  682. *
  683. * @param repo
  684. * @param headId
  685. * @param change
  686. * @return an in-memory index
  687. * @throws IOException
  688. */
  689. private static DirCache createIndex(Repository repo, ObjectId headId, String issuePath,
  690. Change change) throws IOException {
  691. DirCache inCoreIndex = DirCache.newInCore();
  692. DirCacheBuilder dcBuilder = inCoreIndex.builder();
  693. ObjectInserter inserter = repo.newObjectInserter();
  694. Set<String> ignorePaths = new TreeSet<String>();
  695. try {
  696. // Add any attachments to the temporary index
  697. if (change.hasAttachments()) {
  698. for (Attachment attachment : change.attachments) {
  699. // build a path name for the attachment and mark as ignored
  700. String path = issuePath + "/" + attachment.id;
  701. ignorePaths.add(path);
  702. // create an index entry for this attachment
  703. final DirCacheEntry dcEntry = new DirCacheEntry(path);
  704. dcEntry.setLength(attachment.content.length);
  705. dcEntry.setLastModified(change.created.getTime());
  706. dcEntry.setFileMode(FileMode.REGULAR_FILE);
  707. // insert object
  708. dcEntry.setObjectId(inserter.insert(Constants.OBJ_BLOB, attachment.content));
  709. // add to temporary in-core index
  710. dcBuilder.add(dcEntry);
  711. }
  712. }
  713. // Traverse HEAD to add all other paths
  714. TreeWalk treeWalk = new TreeWalk(repo);
  715. int hIdx = -1;
  716. if (headId != null)
  717. hIdx = treeWalk.addTree(new RevWalk(repo).parseTree(headId));
  718. treeWalk.setRecursive(true);
  719. while (treeWalk.next()) {
  720. String path = treeWalk.getPathString();
  721. CanonicalTreeParser hTree = null;
  722. if (hIdx != -1)
  723. hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
  724. if (!ignorePaths.contains(path)) {
  725. // add entries from HEAD for all other paths
  726. if (hTree != null) {
  727. // create a new DirCacheEntry with data retrieved from
  728. // HEAD
  729. final DirCacheEntry dcEntry = new DirCacheEntry(path);
  730. dcEntry.setObjectId(hTree.getEntryObjectId());
  731. dcEntry.setFileMode(hTree.getEntryFileMode());
  732. // add to temporary in-core index
  733. dcBuilder.add(dcEntry);
  734. }
  735. }
  736. }
  737. // release the treewalk
  738. treeWalk.release();
  739. // finish temporary in-core index used for this commit
  740. dcBuilder.finish();
  741. } finally {
  742. inserter.release();
  743. }
  744. return inCoreIndex;
  745. }
  746. }