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.

JGitUtils.java 61KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917
  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.text.DecimalFormat;
  22. import java.text.MessageFormat;
  23. import java.util.ArrayList;
  24. import java.util.Arrays;
  25. import java.util.Collections;
  26. import java.util.Date;
  27. import java.util.HashMap;
  28. import java.util.Iterator;
  29. import java.util.List;
  30. import java.util.Map;
  31. import java.util.Map.Entry;
  32. import java.util.regex.Pattern;
  33. import org.eclipse.jgit.api.CloneCommand;
  34. import org.eclipse.jgit.api.FetchCommand;
  35. import org.eclipse.jgit.api.Git;
  36. import org.eclipse.jgit.api.TagCommand;
  37. import org.eclipse.jgit.api.errors.GitAPIException;
  38. import org.eclipse.jgit.diff.DiffEntry;
  39. import org.eclipse.jgit.diff.DiffEntry.ChangeType;
  40. import org.eclipse.jgit.diff.DiffFormatter;
  41. import org.eclipse.jgit.diff.RawTextComparator;
  42. import org.eclipse.jgit.errors.ConfigInvalidException;
  43. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  44. import org.eclipse.jgit.errors.MissingObjectException;
  45. import org.eclipse.jgit.errors.StopWalkException;
  46. import org.eclipse.jgit.lib.BlobBasedConfig;
  47. import org.eclipse.jgit.lib.CommitBuilder;
  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.ObjectInserter;
  52. import org.eclipse.jgit.lib.ObjectLoader;
  53. import org.eclipse.jgit.lib.PersonIdent;
  54. import org.eclipse.jgit.lib.Ref;
  55. import org.eclipse.jgit.lib.RefUpdate;
  56. import org.eclipse.jgit.lib.RefUpdate.Result;
  57. import org.eclipse.jgit.lib.Repository;
  58. import org.eclipse.jgit.lib.RepositoryCache.FileKey;
  59. import org.eclipse.jgit.lib.TreeFormatter;
  60. import org.eclipse.jgit.revwalk.RevBlob;
  61. import org.eclipse.jgit.revwalk.RevCommit;
  62. import org.eclipse.jgit.revwalk.RevObject;
  63. import org.eclipse.jgit.revwalk.RevSort;
  64. import org.eclipse.jgit.revwalk.RevTree;
  65. import org.eclipse.jgit.revwalk.RevWalk;
  66. import org.eclipse.jgit.revwalk.filter.CommitTimeRevFilter;
  67. import org.eclipse.jgit.revwalk.filter.RevFilter;
  68. import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
  69. import org.eclipse.jgit.transport.CredentialsProvider;
  70. import org.eclipse.jgit.transport.FetchResult;
  71. import org.eclipse.jgit.transport.RefSpec;
  72. import org.eclipse.jgit.treewalk.TreeWalk;
  73. import org.eclipse.jgit.treewalk.filter.AndTreeFilter;
  74. import org.eclipse.jgit.treewalk.filter.OrTreeFilter;
  75. import org.eclipse.jgit.treewalk.filter.PathFilter;
  76. import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
  77. import org.eclipse.jgit.treewalk.filter.PathSuffixFilter;
  78. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  79. import org.eclipse.jgit.util.FS;
  80. import org.eclipse.jgit.util.io.DisabledOutputStream;
  81. import org.slf4j.Logger;
  82. import org.slf4j.LoggerFactory;
  83. import com.gitblit.models.GitNote;
  84. import com.gitblit.models.PathModel;
  85. import com.gitblit.models.PathModel.PathChangeModel;
  86. import com.gitblit.models.RefModel;
  87. import com.gitblit.models.SubmoduleModel;
  88. /**
  89. * Collection of static methods for retrieving information from a repository.
  90. *
  91. * @author James Moger
  92. *
  93. */
  94. public class JGitUtils {
  95. static final Logger LOGGER = LoggerFactory.getLogger(JGitUtils.class);
  96. /**
  97. * Log an error message and exception.
  98. *
  99. * @param t
  100. * @param repository
  101. * if repository is not null it MUST be the {0} parameter in the
  102. * pattern.
  103. * @param pattern
  104. * @param objects
  105. */
  106. private static void error(Throwable t, Repository repository, String pattern, Object... objects) {
  107. List<Object> parameters = new ArrayList<Object>();
  108. if (objects != null && objects.length > 0) {
  109. for (Object o : objects) {
  110. parameters.add(o);
  111. }
  112. }
  113. if (repository != null) {
  114. parameters.add(0, repository.getDirectory().getAbsolutePath());
  115. }
  116. LOGGER.error(MessageFormat.format(pattern, parameters.toArray()), t);
  117. }
  118. /**
  119. * Returns the displayable name of the person in the form "Real Name <email
  120. * address>". If the email address is empty, just "Real Name" is returned.
  121. *
  122. * @param person
  123. * @return "Real Name <email address>" or "Real Name"
  124. */
  125. public static String getDisplayName(PersonIdent person) {
  126. if (StringUtils.isEmpty(person.getEmailAddress())) {
  127. return person.getName();
  128. }
  129. final StringBuilder r = new StringBuilder();
  130. r.append(person.getName());
  131. r.append(" <");
  132. r.append(person.getEmailAddress());
  133. r.append('>');
  134. return r.toString().trim();
  135. }
  136. /**
  137. * Encapsulates the result of cloning or pulling from a repository.
  138. */
  139. public static class CloneResult {
  140. public String name;
  141. public FetchResult fetchResult;
  142. public boolean createdRepository;
  143. }
  144. /**
  145. * Clone or Fetch a repository. If the local repository does not exist,
  146. * clone is called. If the repository does exist, fetch is called. By
  147. * default the clone/fetch retrieves the remote heads, tags, and notes.
  148. *
  149. * @param repositoriesFolder
  150. * @param name
  151. * @param fromUrl
  152. * @return CloneResult
  153. * @throws Exception
  154. */
  155. public static CloneResult cloneRepository(File repositoriesFolder, String name, String fromUrl)
  156. throws Exception {
  157. return cloneRepository(repositoriesFolder, name, fromUrl, true, null);
  158. }
  159. /**
  160. * Clone or Fetch a repository. If the local repository does not exist,
  161. * clone is called. If the repository does exist, fetch is called. By
  162. * default the clone/fetch retrieves the remote heads, tags, and notes.
  163. *
  164. * @param repositoriesFolder
  165. * @param name
  166. * @param fromUrl
  167. * @param bare
  168. * @param credentialsProvider
  169. * @return CloneResult
  170. * @throws Exception
  171. */
  172. public static CloneResult cloneRepository(File repositoriesFolder, String name, String fromUrl,
  173. boolean bare, CredentialsProvider credentialsProvider) throws Exception {
  174. CloneResult result = new CloneResult();
  175. if (bare) {
  176. // bare repository, ensure .git suffix
  177. if (!name.toLowerCase().endsWith(Constants.DOT_GIT_EXT)) {
  178. name += Constants.DOT_GIT_EXT;
  179. }
  180. } else {
  181. // normal repository, strip .git suffix
  182. if (name.toLowerCase().endsWith(Constants.DOT_GIT_EXT)) {
  183. name = name.substring(0, name.indexOf(Constants.DOT_GIT_EXT));
  184. }
  185. }
  186. result.name = name;
  187. File folder = new File(repositoriesFolder, name);
  188. if (folder.exists()) {
  189. File gitDir = FileKey.resolve(new File(repositoriesFolder, name), FS.DETECTED);
  190. Repository repository = new FileRepositoryBuilder().setGitDir(gitDir).build();
  191. result.fetchResult = fetchRepository(credentialsProvider, repository);
  192. repository.close();
  193. } else {
  194. CloneCommand clone = new CloneCommand();
  195. clone.setBare(bare);
  196. clone.setCloneAllBranches(true);
  197. clone.setURI(fromUrl);
  198. clone.setDirectory(folder);
  199. if (credentialsProvider != null) {
  200. clone.setCredentialsProvider(credentialsProvider);
  201. }
  202. Repository repository = clone.call().getRepository();
  203. // Now we have to fetch because CloneCommand doesn't fetch
  204. // refs/notes nor does it allow manual RefSpec.
  205. result.createdRepository = true;
  206. result.fetchResult = fetchRepository(credentialsProvider, repository);
  207. repository.close();
  208. }
  209. return result;
  210. }
  211. /**
  212. * Fetch updates from the remote repository. If refSpecs is unspecifed,
  213. * remote heads, tags, and notes are retrieved.
  214. *
  215. * @param credentialsProvider
  216. * @param repository
  217. * @param refSpecs
  218. * @return FetchResult
  219. * @throws Exception
  220. */
  221. public static FetchResult fetchRepository(CredentialsProvider credentialsProvider,
  222. Repository repository, RefSpec... refSpecs) throws Exception {
  223. Git git = new Git(repository);
  224. FetchCommand fetch = git.fetch();
  225. List<RefSpec> specs = new ArrayList<RefSpec>();
  226. if (refSpecs == null || refSpecs.length == 0) {
  227. specs.add(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));
  228. specs.add(new RefSpec("+refs/tags/*:refs/tags/*"));
  229. specs.add(new RefSpec("+refs/notes/*:refs/notes/*"));
  230. } else {
  231. specs.addAll(Arrays.asList(refSpecs));
  232. }
  233. if (credentialsProvider != null) {
  234. fetch.setCredentialsProvider(credentialsProvider);
  235. }
  236. fetch.setRefSpecs(specs);
  237. FetchResult fetchRes = fetch.call();
  238. return fetchRes;
  239. }
  240. /**
  241. * Creates a bare repository.
  242. *
  243. * @param repositoriesFolder
  244. * @param name
  245. * @return Repository
  246. */
  247. public static Repository createRepository(File repositoriesFolder, String name) {
  248. try {
  249. Git git = Git.init().setDirectory(new File(repositoriesFolder, name)).setBare(true).call();
  250. return git.getRepository();
  251. } catch (GitAPIException e) {
  252. throw new RuntimeException(e);
  253. }
  254. }
  255. /**
  256. * Returns a list of repository names in the specified folder.
  257. *
  258. * @param repositoriesFolder
  259. * @param onlyBare
  260. * if true, only bare repositories repositories are listed. If
  261. * false all repositories are included.
  262. * @param searchSubfolders
  263. * recurse into subfolders to find grouped repositories
  264. * @param depth
  265. * optional recursion depth, -1 = infinite recursion
  266. * @param exclusions
  267. * list of regex exclusions for matching to folder names
  268. * @return list of repository names
  269. */
  270. public static List<String> getRepositoryList(File repositoriesFolder, boolean onlyBare,
  271. boolean searchSubfolders, int depth, List<String> exclusions) {
  272. List<String> list = new ArrayList<String>();
  273. if (repositoriesFolder == null || !repositoriesFolder.exists()) {
  274. return list;
  275. }
  276. List<Pattern> patterns = new ArrayList<Pattern>();
  277. if (!ArrayUtils.isEmpty(exclusions)) {
  278. for (String regex : exclusions) {
  279. patterns.add(Pattern.compile(regex));
  280. }
  281. }
  282. list.addAll(getRepositoryList(repositoriesFolder.getAbsolutePath(), repositoriesFolder,
  283. onlyBare, searchSubfolders, depth, patterns));
  284. StringUtils.sortRepositorynames(list);
  285. list.remove(".git"); // issue-256
  286. return list;
  287. }
  288. /**
  289. * Recursive function to find git repositories.
  290. *
  291. * @param basePath
  292. * basePath is stripped from the repository name as repositories
  293. * are relative to this path
  294. * @param searchFolder
  295. * @param onlyBare
  296. * if true only bare repositories will be listed. if false all
  297. * repositories are included.
  298. * @param searchSubfolders
  299. * recurse into subfolders to find grouped repositories
  300. * @param depth
  301. * recursion depth, -1 = infinite recursion
  302. * @param patterns
  303. * list of regex patterns for matching to folder names
  304. * @return
  305. */
  306. private static List<String> getRepositoryList(String basePath, File searchFolder,
  307. boolean onlyBare, boolean searchSubfolders, int depth, List<Pattern> patterns) {
  308. File baseFile = new File(basePath);
  309. List<String> list = new ArrayList<String>();
  310. if (depth == 0) {
  311. return list;
  312. }
  313. int nextDepth = (depth == -1) ? -1 : depth - 1;
  314. for (File file : searchFolder.listFiles()) {
  315. if (file.isDirectory()) {
  316. boolean exclude = false;
  317. for (Pattern pattern : patterns) {
  318. String path = FileUtils.getRelativePath(baseFile, file).replace('\\', '/');
  319. if (pattern.matcher(path).matches()) {
  320. LOGGER.debug(MessageFormat.format("excluding {0} because of rule {1}", path, pattern.pattern()));
  321. exclude = true;
  322. break;
  323. }
  324. }
  325. if (exclude) {
  326. // skip to next file
  327. continue;
  328. }
  329. File gitDir = FileKey.resolve(new File(searchFolder, file.getName()), FS.DETECTED);
  330. if (gitDir != null) {
  331. if (onlyBare && gitDir.getName().equals(".git")) {
  332. continue;
  333. }
  334. if (gitDir.equals(file) || gitDir.getParentFile().equals(file)) {
  335. // determine repository name relative to base path
  336. String repository = FileUtils.getRelativePath(baseFile, file);
  337. list.add(repository);
  338. } else if (searchSubfolders && file.canRead()) {
  339. // look for repositories in subfolders
  340. list.addAll(getRepositoryList(basePath, file, onlyBare, searchSubfolders,
  341. nextDepth, patterns));
  342. }
  343. } else if (searchSubfolders && file.canRead()) {
  344. // look for repositories in subfolders
  345. list.addAll(getRepositoryList(basePath, file, onlyBare, searchSubfolders,
  346. nextDepth, patterns));
  347. }
  348. }
  349. }
  350. return list;
  351. }
  352. /**
  353. * Returns the first commit on a branch. If the repository does not exist or
  354. * is empty, null is returned.
  355. *
  356. * @param repository
  357. * @param branch
  358. * if unspecified, HEAD is assumed.
  359. * @return RevCommit
  360. */
  361. public static RevCommit getFirstCommit(Repository repository, String branch) {
  362. if (!hasCommits(repository)) {
  363. return null;
  364. }
  365. RevCommit commit = null;
  366. try {
  367. // resolve branch
  368. ObjectId branchObject;
  369. if (StringUtils.isEmpty(branch)) {
  370. branchObject = getDefaultBranch(repository);
  371. } else {
  372. branchObject = repository.resolve(branch);
  373. }
  374. RevWalk walk = new RevWalk(repository);
  375. walk.sort(RevSort.REVERSE);
  376. RevCommit head = walk.parseCommit(branchObject);
  377. walk.markStart(head);
  378. commit = walk.next();
  379. walk.dispose();
  380. } catch (Throwable t) {
  381. error(t, repository, "{0} failed to determine first commit");
  382. }
  383. return commit;
  384. }
  385. /**
  386. * Returns the date of the first commit on a branch. If the repository does
  387. * not exist, Date(0) is returned. If the repository does exist bit is
  388. * empty, the last modified date of the repository folder is returned.
  389. *
  390. * @param repository
  391. * @param branch
  392. * if unspecified, HEAD is assumed.
  393. * @return Date of the first commit on a branch
  394. */
  395. public static Date getFirstChange(Repository repository, String branch) {
  396. RevCommit commit = getFirstCommit(repository, branch);
  397. if (commit == null) {
  398. if (repository == null || !repository.getDirectory().exists()) {
  399. return new Date(0);
  400. }
  401. // fresh repository
  402. return new Date(repository.getDirectory().lastModified());
  403. }
  404. return getCommitDate(commit);
  405. }
  406. /**
  407. * Determine if a repository has any commits. This is determined by checking
  408. * the for loose and packed objects.
  409. *
  410. * @param repository
  411. * @return true if the repository has commits
  412. */
  413. public static boolean hasCommits(Repository repository) {
  414. if (repository != null && repository.getDirectory().exists()) {
  415. return (new File(repository.getDirectory(), "objects").list().length > 2)
  416. || (new File(repository.getDirectory(), "objects/pack").list().length > 0);
  417. }
  418. return false;
  419. }
  420. /**
  421. * Encapsulates the result of cloning or pulling from a repository.
  422. */
  423. public static class LastChange {
  424. public Date when;
  425. public String who;
  426. LastChange() {
  427. when = new Date(0);
  428. }
  429. LastChange(long lastModified) {
  430. this.when = new Date(lastModified);
  431. }
  432. }
  433. /**
  434. * Returns the date and author of the most recent commit on a branch. If the
  435. * repository does not exist Date(0) is returned. If it does exist but is
  436. * empty, the last modified date of the repository folder is returned.
  437. *
  438. * @param repository
  439. * @return a LastChange object
  440. */
  441. public static LastChange getLastChange(Repository repository) {
  442. if (!hasCommits(repository)) {
  443. // null repository
  444. if (repository == null) {
  445. return new LastChange();
  446. }
  447. // fresh repository
  448. return new LastChange(repository.getDirectory().lastModified());
  449. }
  450. List<RefModel> branchModels = getLocalBranches(repository, true, -1);
  451. if (branchModels.size() > 0) {
  452. // find most recent branch update
  453. LastChange lastChange = new LastChange();
  454. for (RefModel branchModel : branchModels) {
  455. if (branchModel.getDate().after(lastChange.when)) {
  456. lastChange.when = branchModel.getDate();
  457. lastChange.who = branchModel.getAuthorIdent().getName();
  458. }
  459. }
  460. return lastChange;
  461. }
  462. // default to the repository folder modification date
  463. return new LastChange(repository.getDirectory().lastModified());
  464. }
  465. /**
  466. * Retrieves a Java Date from a Git commit.
  467. *
  468. * @param commit
  469. * @return date of the commit or Date(0) if the commit is null
  470. */
  471. public static Date getCommitDate(RevCommit commit) {
  472. if (commit == null) {
  473. return new Date(0);
  474. }
  475. return new Date(commit.getCommitTime() * 1000L);
  476. }
  477. /**
  478. * Retrieves a Java Date from a Git commit.
  479. *
  480. * @param commit
  481. * @return date of the commit or Date(0) if the commit is null
  482. */
  483. public static Date getAuthorDate(RevCommit commit) {
  484. if (commit == null) {
  485. return new Date(0);
  486. }
  487. return commit.getAuthorIdent().getWhen();
  488. }
  489. /**
  490. * Returns the specified commit from the repository. If the repository does
  491. * not exist or is empty, null is returned.
  492. *
  493. * @param repository
  494. * @param objectId
  495. * if unspecified, HEAD is assumed.
  496. * @return RevCommit
  497. */
  498. public static RevCommit getCommit(Repository repository, String objectId) {
  499. if (!hasCommits(repository)) {
  500. return null;
  501. }
  502. RevCommit commit = null;
  503. try {
  504. // resolve object id
  505. ObjectId branchObject;
  506. if (StringUtils.isEmpty(objectId)) {
  507. branchObject = getDefaultBranch(repository);
  508. } else {
  509. branchObject = repository.resolve(objectId);
  510. }
  511. RevWalk walk = new RevWalk(repository);
  512. RevCommit rev = walk.parseCommit(branchObject);
  513. commit = rev;
  514. walk.dispose();
  515. } catch (Throwable t) {
  516. error(t, repository, "{0} failed to get commit {1}", objectId);
  517. }
  518. return commit;
  519. }
  520. /**
  521. * Retrieves the raw byte content of a file in the specified tree.
  522. *
  523. * @param repository
  524. * @param tree
  525. * if null, the RevTree from HEAD is assumed.
  526. * @param path
  527. * @return content as a byte []
  528. */
  529. public static byte[] getByteContent(Repository repository, RevTree tree, final String path, boolean throwError) {
  530. RevWalk rw = new RevWalk(repository);
  531. TreeWalk tw = new TreeWalk(repository);
  532. tw.setFilter(PathFilterGroup.createFromStrings(Collections.singleton(path)));
  533. byte[] content = null;
  534. try {
  535. if (tree == null) {
  536. ObjectId object = getDefaultBranch(repository);
  537. RevCommit commit = rw.parseCommit(object);
  538. tree = commit.getTree();
  539. }
  540. tw.reset(tree);
  541. while (tw.next()) {
  542. if (tw.isSubtree() && !path.equals(tw.getPathString())) {
  543. tw.enterSubtree();
  544. continue;
  545. }
  546. ObjectId entid = tw.getObjectId(0);
  547. FileMode entmode = tw.getFileMode(0);
  548. if (entmode != FileMode.GITLINK) {
  549. RevObject ro = rw.lookupAny(entid, entmode.getObjectType());
  550. rw.parseBody(ro);
  551. ByteArrayOutputStream os = new ByteArrayOutputStream();
  552. ObjectLoader ldr = repository.open(ro.getId(), Constants.OBJ_BLOB);
  553. byte[] tmp = new byte[4096];
  554. InputStream in = ldr.openStream();
  555. int n;
  556. while ((n = in.read(tmp)) > 0) {
  557. os.write(tmp, 0, n);
  558. }
  559. in.close();
  560. content = os.toByteArray();
  561. }
  562. }
  563. } catch (Throwable t) {
  564. if (throwError) {
  565. error(t, repository, "{0} can't find {1} in tree {2}", path, tree.name());
  566. }
  567. } finally {
  568. rw.dispose();
  569. tw.release();
  570. }
  571. return content;
  572. }
  573. /**
  574. * Returns the UTF-8 string content of a file in the specified tree.
  575. *
  576. * @param repository
  577. * @param tree
  578. * if null, the RevTree from HEAD is assumed.
  579. * @param blobPath
  580. * @param charsets optional
  581. * @return UTF-8 string content
  582. */
  583. public static String getStringContent(Repository repository, RevTree tree, String blobPath, String... charsets) {
  584. byte[] content = getByteContent(repository, tree, blobPath, true);
  585. if (content == null) {
  586. return null;
  587. }
  588. return StringUtils.decodeString(content, charsets);
  589. }
  590. /**
  591. * Gets the raw byte content of the specified blob object.
  592. *
  593. * @param repository
  594. * @param objectId
  595. * @return byte [] blob content
  596. */
  597. public static byte[] getByteContent(Repository repository, String objectId) {
  598. RevWalk rw = new RevWalk(repository);
  599. byte[] content = null;
  600. try {
  601. RevBlob blob = rw.lookupBlob(ObjectId.fromString(objectId));
  602. rw.parseBody(blob);
  603. ByteArrayOutputStream os = new ByteArrayOutputStream();
  604. ObjectLoader ldr = repository.open(blob.getId(), Constants.OBJ_BLOB);
  605. byte[] tmp = new byte[4096];
  606. InputStream in = ldr.openStream();
  607. int n;
  608. while ((n = in.read(tmp)) > 0) {
  609. os.write(tmp, 0, n);
  610. }
  611. in.close();
  612. content = os.toByteArray();
  613. } catch (Throwable t) {
  614. error(t, repository, "{0} can't find blob {1}", objectId);
  615. } finally {
  616. rw.dispose();
  617. }
  618. return content;
  619. }
  620. /**
  621. * Gets the UTF-8 string content of the blob specified by objectId.
  622. *
  623. * @param repository
  624. * @param objectId
  625. * @param charsets optional
  626. * @return UTF-8 string content
  627. */
  628. public static String getStringContent(Repository repository, String objectId, String... charsets) {
  629. byte[] content = getByteContent(repository, objectId);
  630. if (content == null) {
  631. return null;
  632. }
  633. return StringUtils.decodeString(content, charsets);
  634. }
  635. /**
  636. * Returns the list of files in the specified folder at the specified
  637. * commit. If the repository does not exist or is empty, an empty list is
  638. * returned.
  639. *
  640. * @param repository
  641. * @param path
  642. * if unspecified, root folder is assumed.
  643. * @param commit
  644. * if null, HEAD is assumed.
  645. * @return list of files in specified path
  646. */
  647. public static List<PathModel> getFilesInPath(Repository repository, String path,
  648. RevCommit commit) {
  649. List<PathModel> list = new ArrayList<PathModel>();
  650. if (!hasCommits(repository)) {
  651. return list;
  652. }
  653. if (commit == null) {
  654. commit = getCommit(repository, null);
  655. }
  656. final TreeWalk tw = new TreeWalk(repository);
  657. try {
  658. tw.addTree(commit.getTree());
  659. if (!StringUtils.isEmpty(path)) {
  660. PathFilter f = PathFilter.create(path);
  661. tw.setFilter(f);
  662. tw.setRecursive(false);
  663. boolean foundFolder = false;
  664. while (tw.next()) {
  665. if (!foundFolder && tw.isSubtree()) {
  666. tw.enterSubtree();
  667. }
  668. if (tw.getPathString().equals(path)) {
  669. foundFolder = true;
  670. continue;
  671. }
  672. if (foundFolder) {
  673. list.add(getPathModel(tw, path, commit));
  674. }
  675. }
  676. } else {
  677. tw.setRecursive(false);
  678. while (tw.next()) {
  679. list.add(getPathModel(tw, null, commit));
  680. }
  681. }
  682. } catch (IOException e) {
  683. error(e, repository, "{0} failed to get files for commit {1}", commit.getName());
  684. } finally {
  685. tw.release();
  686. }
  687. Collections.sort(list);
  688. return list;
  689. }
  690. /**
  691. * Returns the list of files changed in a specified commit. If the
  692. * repository does not exist or is empty, an empty list is returned.
  693. *
  694. * @param repository
  695. * @param commit
  696. * if null, HEAD is assumed.
  697. * @return list of files changed in a commit
  698. */
  699. public static List<PathChangeModel> getFilesInCommit(Repository repository, RevCommit commit) {
  700. List<PathChangeModel> list = new ArrayList<PathChangeModel>();
  701. if (!hasCommits(repository)) {
  702. return list;
  703. }
  704. RevWalk rw = new RevWalk(repository);
  705. try {
  706. if (commit == null) {
  707. ObjectId object = getDefaultBranch(repository);
  708. commit = rw.parseCommit(object);
  709. }
  710. if (commit.getParentCount() == 0) {
  711. TreeWalk tw = new TreeWalk(repository);
  712. tw.reset();
  713. tw.setRecursive(true);
  714. tw.addTree(commit.getTree());
  715. while (tw.next()) {
  716. list.add(new PathChangeModel(tw.getPathString(), tw.getPathString(), 0, tw
  717. .getRawMode(0), tw.getObjectId(0).getName(), commit.getId().getName(),
  718. ChangeType.ADD));
  719. }
  720. tw.release();
  721. } else {
  722. RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
  723. DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
  724. df.setRepository(repository);
  725. df.setDiffComparator(RawTextComparator.DEFAULT);
  726. df.setDetectRenames(true);
  727. List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree());
  728. for (DiffEntry diff : diffs) {
  729. String objectId = diff.getNewId().name();
  730. if (diff.getChangeType().equals(ChangeType.DELETE)) {
  731. list.add(new PathChangeModel(diff.getOldPath(), diff.getOldPath(), 0, diff
  732. .getNewMode().getBits(), objectId, commit.getId().getName(), diff
  733. .getChangeType()));
  734. } else if (diff.getChangeType().equals(ChangeType.RENAME)) {
  735. list.add(new PathChangeModel(diff.getOldPath(), diff.getNewPath(), 0, diff
  736. .getNewMode().getBits(), objectId, commit.getId().getName(), diff
  737. .getChangeType()));
  738. } else {
  739. list.add(new PathChangeModel(diff.getNewPath(), diff.getNewPath(), 0, diff
  740. .getNewMode().getBits(), objectId, commit.getId().getName(), diff
  741. .getChangeType()));
  742. }
  743. }
  744. }
  745. } catch (Throwable t) {
  746. error(t, repository, "{0} failed to determine files in commit!");
  747. } finally {
  748. rw.dispose();
  749. }
  750. return list;
  751. }
  752. /**
  753. * Returns the list of files changed in a specified commit. If the
  754. * repository does not exist or is empty, an empty list is returned.
  755. *
  756. * @param repository
  757. * @param startCommit
  758. * earliest commit
  759. * @param endCommit
  760. * most recent commit. if null, HEAD is assumed.
  761. * @return list of files changed in a commit range
  762. */
  763. public static List<PathChangeModel> getFilesInRange(Repository repository, RevCommit startCommit, RevCommit endCommit) {
  764. List<PathChangeModel> list = new ArrayList<PathChangeModel>();
  765. if (!hasCommits(repository)) {
  766. return list;
  767. }
  768. try {
  769. DiffFormatter df = new DiffFormatter(null);
  770. df.setRepository(repository);
  771. df.setDiffComparator(RawTextComparator.DEFAULT);
  772. df.setDetectRenames(true);
  773. List<DiffEntry> diffEntries = df.scan(startCommit.getTree(), endCommit.getTree());
  774. for (DiffEntry diff : diffEntries) {
  775. if (diff.getChangeType().equals(ChangeType.DELETE)) {
  776. list.add(new PathChangeModel(diff.getOldPath(), diff.getOldPath(), 0, diff
  777. .getNewMode().getBits(), diff.getOldId().name(), null, diff
  778. .getChangeType()));
  779. } else if (diff.getChangeType().equals(ChangeType.RENAME)) {
  780. list.add(new PathChangeModel(diff.getOldPath(), diff.getNewPath(), 0, diff
  781. .getNewMode().getBits(), diff.getNewId().name(), null, diff
  782. .getChangeType()));
  783. } else {
  784. list.add(new PathChangeModel(diff.getNewPath(), diff.getNewPath(), 0, diff
  785. .getNewMode().getBits(), diff.getNewId().name(), null, diff
  786. .getChangeType()));
  787. }
  788. }
  789. Collections.sort(list);
  790. } catch (Throwable t) {
  791. error(t, repository, "{0} failed to determine files in range {1}..{2}!", startCommit, endCommit);
  792. }
  793. return list;
  794. }
  795. /**
  796. * Returns the list of files in the repository on the default branch that
  797. * match one of the specified extensions. This is a CASE-SENSITIVE search.
  798. * If the repository does not exist or is empty, an empty list is returned.
  799. *
  800. * @param repository
  801. * @param extensions
  802. * @return list of files in repository with a matching extension
  803. */
  804. public static List<PathModel> getDocuments(Repository repository, List<String> extensions) {
  805. return getDocuments(repository, extensions, null);
  806. }
  807. /**
  808. * Returns the list of files in the repository in the specified commit that
  809. * match one of the specified extensions. This is a CASE-SENSITIVE search.
  810. * If the repository does not exist or is empty, an empty list is returned.
  811. *
  812. * @param repository
  813. * @param extensions
  814. * @param objectId
  815. * @return list of files in repository with a matching extension
  816. */
  817. public static List<PathModel> getDocuments(Repository repository, List<String> extensions,
  818. String objectId) {
  819. List<PathModel> list = new ArrayList<PathModel>();
  820. if (!hasCommits(repository)) {
  821. return list;
  822. }
  823. RevCommit commit = getCommit(repository, objectId);
  824. final TreeWalk tw = new TreeWalk(repository);
  825. try {
  826. tw.addTree(commit.getTree());
  827. if (extensions != null && extensions.size() > 0) {
  828. List<TreeFilter> suffixFilters = new ArrayList<TreeFilter>();
  829. for (String extension : extensions) {
  830. if (extension.charAt(0) == '.') {
  831. suffixFilters.add(PathSuffixFilter.create("\\" + extension));
  832. } else {
  833. // escape the . since this is a regexp filter
  834. suffixFilters.add(PathSuffixFilter.create("\\." + extension));
  835. }
  836. }
  837. TreeFilter filter;
  838. if (suffixFilters.size() == 1) {
  839. filter = suffixFilters.get(0);
  840. } else {
  841. filter = OrTreeFilter.create(suffixFilters);
  842. }
  843. tw.setFilter(filter);
  844. tw.setRecursive(true);
  845. }
  846. while (tw.next()) {
  847. list.add(getPathModel(tw, null, commit));
  848. }
  849. } catch (IOException e) {
  850. error(e, repository, "{0} failed to get documents for commit {1}", commit.getName());
  851. } finally {
  852. tw.release();
  853. }
  854. Collections.sort(list);
  855. return list;
  856. }
  857. /**
  858. * Returns a path model of the current file in the treewalk.
  859. *
  860. * @param tw
  861. * @param basePath
  862. * @param commit
  863. * @return a path model of the current file in the treewalk
  864. */
  865. private static PathModel getPathModel(TreeWalk tw, String basePath, RevCommit commit) {
  866. String name;
  867. long size = 0;
  868. if (StringUtils.isEmpty(basePath)) {
  869. name = tw.getPathString();
  870. } else {
  871. name = tw.getPathString().substring(basePath.length() + 1);
  872. }
  873. ObjectId objectId = tw.getObjectId(0);
  874. try {
  875. if (!tw.isSubtree() && (tw.getFileMode(0) != FileMode.GITLINK)) {
  876. size = tw.getObjectReader().getObjectSize(objectId, Constants.OBJ_BLOB);
  877. }
  878. } catch (Throwable t) {
  879. error(t, null, "failed to retrieve blob size for " + tw.getPathString());
  880. }
  881. return new PathModel(name, tw.getPathString(), size, tw.getFileMode(0).getBits(),
  882. objectId.getName(), commit.getName());
  883. }
  884. /**
  885. * Returns a permissions representation of the mode bits.
  886. *
  887. * @param mode
  888. * @return string representation of the mode bits
  889. */
  890. public static String getPermissionsFromMode(int mode) {
  891. if (FileMode.TREE.equals(mode)) {
  892. return "drwxr-xr-x";
  893. } else if (FileMode.REGULAR_FILE.equals(mode)) {
  894. return "-rw-r--r--";
  895. } else if (FileMode.EXECUTABLE_FILE.equals(mode)) {
  896. return "-rwxr-xr-x";
  897. } else if (FileMode.SYMLINK.equals(mode)) {
  898. return "symlink";
  899. } else if (FileMode.GITLINK.equals(mode)) {
  900. return "submodule";
  901. }
  902. return "missing";
  903. }
  904. /**
  905. * Returns a list of commits since the minimum date starting from the
  906. * specified object id.
  907. *
  908. * @param repository
  909. * @param objectId
  910. * if unspecified, HEAD is assumed.
  911. * @param minimumDate
  912. * @return list of commits
  913. */
  914. public static List<RevCommit> getRevLog(Repository repository, String objectId, Date minimumDate) {
  915. List<RevCommit> list = new ArrayList<RevCommit>();
  916. if (!hasCommits(repository)) {
  917. return list;
  918. }
  919. try {
  920. // resolve branch
  921. ObjectId branchObject;
  922. if (StringUtils.isEmpty(objectId)) {
  923. branchObject = getDefaultBranch(repository);
  924. } else {
  925. branchObject = repository.resolve(objectId);
  926. }
  927. RevWalk rw = new RevWalk(repository);
  928. rw.markStart(rw.parseCommit(branchObject));
  929. rw.setRevFilter(CommitTimeRevFilter.after(minimumDate));
  930. Iterable<RevCommit> revlog = rw;
  931. for (RevCommit rev : revlog) {
  932. list.add(rev);
  933. }
  934. rw.dispose();
  935. } catch (Throwable t) {
  936. error(t, repository, "{0} failed to get {1} revlog for minimum date {2}", objectId,
  937. minimumDate);
  938. }
  939. return list;
  940. }
  941. /**
  942. * Returns a list of commits starting from HEAD and working backwards.
  943. *
  944. * @param repository
  945. * @param maxCount
  946. * if < 0, all commits for the repository are returned.
  947. * @return list of commits
  948. */
  949. public static List<RevCommit> getRevLog(Repository repository, int maxCount) {
  950. return getRevLog(repository, null, 0, maxCount);
  951. }
  952. /**
  953. * Returns a list of commits starting from the specified objectId using an
  954. * offset and maxCount for paging. This is similar to LIMIT n OFFSET p in
  955. * SQL. If the repository does not exist or is empty, an empty list is
  956. * returned.
  957. *
  958. * @param repository
  959. * @param objectId
  960. * if unspecified, HEAD is assumed.
  961. * @param offset
  962. * @param maxCount
  963. * if < 0, all commits are returned.
  964. * @return a paged list of commits
  965. */
  966. public static List<RevCommit> getRevLog(Repository repository, String objectId, int offset,
  967. int maxCount) {
  968. return getRevLog(repository, objectId, null, offset, maxCount);
  969. }
  970. /**
  971. * Returns a list of commits for the repository or a path within the
  972. * repository. Caller may specify ending revision with objectId. Caller may
  973. * specify offset and maxCount to achieve pagination of results. If the
  974. * repository does not exist or is empty, an empty list is returned.
  975. *
  976. * @param repository
  977. * @param objectId
  978. * if unspecified, HEAD is assumed.
  979. * @param path
  980. * if unspecified, commits for repository are returned. If
  981. * specified, commits for the path are returned.
  982. * @param offset
  983. * @param maxCount
  984. * if < 0, all commits are returned.
  985. * @return a paged list of commits
  986. */
  987. public static List<RevCommit> getRevLog(Repository repository, String objectId, String path,
  988. int offset, int maxCount) {
  989. List<RevCommit> list = new ArrayList<RevCommit>();
  990. if (maxCount == 0) {
  991. return list;
  992. }
  993. if (!hasCommits(repository)) {
  994. return list;
  995. }
  996. try {
  997. // resolve branch
  998. ObjectId startRange = null;
  999. ObjectId endRange;
  1000. if (StringUtils.isEmpty(objectId)) {
  1001. endRange = getDefaultBranch(repository);
  1002. } else {
  1003. if( objectId.contains("..") ) {
  1004. // range expression
  1005. String[] parts = objectId.split("\\.\\.");
  1006. startRange = repository.resolve(parts[0]);
  1007. endRange = repository.resolve(parts[1]);
  1008. } else {
  1009. // objectid
  1010. endRange= repository.resolve(objectId);
  1011. }
  1012. }
  1013. if (endRange == null) {
  1014. return list;
  1015. }
  1016. RevWalk rw = new RevWalk(repository);
  1017. rw.markStart(rw.parseCommit(endRange));
  1018. if (startRange != null) {
  1019. rw.markUninteresting(rw.parseCommit(startRange));
  1020. }
  1021. if (!StringUtils.isEmpty(path)) {
  1022. TreeFilter filter = AndTreeFilter.create(
  1023. PathFilterGroup.createFromStrings(Collections.singleton(path)),
  1024. TreeFilter.ANY_DIFF);
  1025. rw.setTreeFilter(filter);
  1026. }
  1027. Iterable<RevCommit> revlog = rw;
  1028. if (offset > 0) {
  1029. int count = 0;
  1030. for (RevCommit rev : revlog) {
  1031. count++;
  1032. if (count > offset) {
  1033. list.add(rev);
  1034. if (maxCount > 0 && list.size() == maxCount) {
  1035. break;
  1036. }
  1037. }
  1038. }
  1039. } else {
  1040. for (RevCommit rev : revlog) {
  1041. list.add(rev);
  1042. if (maxCount > 0 && list.size() == maxCount) {
  1043. break;
  1044. }
  1045. }
  1046. }
  1047. rw.dispose();
  1048. } catch (Throwable t) {
  1049. error(t, repository, "{0} failed to get {1} revlog for path {2}", objectId, path);
  1050. }
  1051. return list;
  1052. }
  1053. /**
  1054. * Returns a list of commits for the repository within the range specified
  1055. * by startRangeId and endRangeId. If the repository does not exist or is
  1056. * empty, an empty list is returned.
  1057. *
  1058. * @param repository
  1059. * @param startRangeId
  1060. * the first commit (not included in results)
  1061. * @param endRangeId
  1062. * the end commit (included in results)
  1063. * @return a list of commits
  1064. */
  1065. public static List<RevCommit> getRevLog(Repository repository, String startRangeId,
  1066. String endRangeId) {
  1067. List<RevCommit> list = new ArrayList<RevCommit>();
  1068. if (!hasCommits(repository)) {
  1069. return list;
  1070. }
  1071. try {
  1072. ObjectId endRange = repository.resolve(endRangeId);
  1073. ObjectId startRange = repository.resolve(startRangeId);
  1074. RevWalk rw = new RevWalk(repository);
  1075. rw.markStart(rw.parseCommit(endRange));
  1076. if (startRange.equals(ObjectId.zeroId())) {
  1077. // maybe this is a tag or an orphan branch
  1078. list.add(rw.parseCommit(endRange));
  1079. rw.dispose();
  1080. return list;
  1081. } else {
  1082. rw.markUninteresting(rw.parseCommit(startRange));
  1083. }
  1084. Iterable<RevCommit> revlog = rw;
  1085. for (RevCommit rev : revlog) {
  1086. list.add(rev);
  1087. }
  1088. rw.dispose();
  1089. } catch (Throwable t) {
  1090. error(t, repository, "{0} failed to get revlog for {1}..{2}", startRangeId, endRangeId);
  1091. }
  1092. return list;
  1093. }
  1094. /**
  1095. * Search the commit history for a case-insensitive match to the value.
  1096. * Search results require a specified SearchType of AUTHOR, COMMITTER, or
  1097. * COMMIT. Results may be paginated using offset and maxCount. If the
  1098. * repository does not exist or is empty, an empty list is returned.
  1099. *
  1100. * @param repository
  1101. * @param objectId
  1102. * if unspecified, HEAD is assumed.
  1103. * @param value
  1104. * @param type
  1105. * AUTHOR, COMMITTER, COMMIT
  1106. * @param offset
  1107. * @param maxCount
  1108. * if < 0, all matches are returned
  1109. * @return matching list of commits
  1110. */
  1111. public static List<RevCommit> searchRevlogs(Repository repository, String objectId,
  1112. String value, final com.gitblit.Constants.SearchType type, int offset, int maxCount) {
  1113. final String lcValue = value.toLowerCase();
  1114. List<RevCommit> list = new ArrayList<RevCommit>();
  1115. if (maxCount == 0) {
  1116. return list;
  1117. }
  1118. if (!hasCommits(repository)) {
  1119. return list;
  1120. }
  1121. try {
  1122. // resolve branch
  1123. ObjectId branchObject;
  1124. if (StringUtils.isEmpty(objectId)) {
  1125. branchObject = getDefaultBranch(repository);
  1126. } else {
  1127. branchObject = repository.resolve(objectId);
  1128. }
  1129. RevWalk rw = new RevWalk(repository);
  1130. rw.setRevFilter(new RevFilter() {
  1131. @Override
  1132. public RevFilter clone() {
  1133. // FindBugs complains about this method name.
  1134. // This is part of JGit design and unrelated to Cloneable.
  1135. return this;
  1136. }
  1137. @Override
  1138. public boolean include(RevWalk walker, RevCommit commit) throws StopWalkException,
  1139. MissingObjectException, IncorrectObjectTypeException, IOException {
  1140. boolean include = false;
  1141. switch (type) {
  1142. case AUTHOR:
  1143. include = (commit.getAuthorIdent().getName().toLowerCase().indexOf(lcValue) > -1)
  1144. || (commit.getAuthorIdent().getEmailAddress().toLowerCase()
  1145. .indexOf(lcValue) > -1);
  1146. break;
  1147. case COMMITTER:
  1148. include = (commit.getCommitterIdent().getName().toLowerCase()
  1149. .indexOf(lcValue) > -1)
  1150. || (commit.getCommitterIdent().getEmailAddress().toLowerCase()
  1151. .indexOf(lcValue) > -1);
  1152. break;
  1153. case COMMIT:
  1154. include = commit.getFullMessage().toLowerCase().indexOf(lcValue) > -1;
  1155. break;
  1156. }
  1157. return include;
  1158. }
  1159. });
  1160. rw.markStart(rw.parseCommit(branchObject));
  1161. Iterable<RevCommit> revlog = rw;
  1162. if (offset > 0) {
  1163. int count = 0;
  1164. for (RevCommit rev : revlog) {
  1165. count++;
  1166. if (count > offset) {
  1167. list.add(rev);
  1168. if (maxCount > 0 && list.size() == maxCount) {
  1169. break;
  1170. }
  1171. }
  1172. }
  1173. } else {
  1174. for (RevCommit rev : revlog) {
  1175. list.add(rev);
  1176. if (maxCount > 0 && list.size() == maxCount) {
  1177. break;
  1178. }
  1179. }
  1180. }
  1181. rw.dispose();
  1182. } catch (Throwable t) {
  1183. error(t, repository, "{0} failed to {1} search revlogs for {2}", type.name(), value);
  1184. }
  1185. return list;
  1186. }
  1187. /**
  1188. * Returns the default branch to use for a repository. Normally returns
  1189. * whatever branch HEAD points to, but if HEAD points to nothing it returns
  1190. * the most recently updated branch.
  1191. *
  1192. * @param repository
  1193. * @return the objectid of a branch
  1194. * @throws Exception
  1195. */
  1196. public static ObjectId getDefaultBranch(Repository repository) throws Exception {
  1197. ObjectId object = repository.resolve(Constants.HEAD);
  1198. if (object == null) {
  1199. // no HEAD
  1200. // perhaps non-standard repository, try local branches
  1201. List<RefModel> branchModels = getLocalBranches(repository, true, -1);
  1202. if (branchModels.size() > 0) {
  1203. // use most recently updated branch
  1204. RefModel branch = null;
  1205. Date lastDate = new Date(0);
  1206. for (RefModel branchModel : branchModels) {
  1207. if (branchModel.getDate().after(lastDate)) {
  1208. branch = branchModel;
  1209. lastDate = branch.getDate();
  1210. }
  1211. }
  1212. object = branch.getReferencedObjectId();
  1213. }
  1214. }
  1215. return object;
  1216. }
  1217. /**
  1218. * Returns the target of the symbolic HEAD reference for a repository.
  1219. * Normally returns a branch reference name, but when HEAD is detached,
  1220. * the commit is matched against the known tags. The most recent matching
  1221. * tag ref name will be returned if it references the HEAD commit. If
  1222. * no match is found, the SHA1 is returned.
  1223. *
  1224. * @param repository
  1225. * @return the ref name or the SHA1 for a detached HEAD
  1226. */
  1227. public static String getHEADRef(Repository repository) {
  1228. String target = null;
  1229. try {
  1230. target = repository.getFullBranch();
  1231. if (!target.startsWith(Constants.R_HEADS)) {
  1232. // refers to an actual commit, probably a tag
  1233. // find latest tag that matches the commit, if any
  1234. List<RefModel> tagModels = getTags(repository, true, -1);
  1235. if (tagModels.size() > 0) {
  1236. RefModel tag = null;
  1237. Date lastDate = new Date(0);
  1238. for (RefModel tagModel : tagModels) {
  1239. if (tagModel.getReferencedObjectId().getName().equals(target) &&
  1240. tagModel.getDate().after(lastDate)) {
  1241. tag = tagModel;
  1242. lastDate = tag.getDate();
  1243. }
  1244. }
  1245. target = tag.getName();
  1246. }
  1247. }
  1248. } catch (Throwable t) {
  1249. error(t, repository, "{0} failed to get symbolic HEAD target");
  1250. }
  1251. return target;
  1252. }
  1253. /**
  1254. * Sets the symbolic ref HEAD to the specified target ref. The
  1255. * HEAD will be detached if the target ref is not a branch.
  1256. *
  1257. * @param repository
  1258. * @param targetRef
  1259. * @return true if successful
  1260. */
  1261. public static boolean setHEADtoRef(Repository repository, String targetRef) {
  1262. try {
  1263. // detach HEAD if target ref is not a branch
  1264. boolean detach = !targetRef.startsWith(Constants.R_HEADS);
  1265. RefUpdate.Result result;
  1266. RefUpdate head = repository.updateRef(Constants.HEAD, detach);
  1267. if (detach) { // Tag
  1268. RevCommit commit = getCommit(repository, targetRef);
  1269. head.setNewObjectId(commit.getId());
  1270. result = head.forceUpdate();
  1271. } else {
  1272. result = head.link(targetRef);
  1273. }
  1274. switch (result) {
  1275. case NEW:
  1276. case FORCED:
  1277. case NO_CHANGE:
  1278. case FAST_FORWARD:
  1279. return true;
  1280. default:
  1281. LOGGER.error(MessageFormat.format("{0} HEAD update to {1} returned result {2}",
  1282. repository.getDirectory().getAbsolutePath(), targetRef, result));
  1283. }
  1284. } catch (Throwable t) {
  1285. error(t, repository, "{0} failed to set HEAD to {1}", targetRef);
  1286. }
  1287. return false;
  1288. }
  1289. /**
  1290. * Sets the local branch ref to point to the specified commit id.
  1291. *
  1292. * @param repository
  1293. * @param branch
  1294. * @param commitId
  1295. * @return true if successful
  1296. */
  1297. public static boolean setBranchRef(Repository repository, String branch, String commitId) {
  1298. String branchName = branch;
  1299. if (!branchName.startsWith(Constants.R_HEADS)) {
  1300. branchName = Constants.R_HEADS + branch;
  1301. }
  1302. try {
  1303. RefUpdate refUpdate = repository.updateRef(branchName, false);
  1304. refUpdate.setNewObjectId(ObjectId.fromString(commitId));
  1305. RefUpdate.Result result = refUpdate.forceUpdate();
  1306. switch (result) {
  1307. case NEW:
  1308. case FORCED:
  1309. case NO_CHANGE:
  1310. case FAST_FORWARD:
  1311. return true;
  1312. default:
  1313. LOGGER.error(MessageFormat.format("{0} {1} update to {2} returned result {3}",
  1314. repository.getDirectory().getAbsolutePath(), branchName, commitId, result));
  1315. }
  1316. } catch (Throwable t) {
  1317. error(t, repository, "{0} failed to set {1} to {2}", branchName, commitId);
  1318. }
  1319. return false;
  1320. }
  1321. /**
  1322. * Deletes the specified branch ref.
  1323. *
  1324. * @param repository
  1325. * @param branch
  1326. * @return true if successful
  1327. */
  1328. public static boolean deleteBranchRef(Repository repository, String branch) {
  1329. String branchName = branch;
  1330. if (!branchName.startsWith(Constants.R_HEADS)) {
  1331. branchName = Constants.R_HEADS + branch;
  1332. }
  1333. try {
  1334. RefUpdate refUpdate = repository.updateRef(branchName, false);
  1335. refUpdate.setForceUpdate(true);
  1336. RefUpdate.Result result = refUpdate.delete();
  1337. switch (result) {
  1338. case NEW:
  1339. case FORCED:
  1340. case NO_CHANGE:
  1341. case FAST_FORWARD:
  1342. return true;
  1343. default:
  1344. LOGGER.error(MessageFormat.format("{0} failed to delete to {1} returned result {2}",
  1345. repository.getDirectory().getAbsolutePath(), branchName, result));
  1346. }
  1347. } catch (Throwable t) {
  1348. error(t, repository, "{0} failed to delete {1}", branchName);
  1349. }
  1350. return false;
  1351. }
  1352. /**
  1353. * Get the full branch and tag ref names for any potential HEAD targets.
  1354. *
  1355. * @param repository
  1356. * @return a list of ref names
  1357. */
  1358. public static List<String> getAvailableHeadTargets(Repository repository) {
  1359. List<String> targets = new ArrayList<String>();
  1360. for (RefModel branchModel : JGitUtils.getLocalBranches(repository, true, -1)) {
  1361. targets.add(branchModel.getName());
  1362. }
  1363. for (RefModel tagModel : JGitUtils.getTags(repository, true, -1)) {
  1364. targets.add(tagModel.getName());
  1365. }
  1366. return targets;
  1367. }
  1368. /**
  1369. * Returns all refs grouped by their associated object id.
  1370. *
  1371. * @param repository
  1372. * @return all refs grouped by their referenced object id
  1373. */
  1374. public static Map<ObjectId, List<RefModel>> getAllRefs(Repository repository) {
  1375. return getAllRefs(repository, true);
  1376. }
  1377. /**
  1378. * Returns all refs grouped by their associated object id.
  1379. *
  1380. * @param repository
  1381. * @param includeRemoteRefs
  1382. * @return all refs grouped by their referenced object id
  1383. */
  1384. public static Map<ObjectId, List<RefModel>> getAllRefs(Repository repository, boolean includeRemoteRefs) {
  1385. List<RefModel> list = getRefs(repository, org.eclipse.jgit.lib.RefDatabase.ALL, true, -1);
  1386. Map<ObjectId, List<RefModel>> refs = new HashMap<ObjectId, List<RefModel>>();
  1387. for (RefModel ref : list) {
  1388. if (!includeRemoteRefs && ref.getName().startsWith(Constants.R_REMOTES)) {
  1389. continue;
  1390. }
  1391. ObjectId objectid = ref.getReferencedObjectId();
  1392. if (!refs.containsKey(objectid)) {
  1393. refs.put(objectid, new ArrayList<RefModel>());
  1394. }
  1395. refs.get(objectid).add(ref);
  1396. }
  1397. return refs;
  1398. }
  1399. /**
  1400. * Returns the list of tags in the repository. If repository does not exist
  1401. * or is empty, an empty list is returned.
  1402. *
  1403. * @param repository
  1404. * @param fullName
  1405. * if true, /refs/tags/yadayadayada is returned. If false,
  1406. * yadayadayada is returned.
  1407. * @param maxCount
  1408. * if < 0, all tags are returned
  1409. * @return list of tags
  1410. */
  1411. public static List<RefModel> getTags(Repository repository, boolean fullName, int maxCount) {
  1412. return getRefs(repository, Constants.R_TAGS, fullName, maxCount);
  1413. }
  1414. /**
  1415. * Returns the list of local branches in the repository. If repository does
  1416. * not exist or is empty, an empty list is returned.
  1417. *
  1418. * @param repository
  1419. * @param fullName
  1420. * if true, /refs/heads/yadayadayada is returned. If false,
  1421. * yadayadayada is returned.
  1422. * @param maxCount
  1423. * if < 0, all local branches are returned
  1424. * @return list of local branches
  1425. */
  1426. public static List<RefModel> getLocalBranches(Repository repository, boolean fullName,
  1427. int maxCount) {
  1428. return getRefs(repository, Constants.R_HEADS, fullName, maxCount);
  1429. }
  1430. /**
  1431. * Returns the list of remote branches in the repository. If repository does
  1432. * not exist or is empty, an empty list is returned.
  1433. *
  1434. * @param repository
  1435. * @param fullName
  1436. * if true, /refs/remotes/yadayadayada is returned. If false,
  1437. * yadayadayada is returned.
  1438. * @param maxCount
  1439. * if < 0, all remote branches are returned
  1440. * @return list of remote branches
  1441. */
  1442. public static List<RefModel> getRemoteBranches(Repository repository, boolean fullName,
  1443. int maxCount) {
  1444. return getRefs(repository, Constants.R_REMOTES, fullName, maxCount);
  1445. }
  1446. /**
  1447. * Returns the list of note branches. If repository does not exist or is
  1448. * empty, an empty list is returned.
  1449. *
  1450. * @param repository
  1451. * @param fullName
  1452. * if true, /refs/notes/yadayadayada is returned. If false,
  1453. * yadayadayada is returned.
  1454. * @param maxCount
  1455. * if < 0, all note branches are returned
  1456. * @return list of note branches
  1457. */
  1458. public static List<RefModel> getNoteBranches(Repository repository, boolean fullName,
  1459. int maxCount) {
  1460. return getRefs(repository, Constants.R_NOTES, fullName, maxCount);
  1461. }
  1462. /**
  1463. * Returns the list of refs in the specified base ref. If repository does
  1464. * not exist or is empty, an empty list is returned.
  1465. *
  1466. * @param repository
  1467. * @param fullName
  1468. * if true, /refs/yadayadayada is returned. If false,
  1469. * yadayadayada is returned.
  1470. * @return list of refs
  1471. */
  1472. public static List<RefModel> getRefs(Repository repository, String baseRef) {
  1473. return getRefs(repository, baseRef, true, -1);
  1474. }
  1475. /**
  1476. * Returns a list of references in the repository matching "refs". If the
  1477. * repository is null or empty, an empty list is returned.
  1478. *
  1479. * @param repository
  1480. * @param refs
  1481. * if unspecified, all refs are returned
  1482. * @param fullName
  1483. * if true, /refs/something/yadayadayada is returned. If false,
  1484. * yadayadayada is returned.
  1485. * @param maxCount
  1486. * if < 0, all references are returned
  1487. * @return list of references
  1488. */
  1489. private static List<RefModel> getRefs(Repository repository, String refs, boolean fullName,
  1490. int maxCount) {
  1491. List<RefModel> list = new ArrayList<RefModel>();
  1492. if (maxCount == 0) {
  1493. return list;
  1494. }
  1495. if (!hasCommits(repository)) {
  1496. return list;
  1497. }
  1498. try {
  1499. Map<String, Ref> map = repository.getRefDatabase().getRefs(refs);
  1500. RevWalk rw = new RevWalk(repository);
  1501. for (Entry<String, Ref> entry : map.entrySet()) {
  1502. Ref ref = entry.getValue();
  1503. RevObject object = rw.parseAny(ref.getObjectId());
  1504. String name = entry.getKey();
  1505. if (fullName && !StringUtils.isEmpty(refs)) {
  1506. name = refs + name;
  1507. }
  1508. list.add(new RefModel(name, ref, object));
  1509. }
  1510. rw.dispose();
  1511. Collections.sort(list);
  1512. Collections.reverse(list);
  1513. if (maxCount > 0 && list.size() > maxCount) {
  1514. list = new ArrayList<RefModel>(list.subList(0, maxCount));
  1515. }
  1516. } catch (IOException e) {
  1517. error(e, repository, "{0} failed to retrieve {1}", refs);
  1518. }
  1519. return list;
  1520. }
  1521. /**
  1522. * Returns a RefModel for the gh-pages branch in the repository. If the
  1523. * branch can not be found, null is returned.
  1524. *
  1525. * @param repository
  1526. * @return a refmodel for the gh-pages branch or null
  1527. */
  1528. public static RefModel getPagesBranch(Repository repository) {
  1529. return getBranch(repository, "gh-pages");
  1530. }
  1531. /**
  1532. * Returns a RefModel for a specific branch name in the repository. If the
  1533. * branch can not be found, null is returned.
  1534. *
  1535. * @param repository
  1536. * @return a refmodel for the branch or null
  1537. */
  1538. public static RefModel getBranch(Repository repository, String name) {
  1539. RefModel branch = null;
  1540. try {
  1541. // search for the branch in local heads
  1542. for (RefModel ref : JGitUtils.getLocalBranches(repository, false, -1)) {
  1543. if (ref.reference.getName().endsWith(name)) {
  1544. branch = ref;
  1545. break;
  1546. }
  1547. }
  1548. // search for the branch in remote heads
  1549. if (branch == null) {
  1550. for (RefModel ref : JGitUtils.getRemoteBranches(repository, false, -1)) {
  1551. if (ref.reference.getName().endsWith(name)) {
  1552. branch = ref;
  1553. break;
  1554. }
  1555. }
  1556. }
  1557. } catch (Throwable t) {
  1558. LOGGER.error(MessageFormat.format("Failed to find {0} branch!", name), t);
  1559. }
  1560. return branch;
  1561. }
  1562. /**
  1563. * Returns the list of submodules for this repository.
  1564. *
  1565. * @param repository
  1566. * @param commit
  1567. * @return list of submodules
  1568. */
  1569. public static List<SubmoduleModel> getSubmodules(Repository repository, String commitId) {
  1570. RevCommit commit = getCommit(repository, commitId);
  1571. return getSubmodules(repository, commit.getTree());
  1572. }
  1573. /**
  1574. * Returns the list of submodules for this repository.
  1575. *
  1576. * @param repository
  1577. * @param commit
  1578. * @return list of submodules
  1579. */
  1580. public static List<SubmoduleModel> getSubmodules(Repository repository, RevTree tree) {
  1581. List<SubmoduleModel> list = new ArrayList<SubmoduleModel>();
  1582. byte [] blob = getByteContent(repository, tree, ".gitmodules", false);
  1583. if (blob == null) {
  1584. return list;
  1585. }
  1586. try {
  1587. BlobBasedConfig config = new BlobBasedConfig(repository.getConfig(), blob);
  1588. for (String module : config.getSubsections("submodule")) {
  1589. String path = config.getString("submodule", module, "path");
  1590. String url = config.getString("submodule", module, "url");
  1591. list.add(new SubmoduleModel(module, path, url));
  1592. }
  1593. } catch (ConfigInvalidException e) {
  1594. LOGGER.error("Failed to load .gitmodules file for " + repository.getDirectory(), e);
  1595. }
  1596. return list;
  1597. }
  1598. /**
  1599. * Returns the submodule definition for the specified path at the specified
  1600. * commit. If no module is defined for the path, null is returned.
  1601. *
  1602. * @param repository
  1603. * @param commit
  1604. * @param path
  1605. * @return a submodule definition or null if there is no submodule
  1606. */
  1607. public static SubmoduleModel getSubmoduleModel(Repository repository, String commitId, String path) {
  1608. for (SubmoduleModel model : getSubmodules(repository, commitId)) {
  1609. if (model.path.equals(path)) {
  1610. return model;
  1611. }
  1612. }
  1613. return null;
  1614. }
  1615. public static String getSubmoduleCommitId(Repository repository, String path, RevCommit commit) {
  1616. String commitId = null;
  1617. RevWalk rw = new RevWalk(repository);
  1618. TreeWalk tw = new TreeWalk(repository);
  1619. tw.setFilter(PathFilterGroup.createFromStrings(Collections.singleton(path)));
  1620. try {
  1621. tw.reset(commit.getTree());
  1622. while (tw.next()) {
  1623. if (tw.isSubtree() && !path.equals(tw.getPathString())) {
  1624. tw.enterSubtree();
  1625. continue;
  1626. }
  1627. if (FileMode.GITLINK == tw.getFileMode(0)) {
  1628. commitId = tw.getObjectId(0).getName();
  1629. break;
  1630. }
  1631. }
  1632. } catch (Throwable t) {
  1633. error(t, repository, "{0} can't find {1} in commit {2}", path, commit.name());
  1634. } finally {
  1635. rw.dispose();
  1636. tw.release();
  1637. }
  1638. return commitId;
  1639. }
  1640. /**
  1641. * Returns the list of notes entered about the commit from the refs/notes
  1642. * namespace. If the repository does not exist or is empty, an empty list is
  1643. * returned.
  1644. *
  1645. * @param repository
  1646. * @param commit
  1647. * @return list of notes
  1648. */
  1649. public static List<GitNote> getNotesOnCommit(Repository repository, RevCommit commit) {
  1650. List<GitNote> list = new ArrayList<GitNote>();
  1651. if (!hasCommits(repository)) {
  1652. return list;
  1653. }
  1654. List<RefModel> noteBranches = getNoteBranches(repository, true, -1);
  1655. for (RefModel notesRef : noteBranches) {
  1656. RevTree notesTree = JGitUtils.getCommit(repository, notesRef.getName()).getTree();
  1657. // flat notes list
  1658. String notePath = commit.getName();
  1659. String text = getStringContent(repository, notesTree, notePath);
  1660. if (!StringUtils.isEmpty(text)) {
  1661. List<RevCommit> history = getRevLog(repository, notesRef.getName(), notePath, 0, -1);
  1662. RefModel noteRef = new RefModel(notesRef.displayName, null, history.get(history
  1663. .size() - 1));
  1664. GitNote gitNote = new GitNote(noteRef, text);
  1665. list.add(gitNote);
  1666. continue;
  1667. }
  1668. // folder structure
  1669. StringBuilder sb = new StringBuilder(commit.getName());
  1670. sb.insert(2, '/');
  1671. notePath = sb.toString();
  1672. text = getStringContent(repository, notesTree, notePath);
  1673. if (!StringUtils.isEmpty(text)) {
  1674. List<RevCommit> history = getRevLog(repository, notesRef.getName(), notePath, 0, -1);
  1675. RefModel noteRef = new RefModel(notesRef.displayName, null, history.get(history
  1676. .size() - 1));
  1677. GitNote gitNote = new GitNote(noteRef, text);
  1678. list.add(gitNote);
  1679. }
  1680. }
  1681. return list;
  1682. }
  1683. /**
  1684. * this method creates an incremental revision number as a tag according to
  1685. * the amount of already existing tags, which start with a defined prefix.
  1686. *
  1687. * @param repository
  1688. * @param objectId
  1689. * @param tagger
  1690. * @param prefix
  1691. * @param intPattern
  1692. * @param message
  1693. * @return true if operation was successful, otherwise false
  1694. */
  1695. public static boolean createIncrementalRevisionTag(Repository repository,
  1696. String objectId, PersonIdent tagger, String prefix, String intPattern, String message) {
  1697. boolean result = false;
  1698. Iterator<Entry<String, Ref>> iterator = repository.getTags().entrySet().iterator();
  1699. long lastRev = 0;
  1700. while (iterator.hasNext()) {
  1701. Entry<String, Ref> entry = iterator.next();
  1702. if (entry.getKey().startsWith(prefix)) {
  1703. try {
  1704. long val = Long.parseLong(entry.getKey().substring(prefix.length()));
  1705. if (val > lastRev) {
  1706. lastRev = val;
  1707. }
  1708. } catch (Exception e) {
  1709. // this tag is NOT an incremental revision tag
  1710. }
  1711. }
  1712. }
  1713. DecimalFormat df = new DecimalFormat(intPattern);
  1714. result = createTag(repository, objectId, tagger, prefix + df.format((lastRev + 1)), message);
  1715. return result;
  1716. }
  1717. /**
  1718. * creates a tag in a repository
  1719. *
  1720. * @param repository
  1721. * @param objectId, the ref the tag points towards
  1722. * @param tagger, the person tagging the object
  1723. * @param tag, the string label
  1724. * @param message, the string message
  1725. * @return boolean, true if operation was successful, otherwise false
  1726. */
  1727. public static boolean createTag(Repository repository, String objectId, PersonIdent tagger, String tag, String message) {
  1728. try {
  1729. Git gitClient = Git.open(repository.getDirectory());
  1730. TagCommand tagCommand = gitClient.tag();
  1731. tagCommand.setTagger(tagger);
  1732. tagCommand.setMessage(message);
  1733. if (objectId != null) {
  1734. RevObject revObj = getCommit(repository, objectId);
  1735. tagCommand.setObjectId(revObj);
  1736. }
  1737. tagCommand.setName(tag);
  1738. Ref call = tagCommand.call();
  1739. return call != null ? true : false;
  1740. } catch (Exception e) {
  1741. error(e, repository, "Failed to create tag {1} in repository {0}", objectId, tag);
  1742. }
  1743. return false;
  1744. }
  1745. /**
  1746. * Create an orphaned branch in a repository.
  1747. *
  1748. * @param repository
  1749. * @param branchName
  1750. * @param author
  1751. * if unspecified, Gitblit will be the author of this new branch
  1752. * @return true if successful
  1753. */
  1754. public static boolean createOrphanBranch(Repository repository, String branchName,
  1755. PersonIdent author) {
  1756. boolean success = false;
  1757. String message = "Created branch " + branchName;
  1758. if (author == null) {
  1759. author = new PersonIdent("Gitblit", "gitblit@localhost");
  1760. }
  1761. try {
  1762. ObjectInserter odi = repository.newObjectInserter();
  1763. try {
  1764. // Create a blob object to insert into a tree
  1765. ObjectId blobId = odi.insert(Constants.OBJ_BLOB,
  1766. message.getBytes(Constants.CHARACTER_ENCODING));
  1767. // Create a tree object to reference from a commit
  1768. TreeFormatter tree = new TreeFormatter();
  1769. tree.append(".branch", FileMode.REGULAR_FILE, blobId);
  1770. ObjectId treeId = odi.insert(tree);
  1771. // Create a commit object
  1772. CommitBuilder commit = new CommitBuilder();
  1773. commit.setAuthor(author);
  1774. commit.setCommitter(author);
  1775. commit.setEncoding(Constants.CHARACTER_ENCODING);
  1776. commit.setMessage(message);
  1777. commit.setTreeId(treeId);
  1778. // Insert the commit into the repository
  1779. ObjectId commitId = odi.insert(commit);
  1780. odi.flush();
  1781. RevWalk revWalk = new RevWalk(repository);
  1782. try {
  1783. RevCommit revCommit = revWalk.parseCommit(commitId);
  1784. if (!branchName.startsWith("refs/")) {
  1785. branchName = "refs/heads/" + branchName;
  1786. }
  1787. RefUpdate ru = repository.updateRef(branchName);
  1788. ru.setNewObjectId(commitId);
  1789. ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
  1790. Result rc = ru.forceUpdate();
  1791. switch (rc) {
  1792. case NEW:
  1793. case FORCED:
  1794. case FAST_FORWARD:
  1795. success = true;
  1796. break;
  1797. default:
  1798. success = false;
  1799. }
  1800. } finally {
  1801. revWalk.release();
  1802. }
  1803. } finally {
  1804. odi.release();
  1805. }
  1806. } catch (Throwable t) {
  1807. error(t, repository, "Failed to create orphan branch {1} in repository {0}", branchName);
  1808. }
  1809. return success;
  1810. }
  1811. /**
  1812. * Reads the sparkleshare id, if present, from the repository.
  1813. *
  1814. * @param repository
  1815. * @return an id or null
  1816. */
  1817. public static String getSparkleshareId(Repository repository) {
  1818. byte[] content = getByteContent(repository, null, ".sparkleshare", false);
  1819. if (content == null) {
  1820. return null;
  1821. }
  1822. return StringUtils.decodeString(content);
  1823. }
  1824. }