您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JGitUtils.java 29KB

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