選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

JGitUtils.java 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  1. package com.gitblit.utils;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.nio.charset.Charset;
  7. import java.text.DateFormat;
  8. import java.text.ParseException;
  9. import java.text.SimpleDateFormat;
  10. import java.util.ArrayList;
  11. import java.util.Collection;
  12. import java.util.Collections;
  13. import java.util.Date;
  14. import java.util.HashMap;
  15. import java.util.List;
  16. import java.util.Map;
  17. import java.util.Set;
  18. import java.util.concurrent.atomic.AtomicInteger;
  19. import org.eclipse.jgit.api.Git;
  20. import org.eclipse.jgit.diff.DiffEntry;
  21. import org.eclipse.jgit.diff.DiffEntry.ChangeType;
  22. import org.eclipse.jgit.diff.DiffFormatter;
  23. import org.eclipse.jgit.diff.RawTextComparator;
  24. import org.eclipse.jgit.errors.ConfigInvalidException;
  25. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  26. import org.eclipse.jgit.errors.MissingObjectException;
  27. import org.eclipse.jgit.errors.StopWalkException;
  28. import org.eclipse.jgit.lib.AnyObjectId;
  29. import org.eclipse.jgit.lib.Constants;
  30. import org.eclipse.jgit.lib.FileMode;
  31. import org.eclipse.jgit.lib.ObjectId;
  32. import org.eclipse.jgit.lib.ObjectLoader;
  33. import org.eclipse.jgit.lib.PersonIdent;
  34. import org.eclipse.jgit.lib.Ref;
  35. import org.eclipse.jgit.lib.Repository;
  36. import org.eclipse.jgit.lib.StoredConfig;
  37. import org.eclipse.jgit.revwalk.RevBlob;
  38. import org.eclipse.jgit.revwalk.RevCommit;
  39. import org.eclipse.jgit.revwalk.RevObject;
  40. import org.eclipse.jgit.revwalk.RevSort;
  41. import org.eclipse.jgit.revwalk.RevTree;
  42. import org.eclipse.jgit.revwalk.RevWalk;
  43. import org.eclipse.jgit.revwalk.filter.RevFilter;
  44. import org.eclipse.jgit.treewalk.TreeWalk;
  45. import org.eclipse.jgit.treewalk.filter.AndTreeFilter;
  46. import org.eclipse.jgit.treewalk.filter.OrTreeFilter;
  47. import org.eclipse.jgit.treewalk.filter.PathFilter;
  48. import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
  49. import org.eclipse.jgit.treewalk.filter.PathSuffixFilter;
  50. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  51. import org.eclipse.jgit.util.io.DisabledOutputStream;
  52. import org.slf4j.Logger;
  53. import org.slf4j.LoggerFactory;
  54. import com.gitblit.wicket.models.Metric;
  55. import com.gitblit.wicket.models.PathModel;
  56. import com.gitblit.wicket.models.PathModel.PathChangeModel;
  57. import com.gitblit.wicket.models.RefModel;
  58. import com.gitblit.wicket.models.TicketModel;
  59. import com.gitblit.wicket.models.TicketModel.Comment;
  60. public class JGitUtils {
  61. /** Prefix for notes refs */
  62. public static final String R_NOTES = "refs/notes/";
  63. /** Standard notes ref */
  64. public static final String R_NOTES_COMMITS = R_NOTES + "commits";
  65. private final static Logger LOGGER = LoggerFactory.getLogger(JGitUtils.class);
  66. public static Repository createRepository(File repositoriesFolder, String name, boolean bare) {
  67. Git git = Git.init().setDirectory(new File(repositoriesFolder, name)).setBare(bare).call();
  68. return git.getRepository();
  69. }
  70. public static List<String> getRepositoryList(File repositoriesFolder, boolean exportAll, boolean readNested) {
  71. List<String> list = new ArrayList<String>();
  72. list.addAll(getNestedRepositories(repositoriesFolder, repositoriesFolder, exportAll, readNested));
  73. Collections.sort(list);
  74. return list;
  75. }
  76. public static List<String> getNestedRepositories(File repositoriesFolder, File folder, boolean exportAll, boolean readNested) {
  77. String basefile = repositoriesFolder.getAbsolutePath();
  78. List<String> list = new ArrayList<String>();
  79. for (File file : folder.listFiles()) {
  80. if (file.isDirectory() && !file.getName().equalsIgnoreCase(Constants.DOT_GIT)) {
  81. // if this is a git repository add it to the list
  82. //
  83. // first look for standard folder/.git structure
  84. File gitFolder = new File(file, Constants.DOT_GIT);
  85. boolean isGitRepository = gitFolder.exists() && gitFolder.isDirectory();
  86. // then look for folder.git/HEAD or folder/HEAD and folder/config
  87. if (!isGitRepository) {
  88. if ((file.getName().endsWith(Constants.DOT_GIT_EXT) && new File(file, Constants.HEAD).exists())
  89. || (new File(file, "config").exists() && new File(file, Constants.HEAD).exists())) {
  90. gitFolder = file;
  91. isGitRepository = true;
  92. }
  93. }
  94. boolean exportRepository = isGitRepository && (exportAll || new File(gitFolder, "git-daemon-export-ok").exists());
  95. if (exportRepository) {
  96. // determine repository name relative to repositories folder
  97. String filename = file.getAbsolutePath();
  98. String repo = filename.substring(basefile.length()).replace('\\', '/');
  99. if (repo.charAt(0) == '/') {
  100. repo = repo.substring(1);
  101. }
  102. list.add(repo);
  103. }
  104. // look for nested repositories
  105. if (readNested) {
  106. list.addAll(getNestedRepositories(repositoriesFolder, file, exportAll, readNested));
  107. }
  108. }
  109. }
  110. return list;
  111. }
  112. public static RevCommit getFirstCommit(Repository r, String branch) {
  113. if (StringUtils.isEmpty(branch)) {
  114. branch = Constants.HEAD;
  115. }
  116. try {
  117. RevWalk walk = new RevWalk(r);
  118. walk.sort(RevSort.REVERSE);
  119. RevCommit head = walk.parseCommit(r.resolve(branch));
  120. walk.markStart(head);
  121. RevCommit commit = walk.next();
  122. walk.dispose();
  123. return commit;
  124. } catch (Throwable t) {
  125. LOGGER.error("Failed to determine first commit", t);
  126. }
  127. return null;
  128. }
  129. public static Date getFirstChange(Repository r, String branch) {
  130. try {
  131. RevCommit commit = getFirstCommit(r, branch);
  132. if (commit == null) {
  133. // fresh repository
  134. return new Date(r.getDirectory().lastModified());
  135. }
  136. return getCommitDate(commit);
  137. } catch (Throwable t) {
  138. LOGGER.error("Failed to determine first change", t);
  139. }
  140. return null;
  141. }
  142. public static Date getLastChange(Repository r) {
  143. RevCommit commit = getCommit(r, Constants.HEAD);
  144. if (commit == null) {
  145. // fresh repository
  146. return new Date(r.getDirectory().lastModified());
  147. }
  148. return getCommitDate(commit);
  149. }
  150. public static RevCommit getCommit(Repository r, String objectId) {
  151. RevCommit commit = null;
  152. try {
  153. if (objectId == null || objectId.trim().length() == 0) {
  154. objectId = Constants.HEAD;
  155. }
  156. ObjectId object = r.resolve(objectId);
  157. RevWalk walk = new RevWalk(r);
  158. RevCommit rev = walk.parseCommit(object);
  159. commit = rev;
  160. walk.dispose();
  161. } catch (Throwable t) {
  162. LOGGER.error("Failed to determine last change", t);
  163. }
  164. return commit;
  165. }
  166. public static Map<ObjectId, List<String>> getAllRefs(Repository r) {
  167. Map<ObjectId, List<String>> refs = new HashMap<ObjectId, List<String>>();
  168. Map<AnyObjectId, Set<Ref>> allRefs = r.getAllRefsByPeeledObjectId();
  169. for (AnyObjectId id : allRefs.keySet()) {
  170. List<String> list = new ArrayList<String>();
  171. for (Ref setRef : allRefs.get(id)) {
  172. String name = setRef.getName();
  173. list.add(name);
  174. }
  175. refs.put(id.toObjectId(), list);
  176. }
  177. return refs;
  178. }
  179. public static Map<ObjectId, List<String>> getRefs(Repository r, String baseRef) {
  180. Map<ObjectId, List<String>> refs = new HashMap<ObjectId, List<String>>();
  181. Map<AnyObjectId, Set<Ref>> allRefs = r.getAllRefsByPeeledObjectId();
  182. for (AnyObjectId id : allRefs.keySet()) {
  183. List<String> list = new ArrayList<String>();
  184. for (Ref setRef : allRefs.get(id)) {
  185. String name = setRef.getName();
  186. if (name.startsWith(baseRef)) {
  187. list.add(name);
  188. }
  189. }
  190. refs.put(id.toObjectId(), list);
  191. }
  192. return refs;
  193. }
  194. /**
  195. * Lookup an entry stored in a tree, failing if not present.
  196. *
  197. * @param tree
  198. * the tree to search.
  199. * @param path
  200. * the path to find the entry of.
  201. * @return the parsed object entry at this path
  202. * @throws Exception
  203. */
  204. public static RevObject getRevObject(Repository r, final RevTree tree, final String path) {
  205. RevObject ro = null;
  206. RevWalk rw = new RevWalk(r);
  207. TreeWalk tw = new TreeWalk(r);
  208. tw.setFilter(PathFilterGroup.createFromStrings(Collections.singleton(path)));
  209. try {
  210. tw.reset(tree);
  211. while (tw.next()) {
  212. if (tw.isSubtree() && !path.equals(tw.getPathString())) {
  213. tw.enterSubtree();
  214. continue;
  215. }
  216. ObjectId entid = tw.getObjectId(0);
  217. FileMode entmode = tw.getFileMode(0);
  218. ro = rw.lookupAny(entid, entmode.getObjectType());
  219. rw.parseBody(ro);
  220. }
  221. } catch (Throwable t) {
  222. LOGGER.error("Can't find " + path + " in tree " + tree.name(), t);
  223. } finally {
  224. if (rw != null) {
  225. rw.dispose();
  226. }
  227. }
  228. return ro;
  229. }
  230. public static byte[] getRawContent(Repository r, RevBlob blob) {
  231. ByteArrayOutputStream os = new ByteArrayOutputStream();
  232. try {
  233. ObjectLoader ldr = r.open(blob.getId(), Constants.OBJ_BLOB);
  234. byte[] tmp = new byte[1024];
  235. InputStream in = ldr.openStream();
  236. int n;
  237. while ((n = in.read(tmp)) > 0) {
  238. os.write(tmp, 0, n);
  239. }
  240. in.close();
  241. } catch (Throwable t) {
  242. LOGGER.error("Failed to read raw content", t);
  243. }
  244. return os.toByteArray();
  245. }
  246. public static String getRawContentAsString(Repository r, RevBlob blob) {
  247. byte [] content = getRawContent(r, blob);
  248. return new String(content, Charset.forName(Constants.CHARACTER_ENCODING));
  249. }
  250. public static String getRawContentAsString(Repository r, RevCommit commit, String blobPath) {
  251. RevObject obj = getRevObject(r, commit.getTree(), blobPath);
  252. byte [] content = getRawContent(r, (RevBlob) obj);
  253. return new String(content, Charset.forName(Constants.CHARACTER_ENCODING));
  254. }
  255. public static List<PathModel> getFilesInPath(Repository r, String basePath, String objectId) {
  256. RevCommit commit = getCommit(r, objectId);
  257. return getFilesInPath(r, basePath, commit);
  258. }
  259. public static List<PathModel> getFilesInPath(Repository r, String basePath, RevCommit commit) {
  260. List<PathModel> list = new ArrayList<PathModel>();
  261. if (commit == null) {
  262. return list;
  263. }
  264. final TreeWalk walk = new TreeWalk(r);
  265. try {
  266. walk.addTree(commit.getTree());
  267. if (basePath != null && basePath.length() > 0) {
  268. PathFilter f = PathFilter.create(basePath);
  269. walk.setFilter(f);
  270. walk.setRecursive(false);
  271. boolean foundFolder = false;
  272. while (walk.next()) {
  273. if (!foundFolder && walk.isSubtree()) {
  274. walk.enterSubtree();
  275. }
  276. if (walk.getPathString().equals(basePath)) {
  277. foundFolder = true;
  278. continue;
  279. }
  280. if (foundFolder) {
  281. list.add(getPathModel(walk, basePath, commit));
  282. }
  283. }
  284. } else {
  285. walk.setRecursive(false);
  286. while (walk.next()) {
  287. list.add(getPathModel(walk, null, commit));
  288. }
  289. }
  290. } catch (IOException e) {
  291. LOGGER.error("Failed to get files for commit " + commit.getName(), e);
  292. } finally {
  293. walk.release();
  294. }
  295. Collections.sort(list);
  296. return list;
  297. }
  298. public static List<PathChangeModel> getFilesInCommit(Repository r, String commitId) {
  299. RevCommit commit = getCommit(r, commitId);
  300. return getFilesInCommit(r, commit);
  301. }
  302. public static List<PathChangeModel> getFilesInCommit(Repository r, RevCommit commit) {
  303. List<PathChangeModel> list = new ArrayList<PathChangeModel>();
  304. try {
  305. final RevWalk rw = new RevWalk(r);
  306. RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
  307. RevTree parentTree = parent.getTree();
  308. RevTree commitTree = commit.getTree();
  309. final TreeWalk walk = new TreeWalk(r);
  310. walk.reset();
  311. walk.setRecursive(true);
  312. walk.addTree(parentTree);
  313. walk.addTree(commitTree);
  314. walk.setFilter(TreeFilter.ANY_DIFF);
  315. RawTextComparator cmp = RawTextComparator.DEFAULT;
  316. DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
  317. df.setRepository(r);
  318. df.setDiffComparator(cmp);
  319. df.setDetectRenames(true);
  320. List<DiffEntry> diffs = df.scan(parentTree, commitTree);
  321. for (DiffEntry diff : diffs) {
  322. if (diff.getChangeType().equals(ChangeType.DELETE)) {
  323. list.add(new PathChangeModel(diff.getOldPath(), diff.getOldPath(), 0, diff.getNewMode().getBits(), commit.getId().getName(), diff.getChangeType()));
  324. } else {
  325. list.add(new PathChangeModel(diff.getNewPath(), diff.getNewPath(), 0, diff.getNewMode().getBits(), commit.getId().getName(), diff.getChangeType()));
  326. }
  327. }
  328. } catch (Throwable t) {
  329. LOGGER.error("failed to determine files in commit!", t);
  330. }
  331. return list;
  332. }
  333. public static List<PathModel> getDocuments(Repository r, List<String> extensions) {
  334. List<PathModel> list = new ArrayList<PathModel>();
  335. RevCommit commit = getCommit(r, Constants.HEAD);
  336. final TreeWalk walk = new TreeWalk(r);
  337. try {
  338. walk.addTree(commit.getTree());
  339. if (extensions != null && extensions.size() > 0) {
  340. Collection<TreeFilter> suffixFilters = new ArrayList<TreeFilter>();
  341. for (String extension:extensions) {
  342. if (extension.charAt(0) == '.') {
  343. suffixFilters.add(PathSuffixFilter.create(extension));
  344. } else {
  345. // escape the . since this is a regexp filter
  346. suffixFilters.add(PathSuffixFilter.create("\\." + extension));
  347. }
  348. }
  349. TreeFilter filter = OrTreeFilter.create(suffixFilters);
  350. walk.setFilter(filter);
  351. walk.setRecursive(true);
  352. while (walk.next()) {
  353. list.add(getPathModel(walk, null, commit));
  354. }
  355. } else {
  356. while (walk.next()) {
  357. list.add(getPathModel(walk, null, commit));
  358. }
  359. }
  360. } catch (IOException e) {
  361. LOGGER.error("Failed to get files for commit " + commit.getName(), e);
  362. } finally {
  363. walk.release();
  364. }
  365. Collections.sort(list);
  366. return list;
  367. }
  368. public static Map<ChangeType, AtomicInteger> getChangedPathsStats(List<PathChangeModel> paths) {
  369. Map<ChangeType, AtomicInteger> stats = new HashMap<ChangeType, AtomicInteger>();
  370. for (PathChangeModel path : paths) {
  371. if (!stats.containsKey(path.changeType)) {
  372. stats.put(path.changeType, new AtomicInteger(0));
  373. }
  374. stats.get(path.changeType).incrementAndGet();
  375. }
  376. return stats;
  377. }
  378. public static enum DiffOutputType {
  379. PLAIN, GITWEB, GITBLIT;
  380. public static DiffOutputType forName(String name) {
  381. for (DiffOutputType type : values()) {
  382. if (type.name().equalsIgnoreCase(name)) {
  383. return type;
  384. }
  385. }
  386. return null;
  387. }
  388. }
  389. public static String getCommitDiff(Repository r, RevCommit commit, DiffOutputType outputType) {
  390. return getCommitDiff(r, null, commit, null, outputType);
  391. }
  392. public static String getCommitDiff(Repository r, RevCommit commit, String path, DiffOutputType outputType) {
  393. return getCommitDiff(r, null, commit, path, outputType);
  394. }
  395. public static String getCommitDiff(Repository r, RevCommit baseCommit, RevCommit commit, DiffOutputType outputType) {
  396. return getCommitDiff(r, baseCommit, commit, null, outputType);
  397. }
  398. public static String getCommitDiff(Repository r, RevCommit baseCommit, RevCommit commit, String path, DiffOutputType outputType) {
  399. try {
  400. RevTree baseTree;
  401. if (baseCommit == null) {
  402. final RevWalk rw = new RevWalk(r);
  403. RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
  404. rw.dispose();
  405. baseTree = parent.getTree();
  406. } else {
  407. baseTree = baseCommit.getTree();
  408. }
  409. RevTree commitTree = commit.getTree();
  410. final TreeWalk walk = new TreeWalk(r);
  411. walk.reset();
  412. walk.setRecursive(true);
  413. walk.addTree(baseTree);
  414. walk.addTree(commitTree);
  415. walk.setFilter(TreeFilter.ANY_DIFF);
  416. final ByteArrayOutputStream os = new ByteArrayOutputStream();
  417. RawTextComparator cmp = RawTextComparator.DEFAULT;
  418. DiffFormatter df;
  419. switch (outputType) {
  420. case GITWEB:
  421. df = new GitWebDiffFormatter(os);
  422. break;
  423. case GITBLIT:
  424. df = new GitBlitDiffFormatter(os);
  425. break;
  426. case PLAIN:
  427. default:
  428. df = new DiffFormatter(os);
  429. break;
  430. }
  431. df.setRepository(r);
  432. df.setDiffComparator(cmp);
  433. df.setDetectRenames(true);
  434. List<DiffEntry> diffs = df.scan(baseTree, commitTree);
  435. if (path != null && path.length() > 0) {
  436. for (DiffEntry diff : diffs) {
  437. if (diff.getNewPath().equalsIgnoreCase(path)) {
  438. df.format(diff);
  439. break;
  440. }
  441. }
  442. } else {
  443. df.format(diffs);
  444. }
  445. String diff;
  446. if (df instanceof GitWebDiffFormatter) {
  447. // workaround for complex private methods in DiffFormatter
  448. diff = ((GitWebDiffFormatter) df).getHtml();
  449. } else {
  450. diff = os.toString();
  451. }
  452. df.flush();
  453. return diff;
  454. } catch (Throwable t) {
  455. LOGGER.error("failed to generate commit diff!", t);
  456. }
  457. return null;
  458. }
  459. public static String getCommitPatch(Repository r, RevCommit commit) {
  460. return getCommitPatch(r, commit);
  461. }
  462. public static String getCommitPatch(Repository r, RevCommit commit, String path) {
  463. return getCommitPatch(r, null, commit, path);
  464. }
  465. public static String getCommitPatch(Repository r, RevCommit baseCommit, RevCommit commit, String path) {
  466. try {
  467. RevTree baseTree;
  468. if (baseCommit == null) {
  469. final RevWalk rw = new RevWalk(r);
  470. RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
  471. baseTree = parent.getTree();
  472. } else {
  473. baseTree = baseCommit.getTree();
  474. }
  475. RevTree commitTree = commit.getTree();
  476. final TreeWalk walk = new TreeWalk(r);
  477. walk.reset();
  478. walk.setRecursive(true);
  479. walk.addTree(baseTree);
  480. walk.addTree(commitTree);
  481. walk.setFilter(TreeFilter.ANY_DIFF);
  482. final ByteArrayOutputStream os = new ByteArrayOutputStream();
  483. RawTextComparator cmp = RawTextComparator.DEFAULT;
  484. PatchFormatter df = new PatchFormatter(os);
  485. df.setRepository(r);
  486. df.setDiffComparator(cmp);
  487. df.setDetectRenames(true);
  488. List<DiffEntry> diffs = df.scan(baseTree, commitTree);
  489. if (path != null && path.length() > 0) {
  490. for (DiffEntry diff : diffs) {
  491. if (diff.getNewPath().equalsIgnoreCase(path)) {
  492. df.format(diff);
  493. break;
  494. }
  495. }
  496. } else {
  497. df.format(diffs);
  498. }
  499. String diff = df.getPatch(commit);
  500. df.flush();
  501. return diff;
  502. } catch (Throwable t) {
  503. LOGGER.error("failed to generate commit diff!", t);
  504. }
  505. return null;
  506. }
  507. private static PathModel getPathModel(TreeWalk walk, String basePath, RevCommit commit) {
  508. String name;
  509. long size = 0;
  510. if (basePath == null) {
  511. name = walk.getPathString();
  512. } else {
  513. try {
  514. name = walk.getPathString().substring(basePath.length() + 1);
  515. } catch (Throwable t) {
  516. name = walk.getPathString();
  517. }
  518. }
  519. try {
  520. if (!walk.isSubtree()) {
  521. size = walk.getObjectReader().getObjectSize(walk.getObjectId(0), Constants.OBJ_BLOB);
  522. }
  523. } catch (Throwable t) {
  524. LOGGER.error("Failed to retrieve blob size", t);
  525. }
  526. return new PathModel(name, walk.getPathString(), size, walk.getFileMode(0).getBits(), commit.getName());
  527. }
  528. public static String getPermissionsFromMode(int mode) {
  529. if (FileMode.TREE.equals(mode)) {
  530. return "drwxr-xr-x";
  531. } else if (FileMode.REGULAR_FILE.equals(mode)) {
  532. return "-rw-r--r--";
  533. } else if (FileMode.EXECUTABLE_FILE.equals(mode)) {
  534. return "-rwxr-xr-x";
  535. } else if (FileMode.SYMLINK.equals(mode)) {
  536. // FIXME symlink permissions
  537. return "symlink";
  538. } else if (FileMode.GITLINK.equals(mode)) {
  539. // FIXME gitlink permissions
  540. return "gitlink";
  541. } else if (FileMode.MISSING.equals(mode)) {
  542. // FIXME missing permissions
  543. return "missing";
  544. }
  545. return "" + mode;
  546. }
  547. public static boolean isTreeFromMode(int mode) {
  548. return FileMode.TREE.equals(mode);
  549. }
  550. public static List<RevCommit> getRevLog(Repository r, int maxCount) {
  551. return getRevLog(r, Constants.HEAD, 0, maxCount);
  552. }
  553. public static List<RevCommit> getRevLog(Repository r, String objectId, int offset, int maxCount) {
  554. return getRevLog(r, objectId, null, offset, maxCount);
  555. }
  556. public static List<RevCommit> getRevLog(Repository r, String objectId, String path, int offset, int maxCount) {
  557. List<RevCommit> list = new ArrayList<RevCommit>();
  558. try {
  559. if (objectId == null || objectId.trim().length() == 0) {
  560. objectId = Constants.HEAD;
  561. }
  562. RevWalk walk = new RevWalk(r);
  563. ObjectId object = r.resolve(objectId);
  564. walk.markStart(walk.parseCommit(object));
  565. if (!StringUtils.isEmpty(path)) {
  566. TreeFilter filter = AndTreeFilter.create(PathFilterGroup.createFromStrings(Collections.singleton(path)), TreeFilter.ANY_DIFF);
  567. walk.setTreeFilter(filter);
  568. }
  569. Iterable<RevCommit> revlog = walk;
  570. if (offset > 0) {
  571. int count = 0;
  572. for (RevCommit rev : revlog) {
  573. count++;
  574. if (count > offset) {
  575. list.add(rev);
  576. if (maxCount > 0 && list.size() == maxCount) {
  577. break;
  578. }
  579. }
  580. }
  581. } else {
  582. for (RevCommit rev : revlog) {
  583. list.add(rev);
  584. if (maxCount > 0 && list.size() == maxCount) {
  585. break;
  586. }
  587. }
  588. }
  589. walk.dispose();
  590. } catch (Throwable t) {
  591. LOGGER.error("Failed to determine last change", t);
  592. }
  593. return list;
  594. }
  595. public static enum SearchType {
  596. AUTHOR, COMMITTER, COMMIT;
  597. public static SearchType forName(String name) {
  598. for (SearchType type : values()) {
  599. if (type.name().equalsIgnoreCase(name)) {
  600. return type;
  601. }
  602. }
  603. return null;
  604. }
  605. public String toString() {
  606. return name().toLowerCase();
  607. }
  608. }
  609. public static List<RevCommit> searchRevlogs(Repository r, String objectId, String value, final SearchType type, int offset, int maxCount) {
  610. final String lcValue = value.toLowerCase();
  611. List<RevCommit> list = new ArrayList<RevCommit>();
  612. try {
  613. if (objectId == null || objectId.trim().length() == 0) {
  614. objectId = Constants.HEAD;
  615. }
  616. RevWalk walk = new RevWalk(r);
  617. walk.setRevFilter(new RevFilter() {
  618. @Override
  619. public RevFilter clone() {
  620. return this;
  621. }
  622. @Override
  623. public boolean include(RevWalk walker, RevCommit commit) throws StopWalkException, MissingObjectException, IncorrectObjectTypeException, IOException {
  624. switch (type) {
  625. case AUTHOR:
  626. return (commit.getAuthorIdent().getName().toLowerCase().indexOf(lcValue) > -1) || (commit.getAuthorIdent().getEmailAddress().toLowerCase().indexOf(lcValue) > -1);
  627. case COMMITTER:
  628. return (commit.getCommitterIdent().getName().toLowerCase().indexOf(lcValue) > -1) || (commit.getCommitterIdent().getEmailAddress().toLowerCase().indexOf(lcValue) > -1);
  629. case COMMIT:
  630. return commit.getFullMessage().toLowerCase().indexOf(lcValue) > -1;
  631. }
  632. return false;
  633. }
  634. });
  635. ObjectId object = r.resolve(objectId);
  636. walk.markStart(walk.parseCommit(object));
  637. Iterable<RevCommit> revlog = walk;
  638. if (offset > 0) {
  639. int count = 0;
  640. for (RevCommit rev : revlog) {
  641. count++;
  642. if (count > offset) {
  643. list.add(rev);
  644. if (maxCount > 0 && list.size() == maxCount) {
  645. break;
  646. }
  647. }
  648. }
  649. } else {
  650. for (RevCommit rev : revlog) {
  651. list.add(rev);
  652. if (maxCount > 0 && list.size() == maxCount) {
  653. break;
  654. }
  655. }
  656. }
  657. walk.dispose();
  658. } catch (Throwable t) {
  659. LOGGER.error("Failed to determine last change", t);
  660. }
  661. return list;
  662. }
  663. public static List<RefModel> getTags(Repository r, int maxCount) {
  664. return getRefs(r, Constants.R_TAGS, maxCount);
  665. }
  666. public static List<RefModel> getLocalBranches(Repository r, int maxCount) {
  667. return getRefs(r, Constants.R_HEADS, maxCount);
  668. }
  669. public static List<RefModel> getRemoteBranches(Repository r, int maxCount) {
  670. return getRefs(r, Constants.R_REMOTES, maxCount);
  671. }
  672. public static List<RefModel> getRefs(Repository r, String refs, int maxCount) {
  673. List<RefModel> list = new ArrayList<RefModel>();
  674. try {
  675. Map<String, Ref> map = r.getRefDatabase().getRefs(refs);
  676. for (String name : map.keySet()) {
  677. Ref ref = map.get(name);
  678. RevCommit commit = getCommit(r, ref.getObjectId().getName());
  679. list.add(new RefModel(name, ref, commit));
  680. }
  681. Collections.sort(list);
  682. Collections.reverse(list);
  683. if (maxCount > 0 && list.size() > maxCount) {
  684. list = new ArrayList<RefModel>(list.subList(0, maxCount));
  685. }
  686. } catch (IOException e) {
  687. LOGGER.error("Failed to retrieve " + refs, e);
  688. }
  689. return list;
  690. }
  691. public static Ref getRef(Repository r, String id) {
  692. try {
  693. Map<String, Ref> map = r.getRefDatabase().getRefs(id);
  694. for (String name : map.keySet()) {
  695. return map.get(name);
  696. }
  697. } catch (IOException e) {
  698. LOGGER.error("Failed to retrieve ref " + id, e);
  699. }
  700. return null;
  701. }
  702. public static Date getCommitDate(RevCommit commit) {
  703. return new Date(commit.getCommitTime() * 1000l);
  704. }
  705. public static String getDisplayName(PersonIdent person) {
  706. final StringBuilder r = new StringBuilder();
  707. r.append(person.getName());
  708. r.append(" <");
  709. r.append(person.getEmailAddress());
  710. r.append(">");
  711. return r.toString();
  712. }
  713. public static StoredConfig readConfig(Repository r) {
  714. StoredConfig c = r.getConfig();
  715. if (c != null) {
  716. try {
  717. c.load();
  718. } catch (ConfigInvalidException cex) {
  719. LOGGER.error("Repository configuration is invalid!", cex);
  720. } catch (IOException cex) {
  721. LOGGER.error("Could not open repository configuration!", cex);
  722. }
  723. return c;
  724. }
  725. return null;
  726. }
  727. public static List<Metric> getDateMetrics(Repository r) {
  728. final List<RefModel> tags = getTags(r, -1);
  729. final Map<ObjectId, RefModel> tagMap = new HashMap<ObjectId, RefModel>();
  730. for (RefModel tag : tags) {
  731. tagMap.put(tag.getCommitId(), tag);
  732. }
  733. Metric total = new Metric("TOTAL");
  734. final Map<String, Metric> metricMap = new HashMap<String, Metric>();
  735. try {
  736. RevWalk walk = new RevWalk(r);
  737. ObjectId object = r.resolve(Constants.HEAD);
  738. RevCommit firstCommit = getFirstCommit(r, Constants.HEAD);
  739. RevCommit lastCommit = walk.parseCommit(object);
  740. int diffDays = (lastCommit.getCommitTime() - firstCommit.getCommitTime()) / (60 * 60 * 24);
  741. total.duration = diffDays;
  742. DateFormat df;
  743. if (diffDays <= 90) {
  744. // Days
  745. df = new SimpleDateFormat("yyyy-MM-dd");
  746. } else if (diffDays > 90 && diffDays < 365) {
  747. // Weeks
  748. df = new SimpleDateFormat("yyyy-MM (w)");
  749. } else {
  750. // Months
  751. df = new SimpleDateFormat("yyyy-MM");
  752. }
  753. walk.markStart(lastCommit);
  754. Iterable<RevCommit> revlog = walk;
  755. for (RevCommit rev : revlog) {
  756. Date d = getCommitDate(rev);
  757. String p = df.format(d);
  758. if (!metricMap.containsKey(p))
  759. metricMap.put(p, new Metric(p));
  760. Metric m = metricMap.get(p);
  761. m.count++;
  762. total.count++;
  763. if (tagMap.containsKey(rev.getId())) {
  764. m.tag++;
  765. total.tag++;
  766. }
  767. }
  768. } catch (Throwable t) {
  769. LOGGER.error("Failed to mine log history for metrics", t);
  770. }
  771. List<String> keys = new ArrayList<String>(metricMap.keySet());
  772. Collections.sort(keys);
  773. List<Metric> metrics = new ArrayList<Metric>();
  774. for (String key : keys) {
  775. metrics.add(metricMap.get(key));
  776. }
  777. metrics.add(0, total);
  778. return metrics;
  779. }
  780. public static RefModel getTicketsBranch(Repository r) {
  781. RefModel ticgitBranch = null;
  782. try {
  783. // search for ticgit branch in local heads
  784. for (RefModel ref : getLocalBranches(r, -1)) {
  785. if (ref.getDisplayName().endsWith("ticgit")) {
  786. ticgitBranch = ref;
  787. break;
  788. }
  789. }
  790. // search for ticgit branch in remote heads
  791. if (ticgitBranch == null) {
  792. for (RefModel ref : getRemoteBranches(r, -1)) {
  793. if (ref.getDisplayName().endsWith("ticgit")) {
  794. ticgitBranch = ref;
  795. break;
  796. }
  797. }
  798. }
  799. } catch (Throwable t) {
  800. LOGGER.error("Failed to find ticgit branch!", t);
  801. }
  802. return ticgitBranch;
  803. }
  804. public static List<TicketModel> getTickets(Repository r) {
  805. RefModel ticgitBranch = getTicketsBranch(r);
  806. List<PathModel> paths = getFilesInPath(r, null, ticgitBranch.getCommit());
  807. List<TicketModel> tickets = new ArrayList<TicketModel>();
  808. for (PathModel ticketFolder : paths) {
  809. if (ticketFolder.isTree()) {
  810. try {
  811. TicketModel t = new TicketModel(ticketFolder.name);
  812. readTicketContents(r, ticgitBranch, t);
  813. tickets.add(t);
  814. } catch (Throwable t) {
  815. LOGGER.error("Failed to get a ticket!", t);
  816. }
  817. }
  818. }
  819. Collections.sort(tickets);
  820. Collections.reverse(tickets);
  821. return tickets;
  822. }
  823. public static TicketModel getTicket(Repository r, String ticketFolder) {
  824. RefModel ticketsBranch = getTicketsBranch(r);
  825. if (ticketsBranch != null) {
  826. try {
  827. TicketModel ticket = new TicketModel(ticketFolder);
  828. readTicketContents(r, ticketsBranch, ticket);
  829. return ticket;
  830. } catch (Throwable t) {
  831. LOGGER.error("Failed to get ticket " + ticketFolder, t);
  832. }
  833. }
  834. return null;
  835. }
  836. private static void readTicketContents(Repository r, RefModel ticketsBranch, TicketModel ticket) {
  837. List<PathModel> ticketFiles = getFilesInPath(r, ticket.name, ticketsBranch.getCommit());
  838. for (PathModel file : ticketFiles) {
  839. String content = getRawContentAsString(r, ticketsBranch.getCommit(), file.path).trim();
  840. if (file.name.equals("TICKET_ID")) {
  841. ticket.id = content;
  842. } else if (file.name.equals("TITLE")) {
  843. ticket.title = content;
  844. } else {
  845. String[] chunks = file.name.split("_");
  846. if (chunks[0].equals("ASSIGNED")) {
  847. ticket.handler = content;
  848. } else if (chunks[0].equals("COMMENT")) {
  849. try {
  850. Comment c = new Comment(file.name, content);
  851. ticket.comments.add(c);
  852. } catch (ParseException e) {
  853. e.printStackTrace();
  854. }
  855. } else if (chunks[0].equals("TAG")) {
  856. if (content.startsWith("TAG_")) {
  857. ticket.tags.add(content.substring(4));
  858. } else {
  859. ticket.tags.add(content);
  860. }
  861. } else if (chunks[0].equals("STATE")) {
  862. ticket.state = content;
  863. }
  864. }
  865. }
  866. Collections.sort(ticket.comments);
  867. }
  868. public static String getTicketContent(Repository r, String filePath) {
  869. RefModel ticketsBranch = getTicketsBranch(r);
  870. if (ticketsBranch != null) {
  871. return getRawContentAsString(r, ticketsBranch.getCommit(), filePath);
  872. }
  873. return "";
  874. }
  875. }