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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405
  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.File;
  18. import java.io.IOException;
  19. import java.text.DecimalFormat;
  20. import java.text.MessageFormat;
  21. import java.util.ArrayList;
  22. import java.util.Arrays;
  23. import java.util.Collections;
  24. import java.util.Date;
  25. import java.util.HashMap;
  26. import java.util.Iterator;
  27. import java.util.List;
  28. import java.util.Map;
  29. import java.util.Map.Entry;
  30. import java.util.regex.Pattern;
  31. import org.apache.commons.io.filefilter.TrueFileFilter;
  32. import org.eclipse.jgit.api.CloneCommand;
  33. import org.eclipse.jgit.api.FetchCommand;
  34. import org.eclipse.jgit.api.Git;
  35. import org.eclipse.jgit.api.TagCommand;
  36. import org.eclipse.jgit.api.errors.GitAPIException;
  37. import org.eclipse.jgit.diff.DiffEntry;
  38. import org.eclipse.jgit.diff.DiffEntry.ChangeType;
  39. import org.eclipse.jgit.diff.DiffFormatter;
  40. import org.eclipse.jgit.diff.RawTextComparator;
  41. import org.eclipse.jgit.errors.ConfigInvalidException;
  42. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  43. import org.eclipse.jgit.errors.MissingObjectException;
  44. import org.eclipse.jgit.errors.StopWalkException;
  45. import org.eclipse.jgit.lib.BlobBasedConfig;
  46. import org.eclipse.jgit.lib.CommitBuilder;
  47. import org.eclipse.jgit.lib.Constants;
  48. import org.eclipse.jgit.lib.FileMode;
  49. import org.eclipse.jgit.lib.ObjectId;
  50. import org.eclipse.jgit.lib.ObjectInserter;
  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.RefUpdate;
  55. import org.eclipse.jgit.lib.RefUpdate.Result;
  56. import org.eclipse.jgit.lib.Repository;
  57. import org.eclipse.jgit.lib.RepositoryCache.FileKey;
  58. import org.eclipse.jgit.lib.StoredConfig;
  59. import org.eclipse.jgit.lib.TreeFormatter;
  60. import org.eclipse.jgit.merge.MergeStrategy;
  61. import org.eclipse.jgit.merge.RecursiveMerger;
  62. import org.eclipse.jgit.revwalk.RevBlob;
  63. import org.eclipse.jgit.revwalk.RevCommit;
  64. import org.eclipse.jgit.revwalk.RevObject;
  65. import org.eclipse.jgit.revwalk.RevSort;
  66. import org.eclipse.jgit.revwalk.RevTree;
  67. import org.eclipse.jgit.revwalk.RevWalk;
  68. import org.eclipse.jgit.revwalk.filter.CommitTimeRevFilter;
  69. import org.eclipse.jgit.revwalk.filter.RevFilter;
  70. import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
  71. import org.eclipse.jgit.transport.CredentialsProvider;
  72. import org.eclipse.jgit.transport.FetchResult;
  73. import org.eclipse.jgit.transport.RefSpec;
  74. import org.eclipse.jgit.treewalk.TreeWalk;
  75. import org.eclipse.jgit.treewalk.filter.AndTreeFilter;
  76. import org.eclipse.jgit.treewalk.filter.OrTreeFilter;
  77. import org.eclipse.jgit.treewalk.filter.PathFilter;
  78. import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
  79. import org.eclipse.jgit.treewalk.filter.PathSuffixFilter;
  80. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  81. import org.eclipse.jgit.util.FS;
  82. import org.slf4j.Logger;
  83. import org.slf4j.LoggerFactory;
  84. import com.gitblit.GitBlitException;
  85. import com.gitblit.models.GitNote;
  86. import com.gitblit.models.PathModel;
  87. import com.gitblit.models.PathModel.PathChangeModel;
  88. import com.gitblit.models.RefModel;
  89. import com.gitblit.models.SubmoduleModel;
  90. /**
  91. * Collection of static methods for retrieving information from a repository.
  92. *
  93. * @author James Moger
  94. *
  95. */
  96. public class JGitUtils {
  97. static final Logger LOGGER = LoggerFactory.getLogger(JGitUtils.class);
  98. /**
  99. * Log an error message and exception.
  100. *
  101. * @param t
  102. * @param repository
  103. * if repository is not null it MUST be the {0} parameter in the
  104. * pattern.
  105. * @param pattern
  106. * @param objects
  107. */
  108. private static void error(Throwable t, Repository repository, String pattern, Object... objects) {
  109. List<Object> parameters = new ArrayList<Object>();
  110. if (objects != null && objects.length > 0) {
  111. for (Object o : objects) {
  112. parameters.add(o);
  113. }
  114. }
  115. if (repository != null) {
  116. parameters.add(0, repository.getDirectory().getAbsolutePath());
  117. }
  118. LOGGER.error(MessageFormat.format(pattern, parameters.toArray()), t);
  119. }
  120. /**
  121. * Returns the displayable name of the person in the form "Real Name <email
  122. * address>". If the email address is empty, just "Real Name" is returned.
  123. *
  124. * @param person
  125. * @return "Real Name <email address>" or "Real Name"
  126. */
  127. public static String getDisplayName(PersonIdent person) {
  128. if (StringUtils.isEmpty(person.getEmailAddress())) {
  129. return person.getName();
  130. }
  131. final StringBuilder r = new StringBuilder();
  132. r.append(person.getName());
  133. r.append(" <");
  134. r.append(person.getEmailAddress());
  135. r.append('>');
  136. return r.toString().trim();
  137. }
  138. /**
  139. * Encapsulates the result of cloning or pulling from a repository.
  140. */
  141. public static class CloneResult {
  142. public String name;
  143. public FetchResult fetchResult;
  144. public boolean createdRepository;
  145. }
  146. /**
  147. * Clone or Fetch a repository. If the local repository does not exist,
  148. * clone is called. If the repository does exist, fetch is called. By
  149. * default the clone/fetch retrieves the remote heads, tags, and notes.
  150. *
  151. * @param repositoriesFolder
  152. * @param name
  153. * @param fromUrl
  154. * @return CloneResult
  155. * @throws Exception
  156. */
  157. public static CloneResult cloneRepository(File repositoriesFolder, String name, String fromUrl)
  158. throws Exception {
  159. return cloneRepository(repositoriesFolder, name, fromUrl, true, null);
  160. }
  161. /**
  162. * Clone or Fetch a repository. If the local repository does not exist,
  163. * clone is called. If the repository does exist, fetch is called. By
  164. * default the clone/fetch retrieves the remote heads, tags, and notes.
  165. *
  166. * @param repositoriesFolder
  167. * @param name
  168. * @param fromUrl
  169. * @param bare
  170. * @param credentialsProvider
  171. * @return CloneResult
  172. * @throws Exception
  173. */
  174. public static CloneResult cloneRepository(File repositoriesFolder, String name, String fromUrl,
  175. boolean bare, CredentialsProvider credentialsProvider) throws Exception {
  176. CloneResult result = new CloneResult();
  177. if (bare) {
  178. // bare repository, ensure .git suffix
  179. if (!name.toLowerCase().endsWith(Constants.DOT_GIT_EXT)) {
  180. name += Constants.DOT_GIT_EXT;
  181. }
  182. } else {
  183. // normal repository, strip .git suffix
  184. if (name.toLowerCase().endsWith(Constants.DOT_GIT_EXT)) {
  185. name = name.substring(0, name.indexOf(Constants.DOT_GIT_EXT));
  186. }
  187. }
  188. result.name = name;
  189. File folder = new File(repositoriesFolder, name);
  190. if (folder.exists()) {
  191. File gitDir = FileKey.resolve(new File(repositoriesFolder, name), FS.DETECTED);
  192. Repository repository = new FileRepositoryBuilder().setGitDir(gitDir).build();
  193. result.fetchResult = fetchRepository(credentialsProvider, repository);
  194. repository.close();
  195. } else {
  196. CloneCommand clone = new CloneCommand();
  197. clone.setBare(bare);
  198. clone.setCloneAllBranches(true);
  199. clone.setURI(fromUrl);
  200. clone.setDirectory(folder);
  201. if (credentialsProvider != null) {
  202. clone.setCredentialsProvider(credentialsProvider);
  203. }
  204. Repository repository = clone.call().getRepository();
  205. // Now we have to fetch because CloneCommand doesn't fetch
  206. // refs/notes nor does it allow manual RefSpec.
  207. result.createdRepository = true;
  208. result.fetchResult = fetchRepository(credentialsProvider, repository);
  209. repository.close();
  210. }
  211. return result;
  212. }
  213. /**
  214. * Fetch updates from the remote repository. If refSpecs is unspecifed,
  215. * remote heads, tags, and notes are retrieved.
  216. *
  217. * @param credentialsProvider
  218. * @param repository
  219. * @param refSpecs
  220. * @return FetchResult
  221. * @throws Exception
  222. */
  223. public static FetchResult fetchRepository(CredentialsProvider credentialsProvider,
  224. Repository repository, RefSpec... refSpecs) throws Exception {
  225. Git git = new Git(repository);
  226. FetchCommand fetch = git.fetch();
  227. List<RefSpec> specs = new ArrayList<RefSpec>();
  228. if (refSpecs == null || refSpecs.length == 0) {
  229. specs.add(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));
  230. specs.add(new RefSpec("+refs/tags/*:refs/tags/*"));
  231. specs.add(new RefSpec("+refs/notes/*:refs/notes/*"));
  232. } else {
  233. specs.addAll(Arrays.asList(refSpecs));
  234. }
  235. if (credentialsProvider != null) {
  236. fetch.setCredentialsProvider(credentialsProvider);
  237. }
  238. fetch.setRefSpecs(specs);
  239. FetchResult fetchRes = fetch.call();
  240. return fetchRes;
  241. }
  242. /**
  243. * Creates a bare repository.
  244. *
  245. * @param repositoriesFolder
  246. * @param name
  247. * @return Repository
  248. */
  249. public static Repository createRepository(File repositoriesFolder, String name) {
  250. return createRepository(repositoriesFolder, name, "FALSE");
  251. }
  252. /**
  253. * Creates a bare, shared repository.
  254. *
  255. * @param repositoriesFolder
  256. * @param name
  257. * @param shared
  258. * the setting for the --shared option of "git init".
  259. * @return Repository
  260. */
  261. public static Repository createRepository(File repositoriesFolder, String name, String shared) {
  262. try {
  263. Repository repo = null;
  264. try {
  265. Git git = Git.init().setDirectory(new File(repositoriesFolder, name)).setBare(true).call();
  266. repo = git.getRepository();
  267. } catch (GitAPIException e) {
  268. throw new RuntimeException(e);
  269. }
  270. GitConfigSharedRepository sharedRepository = new GitConfigSharedRepository(shared);
  271. if (sharedRepository.isShared()) {
  272. StoredConfig config = repo.getConfig();
  273. config.setString("core", null, "sharedRepository", sharedRepository.getValue());
  274. config.setBoolean("receive", null, "denyNonFastforwards", true);
  275. config.save();
  276. if (! JnaUtils.isWindows()) {
  277. Iterator<File> iter = org.apache.commons.io.FileUtils.iterateFilesAndDirs(repo.getDirectory(),
  278. TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
  279. // Adjust permissions on file/directory
  280. while (iter.hasNext()) {
  281. adjustSharedPerm(iter.next(), sharedRepository);
  282. }
  283. }
  284. }
  285. return repo;
  286. } catch (IOException e) {
  287. throw new RuntimeException(e);
  288. }
  289. }
  290. private enum GitConfigSharedRepositoryValue
  291. {
  292. UMASK("0", 0), FALSE("0", 0), OFF("0", 0), NO("0", 0),
  293. GROUP("1", 0660), TRUE("1", 0660), ON("1", 0660), YES("1", 0660),
  294. ALL("2", 0664), WORLD("2", 0664), EVERYBODY("2", 0664),
  295. Oxxx(null, -1);
  296. private String configValue;
  297. private int permValue;
  298. private GitConfigSharedRepositoryValue(String config, int perm) { configValue = config; permValue = perm; };
  299. public String getConfigValue() { return configValue; };
  300. public int getPerm() { return permValue; };
  301. }
  302. private static class GitConfigSharedRepository
  303. {
  304. private int intValue;
  305. private GitConfigSharedRepositoryValue enumValue;
  306. GitConfigSharedRepository(String s) {
  307. if ( s == null || s.trim().isEmpty() ) {
  308. enumValue = GitConfigSharedRepositoryValue.GROUP;
  309. }
  310. else {
  311. try {
  312. // Try one of the string values
  313. enumValue = GitConfigSharedRepositoryValue.valueOf(s.trim().toUpperCase());
  314. } catch (IllegalArgumentException iae) {
  315. try {
  316. // Try if this is an octal number
  317. int i = Integer.parseInt(s, 8);
  318. if ( (i & 0600) != 0600 ) {
  319. String msg = String.format("Problem with core.sharedRepository filemode value (0%03o).\nThe owner of files must always have read and write permissions.", i);
  320. throw new IllegalArgumentException(msg);
  321. }
  322. intValue = i & 0666;
  323. enumValue = GitConfigSharedRepositoryValue.Oxxx;
  324. } catch (NumberFormatException nfe) {
  325. throw new IllegalArgumentException("Bad configuration value for 'shared': '" + s + "'");
  326. }
  327. }
  328. }
  329. }
  330. String getValue() {
  331. if ( enumValue == GitConfigSharedRepositoryValue.Oxxx ) {
  332. if (intValue == 0) return "0";
  333. return String.format("0%o", intValue);
  334. }
  335. return enumValue.getConfigValue();
  336. }
  337. int getPerm() {
  338. if ( enumValue == GitConfigSharedRepositoryValue.Oxxx ) return intValue;
  339. return enumValue.getPerm();
  340. }
  341. boolean isCustom() {
  342. return enumValue == GitConfigSharedRepositoryValue.Oxxx;
  343. }
  344. boolean isShared() {
  345. return (enumValue.getPerm() > 0) || enumValue == GitConfigSharedRepositoryValue.Oxxx;
  346. }
  347. }
  348. /**
  349. * Adjust file permissions of a file/directory for shared repositories
  350. *
  351. * @param path
  352. * File that should get its permissions changed.
  353. * @param configShared
  354. * Configuration string value for the shared mode.
  355. * @return Upon successful completion, a value of 0 is returned. Otherwise, a value of -1 is returned.
  356. */
  357. public static int adjustSharedPerm(File path, String configShared) {
  358. return adjustSharedPerm(path, new GitConfigSharedRepository(configShared));
  359. }
  360. /**
  361. * Adjust file permissions of a file/directory for shared repositories
  362. *
  363. * @param path
  364. * File that should get its permissions changed.
  365. * @param configShared
  366. * Configuration setting for the shared mode.
  367. * @return Upon successful completion, a value of 0 is returned. Otherwise, a value of -1 is returned.
  368. */
  369. public static int adjustSharedPerm(File path, GitConfigSharedRepository configShared) {
  370. if (! configShared.isShared()) return 0;
  371. if (! path.exists()) return -1;
  372. int perm = configShared.getPerm();
  373. JnaUtils.Filestat stat = JnaUtils.getFilestat(path);
  374. if (stat == null) return -1;
  375. int mode = stat.mode;
  376. if (mode < 0) return -1;
  377. // Now, here is the kicker: Under Linux, chmod'ing a sgid file whose guid is different from the process'
  378. // effective guid will reset the sgid flag of the file. Since there is no way to get the sgid flag back in
  379. // that case, we decide to rather not touch is and getting the right permissions will have to be achieved
  380. // in a different way, e.g. by using an appropriate umask for the Gitblit process.
  381. if (System.getProperty("os.name").toLowerCase().startsWith("linux")) {
  382. if ( ((mode & (JnaUtils.S_ISGID | JnaUtils.S_ISUID)) != 0)
  383. && stat.gid != JnaUtils.getegid() ) {
  384. LOGGER.debug("Not adjusting permissions to prevent clearing suid/sgid bits for '" + path + "'" );
  385. return 0;
  386. }
  387. }
  388. // If the owner has no write access, delete it from group and other, too.
  389. if ((mode & JnaUtils.S_IWUSR) == 0) perm &= ~0222;
  390. // If the owner has execute access, set it for all blocks that have read access.
  391. if ((mode & JnaUtils.S_IXUSR) == JnaUtils.S_IXUSR) perm |= (perm & 0444) >> 2;
  392. if (configShared.isCustom()) {
  393. // Use the custom value for access permissions.
  394. mode = (mode & ~0777) | perm;
  395. }
  396. else {
  397. // Just add necessary bits to existing permissions.
  398. mode |= perm;
  399. }
  400. if (path.isDirectory()) {
  401. mode |= (mode & 0444) >> 2;
  402. mode |= JnaUtils.S_ISGID;
  403. }
  404. return JnaUtils.setFilemode(path, mode);
  405. }
  406. /**
  407. * Returns a list of repository names in the specified folder.
  408. *
  409. * @param repositoriesFolder
  410. * @param onlyBare
  411. * if true, only bare repositories repositories are listed. If
  412. * false all repositories are included.
  413. * @param searchSubfolders
  414. * recurse into subfolders to find grouped repositories
  415. * @param depth
  416. * optional recursion depth, -1 = infinite recursion
  417. * @param exclusions
  418. * list of regex exclusions for matching to folder names
  419. * @return list of repository names
  420. */
  421. public static List<String> getRepositoryList(File repositoriesFolder, boolean onlyBare,
  422. boolean searchSubfolders, int depth, List<String> exclusions) {
  423. List<String> list = new ArrayList<String>();
  424. if (repositoriesFolder == null || !repositoriesFolder.exists()) {
  425. return list;
  426. }
  427. List<Pattern> patterns = new ArrayList<Pattern>();
  428. if (!ArrayUtils.isEmpty(exclusions)) {
  429. for (String regex : exclusions) {
  430. patterns.add(Pattern.compile(regex));
  431. }
  432. }
  433. list.addAll(getRepositoryList(repositoriesFolder.getAbsolutePath(), repositoriesFolder,
  434. onlyBare, searchSubfolders, depth, patterns));
  435. StringUtils.sortRepositorynames(list);
  436. list.remove(".git"); // issue-256
  437. return list;
  438. }
  439. /**
  440. * Recursive function to find git repositories.
  441. *
  442. * @param basePath
  443. * basePath is stripped from the repository name as repositories
  444. * are relative to this path
  445. * @param searchFolder
  446. * @param onlyBare
  447. * if true only bare repositories will be listed. if false all
  448. * repositories are included.
  449. * @param searchSubfolders
  450. * recurse into subfolders to find grouped repositories
  451. * @param depth
  452. * recursion depth, -1 = infinite recursion
  453. * @param patterns
  454. * list of regex patterns for matching to folder names
  455. * @return
  456. */
  457. private static List<String> getRepositoryList(String basePath, File searchFolder,
  458. boolean onlyBare, boolean searchSubfolders, int depth, List<Pattern> patterns) {
  459. File baseFile = new File(basePath);
  460. List<String> list = new ArrayList<String>();
  461. if (depth == 0) {
  462. return list;
  463. }
  464. int nextDepth = (depth == -1) ? -1 : depth - 1;
  465. for (File file : searchFolder.listFiles()) {
  466. if (file.isDirectory()) {
  467. boolean exclude = false;
  468. for (Pattern pattern : patterns) {
  469. String path = FileUtils.getRelativePath(baseFile, file).replace('\\', '/');
  470. if (pattern.matcher(path).matches()) {
  471. LOGGER.debug(MessageFormat.format("excluding {0} because of rule {1}", path, pattern.pattern()));
  472. exclude = true;
  473. break;
  474. }
  475. }
  476. if (exclude) {
  477. // skip to next file
  478. continue;
  479. }
  480. File gitDir = FileKey.resolve(new File(searchFolder, file.getName()), FS.DETECTED);
  481. if (gitDir != null) {
  482. if (onlyBare && gitDir.getName().equals(".git")) {
  483. continue;
  484. }
  485. if (gitDir.equals(file) || gitDir.getParentFile().equals(file)) {
  486. // determine repository name relative to base path
  487. String repository = FileUtils.getRelativePath(baseFile, file);
  488. list.add(repository);
  489. } else if (searchSubfolders && file.canRead()) {
  490. // look for repositories in subfolders
  491. list.addAll(getRepositoryList(basePath, file, onlyBare, searchSubfolders,
  492. nextDepth, patterns));
  493. }
  494. } else if (searchSubfolders && file.canRead()) {
  495. // look for repositories in subfolders
  496. list.addAll(getRepositoryList(basePath, file, onlyBare, searchSubfolders,
  497. nextDepth, patterns));
  498. }
  499. }
  500. }
  501. return list;
  502. }
  503. /**
  504. * Returns the first commit on a branch. If the repository does not exist or
  505. * is empty, null is returned.
  506. *
  507. * @param repository
  508. * @param branch
  509. * if unspecified, HEAD is assumed.
  510. * @return RevCommit
  511. */
  512. public static RevCommit getFirstCommit(Repository repository, String branch) {
  513. if (!hasCommits(repository)) {
  514. return null;
  515. }
  516. RevCommit commit = null;
  517. try {
  518. // resolve branch
  519. ObjectId branchObject;
  520. if (StringUtils.isEmpty(branch)) {
  521. branchObject = getDefaultBranch(repository);
  522. } else {
  523. branchObject = repository.resolve(branch);
  524. }
  525. RevWalk walk = new RevWalk(repository);
  526. walk.sort(RevSort.REVERSE);
  527. RevCommit head = walk.parseCommit(branchObject);
  528. walk.markStart(head);
  529. commit = walk.next();
  530. walk.dispose();
  531. } catch (Throwable t) {
  532. error(t, repository, "{0} failed to determine first commit");
  533. }
  534. return commit;
  535. }
  536. /**
  537. * Returns the date of the first commit on a branch. If the repository does
  538. * not exist, Date(0) is returned. If the repository does exist bit is
  539. * empty, the last modified date of the repository folder is returned.
  540. *
  541. * @param repository
  542. * @param branch
  543. * if unspecified, HEAD is assumed.
  544. * @return Date of the first commit on a branch
  545. */
  546. public static Date getFirstChange(Repository repository, String branch) {
  547. RevCommit commit = getFirstCommit(repository, branch);
  548. if (commit == null) {
  549. if (repository == null || !repository.getDirectory().exists()) {
  550. return new Date(0);
  551. }
  552. // fresh repository
  553. return new Date(repository.getDirectory().lastModified());
  554. }
  555. return getCommitDate(commit);
  556. }
  557. /**
  558. * Determine if a repository has any commits. This is determined by checking
  559. * the for loose and packed objects.
  560. *
  561. * @param repository
  562. * @return true if the repository has commits
  563. */
  564. public static boolean hasCommits(Repository repository) {
  565. if (repository != null && repository.getDirectory().exists()) {
  566. return (new File(repository.getDirectory(), "objects").list().length > 2)
  567. || (new File(repository.getDirectory(), "objects/pack").list().length > 0);
  568. }
  569. return false;
  570. }
  571. /**
  572. * Encapsulates the result of cloning or pulling from a repository.
  573. */
  574. public static class LastChange {
  575. public Date when;
  576. public String who;
  577. LastChange() {
  578. when = new Date(0);
  579. }
  580. LastChange(long lastModified) {
  581. this.when = new Date(lastModified);
  582. }
  583. }
  584. /**
  585. * Returns the date and author of the most recent commit on a branch. If the
  586. * repository does not exist Date(0) is returned. If it does exist but is
  587. * empty, the last modified date of the repository folder is returned.
  588. *
  589. * @param repository
  590. * @return a LastChange object
  591. */
  592. public static LastChange getLastChange(Repository repository) {
  593. if (!hasCommits(repository)) {
  594. // null repository
  595. if (repository == null) {
  596. return new LastChange();
  597. }
  598. // fresh repository
  599. return new LastChange(repository.getDirectory().lastModified());
  600. }
  601. List<RefModel> branchModels = getLocalBranches(repository, true, -1);
  602. if (branchModels.size() > 0) {
  603. // find most recent branch update
  604. LastChange lastChange = new LastChange();
  605. for (RefModel branchModel : branchModels) {
  606. if (branchModel.getDate().after(lastChange.when)) {
  607. lastChange.when = branchModel.getDate();
  608. lastChange.who = branchModel.getAuthorIdent().getName();
  609. }
  610. }
  611. return lastChange;
  612. }
  613. // default to the repository folder modification date
  614. return new LastChange(repository.getDirectory().lastModified());
  615. }
  616. /**
  617. * Retrieves a Java Date from a Git commit.
  618. *
  619. * @param commit
  620. * @return date of the commit or Date(0) if the commit is null
  621. */
  622. public static Date getCommitDate(RevCommit commit) {
  623. if (commit == null) {
  624. return new Date(0);
  625. }
  626. return new Date(commit.getCommitTime() * 1000L);
  627. }
  628. /**
  629. * Retrieves a Java Date from a Git commit.
  630. *
  631. * @param commit
  632. * @return date of the commit or Date(0) if the commit is null
  633. */
  634. public static Date getAuthorDate(RevCommit commit) {
  635. if (commit == null) {
  636. return new Date(0);
  637. }
  638. return commit.getAuthorIdent().getWhen();
  639. }
  640. /**
  641. * Returns the specified commit from the repository. If the repository does
  642. * not exist or is empty, null is returned.
  643. *
  644. * @param repository
  645. * @param objectId
  646. * if unspecified, HEAD is assumed.
  647. * @return RevCommit
  648. */
  649. public static RevCommit getCommit(Repository repository, String objectId) {
  650. if (!hasCommits(repository)) {
  651. return null;
  652. }
  653. RevCommit commit = null;
  654. RevWalk walk = null;
  655. try {
  656. // resolve object id
  657. ObjectId branchObject;
  658. if (StringUtils.isEmpty(objectId) || "HEAD".equalsIgnoreCase(objectId)) {
  659. branchObject = getDefaultBranch(repository);
  660. } else {
  661. branchObject = repository.resolve(objectId);
  662. }
  663. if (branchObject == null) {
  664. return null;
  665. }
  666. walk = new RevWalk(repository);
  667. RevCommit rev = walk.parseCommit(branchObject);
  668. commit = rev;
  669. } catch (Throwable t) {
  670. error(t, repository, "{0} failed to get commit {1}", objectId);
  671. } finally {
  672. if (walk != null) {
  673. walk.dispose();
  674. }
  675. }
  676. return commit;
  677. }
  678. /**
  679. * Retrieves the raw byte content of a file in the specified tree.
  680. *
  681. * @param repository
  682. * @param tree
  683. * if null, the RevTree from HEAD is assumed.
  684. * @param path
  685. * @return content as a byte []
  686. */
  687. public static byte[] getByteContent(Repository repository, RevTree tree, final String path, boolean throwError) {
  688. RevWalk rw = new RevWalk(repository);
  689. TreeWalk tw = new TreeWalk(repository);
  690. tw.setFilter(PathFilterGroup.createFromStrings(Collections.singleton(path)));
  691. byte[] content = null;
  692. try {
  693. if (tree == null) {
  694. ObjectId object = getDefaultBranch(repository);
  695. if (object == null)
  696. return null;
  697. RevCommit commit = rw.parseCommit(object);
  698. tree = commit.getTree();
  699. }
  700. tw.reset(tree);
  701. while (tw.next()) {
  702. if (tw.isSubtree() && !path.equals(tw.getPathString())) {
  703. tw.enterSubtree();
  704. continue;
  705. }
  706. ObjectId entid = tw.getObjectId(0);
  707. FileMode entmode = tw.getFileMode(0);
  708. if (entmode != FileMode.GITLINK) {
  709. ObjectLoader ldr = repository.open(entid, Constants.OBJ_BLOB);
  710. content = ldr.getCachedBytes();
  711. }
  712. }
  713. } catch (Throwable t) {
  714. if (throwError) {
  715. error(t, repository, "{0} can't find {1} in tree {2}", path, tree.name());
  716. }
  717. } finally {
  718. rw.dispose();
  719. tw.release();
  720. }
  721. return content;
  722. }
  723. /**
  724. * Returns the UTF-8 string content of a file in the specified tree.
  725. *
  726. * @param repository
  727. * @param tree
  728. * if null, the RevTree from HEAD is assumed.
  729. * @param blobPath
  730. * @param charsets optional
  731. * @return UTF-8 string content
  732. */
  733. public static String getStringContent(Repository repository, RevTree tree, String blobPath, String... charsets) {
  734. byte[] content = getByteContent(repository, tree, blobPath, true);
  735. if (content == null) {
  736. return null;
  737. }
  738. return StringUtils.decodeString(content, charsets);
  739. }
  740. /**
  741. * Gets the raw byte content of the specified blob object.
  742. *
  743. * @param repository
  744. * @param objectId
  745. * @return byte [] blob content
  746. */
  747. public static byte[] getByteContent(Repository repository, String objectId) {
  748. RevWalk rw = new RevWalk(repository);
  749. byte[] content = null;
  750. try {
  751. RevBlob blob = rw.lookupBlob(ObjectId.fromString(objectId));
  752. ObjectLoader ldr = repository.open(blob.getId(), Constants.OBJ_BLOB);
  753. content = ldr.getCachedBytes();
  754. } catch (Throwable t) {
  755. error(t, repository, "{0} can't find blob {1}", objectId);
  756. } finally {
  757. rw.dispose();
  758. }
  759. return content;
  760. }
  761. /**
  762. * Gets the UTF-8 string content of the blob specified by objectId.
  763. *
  764. * @param repository
  765. * @param objectId
  766. * @param charsets optional
  767. * @return UTF-8 string content
  768. */
  769. public static String getStringContent(Repository repository, String objectId, String... charsets) {
  770. byte[] content = getByteContent(repository, objectId);
  771. if (content == null) {
  772. return null;
  773. }
  774. return StringUtils.decodeString(content, charsets);
  775. }
  776. /**
  777. * Returns the list of files in the specified folder at the specified
  778. * commit. If the repository does not exist or is empty, an empty list is
  779. * returned.
  780. *
  781. * @param repository
  782. * @param path
  783. * if unspecified, root folder is assumed.
  784. * @param commit
  785. * if null, HEAD is assumed.
  786. * @return list of files in specified path
  787. */
  788. public static List<PathModel> getFilesInPath(Repository repository, String path,
  789. RevCommit commit) {
  790. List<PathModel> list = new ArrayList<PathModel>();
  791. if (!hasCommits(repository)) {
  792. return list;
  793. }
  794. if (commit == null) {
  795. commit = getCommit(repository, null);
  796. }
  797. final TreeWalk tw = new TreeWalk(repository);
  798. try {
  799. tw.addTree(commit.getTree());
  800. if (!StringUtils.isEmpty(path)) {
  801. PathFilter f = PathFilter.create(path);
  802. tw.setFilter(f);
  803. tw.setRecursive(false);
  804. boolean foundFolder = false;
  805. while (tw.next()) {
  806. if (!foundFolder && tw.isSubtree()) {
  807. tw.enterSubtree();
  808. }
  809. if (tw.getPathString().equals(path)) {
  810. foundFolder = true;
  811. continue;
  812. }
  813. if (foundFolder) {
  814. list.add(getPathModel(tw, path, commit));
  815. }
  816. }
  817. } else {
  818. tw.setRecursive(false);
  819. while (tw.next()) {
  820. list.add(getPathModel(tw, null, commit));
  821. }
  822. }
  823. } catch (IOException e) {
  824. error(e, repository, "{0} failed to get files for commit {1}", commit.getName());
  825. } finally {
  826. tw.release();
  827. }
  828. Collections.sort(list);
  829. return list;
  830. }
  831. /**
  832. * Returns the list of files changed in a specified commit. If the
  833. * repository does not exist or is empty, an empty list is returned.
  834. *
  835. * @param repository
  836. * @param commit
  837. * if null, HEAD is assumed.
  838. * @return list of files changed in a commit
  839. */
  840. public static List<PathChangeModel> getFilesInCommit(Repository repository, RevCommit commit) {
  841. return getFilesInCommit(repository, commit, true);
  842. }
  843. /**
  844. * Returns the list of files changed in a specified commit. If the
  845. * repository does not exist or is empty, an empty list is returned.
  846. *
  847. * @param repository
  848. * @param commit
  849. * if null, HEAD is assumed.
  850. * @param calculateDiffStat
  851. * if true, each PathChangeModel will have insertions/deletions
  852. * @return list of files changed in a commit
  853. */
  854. public static List<PathChangeModel> getFilesInCommit(Repository repository, RevCommit commit, boolean calculateDiffStat) {
  855. List<PathChangeModel> list = new ArrayList<PathChangeModel>();
  856. if (!hasCommits(repository)) {
  857. return list;
  858. }
  859. RevWalk rw = new RevWalk(repository);
  860. try {
  861. if (commit == null) {
  862. ObjectId object = getDefaultBranch(repository);
  863. commit = rw.parseCommit(object);
  864. }
  865. if (commit.getParentCount() == 0) {
  866. TreeWalk tw = new TreeWalk(repository);
  867. tw.reset();
  868. tw.setRecursive(true);
  869. tw.addTree(commit.getTree());
  870. while (tw.next()) {
  871. list.add(new PathChangeModel(tw.getPathString(), tw.getPathString(), 0, tw
  872. .getRawMode(0), tw.getObjectId(0).getName(), commit.getId().getName(),
  873. ChangeType.ADD));
  874. }
  875. tw.release();
  876. } else {
  877. RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
  878. DiffStatFormatter df = new DiffStatFormatter(commit.getName());
  879. df.setRepository(repository);
  880. df.setDiffComparator(RawTextComparator.DEFAULT);
  881. df.setDetectRenames(true);
  882. List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree());
  883. for (DiffEntry diff : diffs) {
  884. // create the path change model
  885. PathChangeModel pcm = PathChangeModel.from(diff, commit.getName());
  886. if (calculateDiffStat) {
  887. // update file diffstats
  888. df.format(diff);
  889. PathChangeModel pathStat = df.getDiffStat().getPath(pcm.path);
  890. if (pathStat != null) {
  891. pcm.insertions = pathStat.insertions;
  892. pcm.deletions = pathStat.deletions;
  893. }
  894. }
  895. list.add(pcm);
  896. }
  897. }
  898. } catch (Throwable t) {
  899. error(t, repository, "{0} failed to determine files in commit!");
  900. } finally {
  901. rw.dispose();
  902. }
  903. return list;
  904. }
  905. /**
  906. * Returns the list of files changed in a specified commit. If the
  907. * repository does not exist or is empty, an empty list is returned.
  908. *
  909. * @param repository
  910. * @param startCommit
  911. * earliest commit
  912. * @param endCommit
  913. * most recent commit. if null, HEAD is assumed.
  914. * @return list of files changed in a commit range
  915. */
  916. public static List<PathChangeModel> getFilesInRange(Repository repository, String startCommit, String endCommit) {
  917. List<PathChangeModel> list = new ArrayList<PathChangeModel>();
  918. if (!hasCommits(repository)) {
  919. return list;
  920. }
  921. try {
  922. ObjectId startRange = repository.resolve(startCommit);
  923. ObjectId endRange = repository.resolve(endCommit);
  924. RevWalk rw = new RevWalk(repository);
  925. RevCommit start = rw.parseCommit(startRange);
  926. RevCommit end = rw.parseCommit(endRange);
  927. list.addAll(getFilesInRange(repository, start, end));
  928. rw.release();
  929. } catch (Throwable t) {
  930. error(t, repository, "{0} failed to determine files in range {1}..{2}!", startCommit, endCommit);
  931. }
  932. return list;
  933. }
  934. /**
  935. * Returns the list of files changed in a specified commit. If the
  936. * repository does not exist or is empty, an empty list is returned.
  937. *
  938. * @param repository
  939. * @param startCommit
  940. * earliest commit
  941. * @param endCommit
  942. * most recent commit. if null, HEAD is assumed.
  943. * @return list of files changed in a commit range
  944. */
  945. public static List<PathChangeModel> getFilesInRange(Repository repository, RevCommit startCommit, RevCommit endCommit) {
  946. List<PathChangeModel> list = new ArrayList<PathChangeModel>();
  947. if (!hasCommits(repository)) {
  948. return list;
  949. }
  950. try {
  951. DiffFormatter df = new DiffFormatter(null);
  952. df.setRepository(repository);
  953. df.setDiffComparator(RawTextComparator.DEFAULT);
  954. df.setDetectRenames(true);
  955. List<DiffEntry> diffEntries = df.scan(startCommit.getTree(), endCommit.getTree());
  956. for (DiffEntry diff : diffEntries) {
  957. PathChangeModel pcm = PathChangeModel.from(diff, endCommit.getName());
  958. list.add(pcm);
  959. }
  960. Collections.sort(list);
  961. } catch (Throwable t) {
  962. error(t, repository, "{0} failed to determine files in range {1}..{2}!", startCommit, endCommit);
  963. }
  964. return list;
  965. }
  966. /**
  967. * Returns the list of files in the repository on the default branch that
  968. * match one of the specified extensions. This is a CASE-SENSITIVE search.
  969. * If the repository does not exist or is empty, an empty list is returned.
  970. *
  971. * @param repository
  972. * @param extensions
  973. * @return list of files in repository with a matching extension
  974. */
  975. public static List<PathModel> getDocuments(Repository repository, List<String> extensions) {
  976. return getDocuments(repository, extensions, null);
  977. }
  978. /**
  979. * Returns the list of files in the repository in the specified commit that
  980. * match one of the specified extensions. This is a CASE-SENSITIVE search.
  981. * If the repository does not exist or is empty, an empty list is returned.
  982. *
  983. * @param repository
  984. * @param extensions
  985. * @param objectId
  986. * @return list of files in repository with a matching extension
  987. */
  988. public static List<PathModel> getDocuments(Repository repository, List<String> extensions,
  989. String objectId) {
  990. List<PathModel> list = new ArrayList<PathModel>();
  991. if (!hasCommits(repository)) {
  992. return list;
  993. }
  994. RevCommit commit = getCommit(repository, objectId);
  995. final TreeWalk tw = new TreeWalk(repository);
  996. try {
  997. tw.addTree(commit.getTree());
  998. if (extensions != null && extensions.size() > 0) {
  999. List<TreeFilter> suffixFilters = new ArrayList<TreeFilter>();
  1000. for (String extension : extensions) {
  1001. if (extension.charAt(0) == '.') {
  1002. suffixFilters.add(PathSuffixFilter.create(extension));
  1003. } else {
  1004. // escape the . since this is a regexp filter
  1005. suffixFilters.add(PathSuffixFilter.create("." + extension));
  1006. }
  1007. }
  1008. TreeFilter filter;
  1009. if (suffixFilters.size() == 1) {
  1010. filter = suffixFilters.get(0);
  1011. } else {
  1012. filter = OrTreeFilter.create(suffixFilters);
  1013. }
  1014. tw.setFilter(filter);
  1015. tw.setRecursive(true);
  1016. }
  1017. while (tw.next()) {
  1018. list.add(getPathModel(tw, null, commit));
  1019. }
  1020. } catch (IOException e) {
  1021. error(e, repository, "{0} failed to get documents for commit {1}", commit.getName());
  1022. } finally {
  1023. tw.release();
  1024. }
  1025. Collections.sort(list);
  1026. return list;
  1027. }
  1028. /**
  1029. * Returns a path model of the current file in the treewalk.
  1030. *
  1031. * @param tw
  1032. * @param basePath
  1033. * @param commit
  1034. * @return a path model of the current file in the treewalk
  1035. */
  1036. private static PathModel getPathModel(TreeWalk tw, String basePath, RevCommit commit) {
  1037. String name;
  1038. long size = 0;
  1039. if (StringUtils.isEmpty(basePath)) {
  1040. name = tw.getPathString();
  1041. } else {
  1042. name = tw.getPathString().substring(basePath.length() + 1);
  1043. }
  1044. ObjectId objectId = tw.getObjectId(0);
  1045. try {
  1046. if (!tw.isSubtree() && (tw.getFileMode(0) != FileMode.GITLINK)) {
  1047. size = tw.getObjectReader().getObjectSize(objectId, Constants.OBJ_BLOB);
  1048. }
  1049. } catch (Throwable t) {
  1050. error(t, null, "failed to retrieve blob size for " + tw.getPathString());
  1051. }
  1052. return new PathModel(name, tw.getPathString(), size, tw.getFileMode(0).getBits(),
  1053. objectId.getName(), commit.getName());
  1054. }
  1055. /**
  1056. * Returns a permissions representation of the mode bits.
  1057. *
  1058. * @param mode
  1059. * @return string representation of the mode bits
  1060. */
  1061. public static String getPermissionsFromMode(int mode) {
  1062. if (FileMode.TREE.equals(mode)) {
  1063. return "drwxr-xr-x";
  1064. } else if (FileMode.REGULAR_FILE.equals(mode)) {
  1065. return "-rw-r--r--";
  1066. } else if (FileMode.EXECUTABLE_FILE.equals(mode)) {
  1067. return "-rwxr-xr-x";
  1068. } else if (FileMode.SYMLINK.equals(mode)) {
  1069. return "symlink";
  1070. } else if (FileMode.GITLINK.equals(mode)) {
  1071. return "submodule";
  1072. }
  1073. return "missing";
  1074. }
  1075. /**
  1076. * Returns a list of commits since the minimum date starting from the
  1077. * specified object id.
  1078. *
  1079. * @param repository
  1080. * @param objectId
  1081. * if unspecified, HEAD is assumed.
  1082. * @param minimumDate
  1083. * @return list of commits
  1084. */
  1085. public static List<RevCommit> getRevLog(Repository repository, String objectId, Date minimumDate) {
  1086. List<RevCommit> list = new ArrayList<RevCommit>();
  1087. if (!hasCommits(repository)) {
  1088. return list;
  1089. }
  1090. try {
  1091. // resolve branch
  1092. ObjectId branchObject;
  1093. if (StringUtils.isEmpty(objectId)) {
  1094. branchObject = getDefaultBranch(repository);
  1095. } else {
  1096. branchObject = repository.resolve(objectId);
  1097. }
  1098. RevWalk rw = new RevWalk(repository);
  1099. rw.markStart(rw.parseCommit(branchObject));
  1100. rw.setRevFilter(CommitTimeRevFilter.after(minimumDate));
  1101. Iterable<RevCommit> revlog = rw;
  1102. for (RevCommit rev : revlog) {
  1103. list.add(rev);
  1104. }
  1105. rw.dispose();
  1106. } catch (Throwable t) {
  1107. error(t, repository, "{0} failed to get {1} revlog for minimum date {2}", objectId,
  1108. minimumDate);
  1109. }
  1110. return list;
  1111. }
  1112. /**
  1113. * Returns a list of commits starting from HEAD and working backwards.
  1114. *
  1115. * @param repository
  1116. * @param maxCount
  1117. * if < 0, all commits for the repository are returned.
  1118. * @return list of commits
  1119. */
  1120. public static List<RevCommit> getRevLog(Repository repository, int maxCount) {
  1121. return getRevLog(repository, null, 0, maxCount);
  1122. }
  1123. /**
  1124. * Returns a list of commits starting from the specified objectId using an
  1125. * offset and maxCount for paging. This is similar to LIMIT n OFFSET p in
  1126. * SQL. If the repository does not exist or is empty, an empty list is
  1127. * returned.
  1128. *
  1129. * @param repository
  1130. * @param objectId
  1131. * if unspecified, HEAD is assumed.
  1132. * @param offset
  1133. * @param maxCount
  1134. * if < 0, all commits are returned.
  1135. * @return a paged list of commits
  1136. */
  1137. public static List<RevCommit> getRevLog(Repository repository, String objectId, int offset,
  1138. int maxCount) {
  1139. return getRevLog(repository, objectId, null, offset, maxCount);
  1140. }
  1141. /**
  1142. * Returns a list of commits for the repository or a path within the
  1143. * repository. Caller may specify ending revision with objectId. Caller may
  1144. * specify offset and maxCount to achieve pagination of results. If the
  1145. * repository does not exist or is empty, an empty list is returned.
  1146. *
  1147. * @param repository
  1148. * @param objectId
  1149. * if unspecified, HEAD is assumed.
  1150. * @param path
  1151. * if unspecified, commits for repository are returned. If
  1152. * specified, commits for the path are returned.
  1153. * @param offset
  1154. * @param maxCount
  1155. * if < 0, all commits are returned.
  1156. * @return a paged list of commits
  1157. */
  1158. public static List<RevCommit> getRevLog(Repository repository, String objectId, String path,
  1159. int offset, int maxCount) {
  1160. List<RevCommit> list = new ArrayList<RevCommit>();
  1161. if (maxCount == 0) {
  1162. return list;
  1163. }
  1164. if (!hasCommits(repository)) {
  1165. return list;
  1166. }
  1167. try {
  1168. // resolve branch
  1169. ObjectId startRange = null;
  1170. ObjectId endRange;
  1171. if (StringUtils.isEmpty(objectId)) {
  1172. endRange = getDefaultBranch(repository);
  1173. } else {
  1174. if( objectId.contains("..") ) {
  1175. // range expression
  1176. String[] parts = objectId.split("\\.\\.");
  1177. startRange = repository.resolve(parts[0]);
  1178. endRange = repository.resolve(parts[1]);
  1179. } else {
  1180. // objectid
  1181. endRange= repository.resolve(objectId);
  1182. }
  1183. }
  1184. if (endRange == null) {
  1185. return list;
  1186. }
  1187. RevWalk rw = new RevWalk(repository);
  1188. rw.markStart(rw.parseCommit(endRange));
  1189. if (startRange != null) {
  1190. rw.markUninteresting(rw.parseCommit(startRange));
  1191. }
  1192. if (!StringUtils.isEmpty(path)) {
  1193. TreeFilter filter = AndTreeFilter.create(
  1194. PathFilterGroup.createFromStrings(Collections.singleton(path)),
  1195. TreeFilter.ANY_DIFF);
  1196. rw.setTreeFilter(filter);
  1197. }
  1198. Iterable<RevCommit> revlog = rw;
  1199. if (offset > 0) {
  1200. int count = 0;
  1201. for (RevCommit rev : revlog) {
  1202. count++;
  1203. if (count > offset) {
  1204. list.add(rev);
  1205. if (maxCount > 0 && list.size() == maxCount) {
  1206. break;
  1207. }
  1208. }
  1209. }
  1210. } else {
  1211. for (RevCommit rev : revlog) {
  1212. list.add(rev);
  1213. if (maxCount > 0 && list.size() == maxCount) {
  1214. break;
  1215. }
  1216. }
  1217. }
  1218. rw.dispose();
  1219. } catch (Throwable t) {
  1220. error(t, repository, "{0} failed to get {1} revlog for path {2}", objectId, path);
  1221. }
  1222. return list;
  1223. }
  1224. /**
  1225. * Returns a list of commits for the repository within the range specified
  1226. * by startRangeId and endRangeId. If the repository does not exist or is
  1227. * empty, an empty list is returned.
  1228. *
  1229. * @param repository
  1230. * @param startRangeId
  1231. * the first commit (not included in results)
  1232. * @param endRangeId
  1233. * the end commit (included in results)
  1234. * @return a list of commits
  1235. */
  1236. public static List<RevCommit> getRevLog(Repository repository, String startRangeId,
  1237. String endRangeId) {
  1238. List<RevCommit> list = new ArrayList<RevCommit>();
  1239. if (!hasCommits(repository)) {
  1240. return list;
  1241. }
  1242. try {
  1243. ObjectId endRange = repository.resolve(endRangeId);
  1244. ObjectId startRange = repository.resolve(startRangeId);
  1245. RevWalk rw = new RevWalk(repository);
  1246. rw.markStart(rw.parseCommit(endRange));
  1247. if (startRange.equals(ObjectId.zeroId())) {
  1248. // maybe this is a tag or an orphan branch
  1249. list.add(rw.parseCommit(endRange));
  1250. rw.dispose();
  1251. return list;
  1252. } else {
  1253. rw.markUninteresting(rw.parseCommit(startRange));
  1254. }
  1255. Iterable<RevCommit> revlog = rw;
  1256. for (RevCommit rev : revlog) {
  1257. list.add(rev);
  1258. }
  1259. rw.dispose();
  1260. } catch (Throwable t) {
  1261. error(t, repository, "{0} failed to get revlog for {1}..{2}", startRangeId, endRangeId);
  1262. }
  1263. return list;
  1264. }
  1265. /**
  1266. * Search the commit history for a case-insensitive match to the value.
  1267. * Search results require a specified SearchType of AUTHOR, COMMITTER, or
  1268. * COMMIT. Results may be paginated using offset and maxCount. If the
  1269. * repository does not exist or is empty, an empty list is returned.
  1270. *
  1271. * @param repository
  1272. * @param objectId
  1273. * if unspecified, HEAD is assumed.
  1274. * @param value
  1275. * @param type
  1276. * AUTHOR, COMMITTER, COMMIT
  1277. * @param offset
  1278. * @param maxCount
  1279. * if < 0, all matches are returned
  1280. * @return matching list of commits
  1281. */
  1282. public static List<RevCommit> searchRevlogs(Repository repository, String objectId,
  1283. String value, final com.gitblit.Constants.SearchType type, int offset, int maxCount) {
  1284. List<RevCommit> list = new ArrayList<RevCommit>();
  1285. if (StringUtils.isEmpty(value)) {
  1286. return list;
  1287. }
  1288. if (maxCount == 0) {
  1289. return list;
  1290. }
  1291. if (!hasCommits(repository)) {
  1292. return list;
  1293. }
  1294. final String lcValue = value.toLowerCase();
  1295. try {
  1296. // resolve branch
  1297. ObjectId branchObject;
  1298. if (StringUtils.isEmpty(objectId)) {
  1299. branchObject = getDefaultBranch(repository);
  1300. } else {
  1301. branchObject = repository.resolve(objectId);
  1302. }
  1303. RevWalk rw = new RevWalk(repository);
  1304. rw.setRevFilter(new RevFilter() {
  1305. @Override
  1306. public RevFilter clone() {
  1307. // FindBugs complains about this method name.
  1308. // This is part of JGit design and unrelated to Cloneable.
  1309. return this;
  1310. }
  1311. @Override
  1312. public boolean include(RevWalk walker, RevCommit commit) throws StopWalkException,
  1313. MissingObjectException, IncorrectObjectTypeException, IOException {
  1314. boolean include = false;
  1315. switch (type) {
  1316. case AUTHOR:
  1317. include = (commit.getAuthorIdent().getName().toLowerCase().indexOf(lcValue) > -1)
  1318. || (commit.getAuthorIdent().getEmailAddress().toLowerCase()
  1319. .indexOf(lcValue) > -1);
  1320. break;
  1321. case COMMITTER:
  1322. include = (commit.getCommitterIdent().getName().toLowerCase()
  1323. .indexOf(lcValue) > -1)
  1324. || (commit.getCommitterIdent().getEmailAddress().toLowerCase()
  1325. .indexOf(lcValue) > -1);
  1326. break;
  1327. case COMMIT:
  1328. include = commit.getFullMessage().toLowerCase().indexOf(lcValue) > -1;
  1329. break;
  1330. }
  1331. return include;
  1332. }
  1333. });
  1334. rw.markStart(rw.parseCommit(branchObject));
  1335. Iterable<RevCommit> revlog = rw;
  1336. if (offset > 0) {
  1337. int count = 0;
  1338. for (RevCommit rev : revlog) {
  1339. count++;
  1340. if (count > offset) {
  1341. list.add(rev);
  1342. if (maxCount > 0 && list.size() == maxCount) {
  1343. break;
  1344. }
  1345. }
  1346. }
  1347. } else {
  1348. for (RevCommit rev : revlog) {
  1349. list.add(rev);
  1350. if (maxCount > 0 && list.size() == maxCount) {
  1351. break;
  1352. }
  1353. }
  1354. }
  1355. rw.dispose();
  1356. } catch (Throwable t) {
  1357. error(t, repository, "{0} failed to {1} search revlogs for {2}", type.name(), value);
  1358. }
  1359. return list;
  1360. }
  1361. /**
  1362. * Returns the default branch to use for a repository. Normally returns
  1363. * whatever branch HEAD points to, but if HEAD points to nothing it returns
  1364. * the most recently updated branch.
  1365. *
  1366. * @param repository
  1367. * @return the objectid of a branch
  1368. * @throws Exception
  1369. */
  1370. public static ObjectId getDefaultBranch(Repository repository) throws Exception {
  1371. ObjectId object = repository.resolve(Constants.HEAD);
  1372. if (object == null) {
  1373. // no HEAD
  1374. // perhaps non-standard repository, try local branches
  1375. List<RefModel> branchModels = getLocalBranches(repository, true, -1);
  1376. if (branchModels.size() > 0) {
  1377. // use most recently updated branch
  1378. RefModel branch = null;
  1379. Date lastDate = new Date(0);
  1380. for (RefModel branchModel : branchModels) {
  1381. if (branchModel.getDate().after(lastDate)) {
  1382. branch = branchModel;
  1383. lastDate = branch.getDate();
  1384. }
  1385. }
  1386. object = branch.getReferencedObjectId();
  1387. }
  1388. }
  1389. return object;
  1390. }
  1391. /**
  1392. * Returns the target of the symbolic HEAD reference for a repository.
  1393. * Normally returns a branch reference name, but when HEAD is detached,
  1394. * the commit is matched against the known tags. The most recent matching
  1395. * tag ref name will be returned if it references the HEAD commit. If
  1396. * no match is found, the SHA1 is returned.
  1397. *
  1398. * @param repository
  1399. * @return the ref name or the SHA1 for a detached HEAD
  1400. */
  1401. public static String getHEADRef(Repository repository) {
  1402. String target = null;
  1403. try {
  1404. target = repository.getFullBranch();
  1405. } catch (Throwable t) {
  1406. error(t, repository, "{0} failed to get symbolic HEAD target");
  1407. }
  1408. return target;
  1409. }
  1410. /**
  1411. * Sets the symbolic ref HEAD to the specified target ref. The
  1412. * HEAD will be detached if the target ref is not a branch.
  1413. *
  1414. * @param repository
  1415. * @param targetRef
  1416. * @return true if successful
  1417. */
  1418. public static boolean setHEADtoRef(Repository repository, String targetRef) {
  1419. try {
  1420. // detach HEAD if target ref is not a branch
  1421. boolean detach = !targetRef.startsWith(Constants.R_HEADS);
  1422. RefUpdate.Result result;
  1423. RefUpdate head = repository.updateRef(Constants.HEAD, detach);
  1424. if (detach) { // Tag
  1425. RevCommit commit = getCommit(repository, targetRef);
  1426. head.setNewObjectId(commit.getId());
  1427. result = head.forceUpdate();
  1428. } else {
  1429. result = head.link(targetRef);
  1430. }
  1431. switch (result) {
  1432. case NEW:
  1433. case FORCED:
  1434. case NO_CHANGE:
  1435. case FAST_FORWARD:
  1436. return true;
  1437. default:
  1438. LOGGER.error(MessageFormat.format("{0} HEAD update to {1} returned result {2}",
  1439. repository.getDirectory().getAbsolutePath(), targetRef, result));
  1440. }
  1441. } catch (Throwable t) {
  1442. error(t, repository, "{0} failed to set HEAD to {1}", targetRef);
  1443. }
  1444. return false;
  1445. }
  1446. /**
  1447. * Sets the local branch ref to point to the specified commit id.
  1448. *
  1449. * @param repository
  1450. * @param branch
  1451. * @param commitId
  1452. * @return true if successful
  1453. */
  1454. public static boolean setBranchRef(Repository repository, String branch, String commitId) {
  1455. String branchName = branch;
  1456. if (!branchName.startsWith(Constants.R_REFS)) {
  1457. branchName = Constants.R_HEADS + branch;
  1458. }
  1459. try {
  1460. RefUpdate refUpdate = repository.updateRef(branchName, false);
  1461. refUpdate.setNewObjectId(ObjectId.fromString(commitId));
  1462. RefUpdate.Result result = refUpdate.forceUpdate();
  1463. switch (result) {
  1464. case NEW:
  1465. case FORCED:
  1466. case NO_CHANGE:
  1467. case FAST_FORWARD:
  1468. return true;
  1469. default:
  1470. LOGGER.error(MessageFormat.format("{0} {1} update to {2} returned result {3}",
  1471. repository.getDirectory().getAbsolutePath(), branchName, commitId, result));
  1472. }
  1473. } catch (Throwable t) {
  1474. error(t, repository, "{0} failed to set {1} to {2}", branchName, commitId);
  1475. }
  1476. return false;
  1477. }
  1478. /**
  1479. * Deletes the specified branch ref.
  1480. *
  1481. * @param repository
  1482. * @param branch
  1483. * @return true if successful
  1484. */
  1485. public static boolean deleteBranchRef(Repository repository, String branch) {
  1486. String branchName = branch;
  1487. if (!branchName.startsWith(Constants.R_HEADS)) {
  1488. branchName = Constants.R_HEADS + branch;
  1489. }
  1490. try {
  1491. RefUpdate refUpdate = repository.updateRef(branchName, false);
  1492. refUpdate.setForceUpdate(true);
  1493. RefUpdate.Result result = refUpdate.delete();
  1494. switch (result) {
  1495. case NEW:
  1496. case FORCED:
  1497. case NO_CHANGE:
  1498. case FAST_FORWARD:
  1499. return true;
  1500. default:
  1501. LOGGER.error(MessageFormat.format("{0} failed to delete to {1} returned result {2}",
  1502. repository.getDirectory().getAbsolutePath(), branchName, result));
  1503. }
  1504. } catch (Throwable t) {
  1505. error(t, repository, "{0} failed to delete {1}", branchName);
  1506. }
  1507. return false;
  1508. }
  1509. /**
  1510. * Get the full branch and tag ref names for any potential HEAD targets.
  1511. *
  1512. * @param repository
  1513. * @return a list of ref names
  1514. */
  1515. public static List<String> getAvailableHeadTargets(Repository repository) {
  1516. List<String> targets = new ArrayList<String>();
  1517. for (RefModel branchModel : JGitUtils.getLocalBranches(repository, true, -1)) {
  1518. targets.add(branchModel.getName());
  1519. }
  1520. for (RefModel tagModel : JGitUtils.getTags(repository, true, -1)) {
  1521. targets.add(tagModel.getName());
  1522. }
  1523. return targets;
  1524. }
  1525. /**
  1526. * Returns all refs grouped by their associated object id.
  1527. *
  1528. * @param repository
  1529. * @return all refs grouped by their referenced object id
  1530. */
  1531. public static Map<ObjectId, List<RefModel>> getAllRefs(Repository repository) {
  1532. return getAllRefs(repository, true);
  1533. }
  1534. /**
  1535. * Returns all refs grouped by their associated object id.
  1536. *
  1537. * @param repository
  1538. * @param includeRemoteRefs
  1539. * @return all refs grouped by their referenced object id
  1540. */
  1541. public static Map<ObjectId, List<RefModel>> getAllRefs(Repository repository, boolean includeRemoteRefs) {
  1542. List<RefModel> list = getRefs(repository, org.eclipse.jgit.lib.RefDatabase.ALL, true, -1);
  1543. Map<ObjectId, List<RefModel>> refs = new HashMap<ObjectId, List<RefModel>>();
  1544. for (RefModel ref : list) {
  1545. if (!includeRemoteRefs && ref.getName().startsWith(Constants.R_REMOTES)) {
  1546. continue;
  1547. }
  1548. ObjectId objectid = ref.getReferencedObjectId();
  1549. if (!refs.containsKey(objectid)) {
  1550. refs.put(objectid, new ArrayList<RefModel>());
  1551. }
  1552. refs.get(objectid).add(ref);
  1553. }
  1554. return refs;
  1555. }
  1556. /**
  1557. * Returns the list of tags in the repository. If repository does not exist
  1558. * or is empty, an empty list is returned.
  1559. *
  1560. * @param repository
  1561. * @param fullName
  1562. * if true, /refs/tags/yadayadayada is returned. If false,
  1563. * yadayadayada is returned.
  1564. * @param maxCount
  1565. * if < 0, all tags are returned
  1566. * @return list of tags
  1567. */
  1568. public static List<RefModel> getTags(Repository repository, boolean fullName, int maxCount) {
  1569. return getRefs(repository, Constants.R_TAGS, fullName, maxCount);
  1570. }
  1571. /**
  1572. * Returns the list of tags in the repository. If repository does not exist
  1573. * or is empty, an empty list is returned.
  1574. *
  1575. * @param repository
  1576. * @param fullName
  1577. * if true, /refs/tags/yadayadayada is returned. If false,
  1578. * yadayadayada is returned.
  1579. * @param maxCount
  1580. * if < 0, all tags are returned
  1581. * @param offset
  1582. * if maxCount provided sets the starting point of the records to return
  1583. * @return list of tags
  1584. */
  1585. public static List<RefModel> getTags(Repository repository, boolean fullName, int maxCount, int offset) {
  1586. return getRefs(repository, Constants.R_TAGS, fullName, maxCount, offset);
  1587. }
  1588. /**
  1589. * Returns the list of local branches in the repository. If repository does
  1590. * not exist or is empty, an empty list is returned.
  1591. *
  1592. * @param repository
  1593. * @param fullName
  1594. * if true, /refs/heads/yadayadayada is returned. If false,
  1595. * yadayadayada is returned.
  1596. * @param maxCount
  1597. * if < 0, all local branches are returned
  1598. * @return list of local branches
  1599. */
  1600. public static List<RefModel> getLocalBranches(Repository repository, boolean fullName,
  1601. int maxCount) {
  1602. return getRefs(repository, Constants.R_HEADS, fullName, maxCount);
  1603. }
  1604. /**
  1605. * Returns the list of remote branches in the repository. If repository does
  1606. * not exist or is empty, an empty list is returned.
  1607. *
  1608. * @param repository
  1609. * @param fullName
  1610. * if true, /refs/remotes/yadayadayada is returned. If false,
  1611. * yadayadayada is returned.
  1612. * @param maxCount
  1613. * if < 0, all remote branches are returned
  1614. * @return list of remote branches
  1615. */
  1616. public static List<RefModel> getRemoteBranches(Repository repository, boolean fullName,
  1617. int maxCount) {
  1618. return getRefs(repository, Constants.R_REMOTES, fullName, maxCount);
  1619. }
  1620. /**
  1621. * Returns the list of note branches. If repository does not exist or is
  1622. * empty, an empty list is returned.
  1623. *
  1624. * @param repository
  1625. * @param fullName
  1626. * if true, /refs/notes/yadayadayada is returned. If false,
  1627. * yadayadayada is returned.
  1628. * @param maxCount
  1629. * if < 0, all note branches are returned
  1630. * @return list of note branches
  1631. */
  1632. public static List<RefModel> getNoteBranches(Repository repository, boolean fullName,
  1633. int maxCount) {
  1634. return getRefs(repository, Constants.R_NOTES, fullName, maxCount);
  1635. }
  1636. /**
  1637. * Returns the list of refs in the specified base ref. If repository does
  1638. * not exist or is empty, an empty list is returned.
  1639. *
  1640. * @param repository
  1641. * @param fullName
  1642. * if true, /refs/yadayadayada is returned. If false,
  1643. * yadayadayada is returned.
  1644. * @return list of refs
  1645. */
  1646. public static List<RefModel> getRefs(Repository repository, String baseRef) {
  1647. return getRefs(repository, baseRef, true, -1);
  1648. }
  1649. /**
  1650. * Returns a list of references in the repository matching "refs". If the
  1651. * repository is null or empty, an empty list is returned.
  1652. *
  1653. * @param repository
  1654. * @param refs
  1655. * if unspecified, all refs are returned
  1656. * @param fullName
  1657. * if true, /refs/something/yadayadayada is returned. If false,
  1658. * yadayadayada is returned.
  1659. * @param maxCount
  1660. * if < 0, all references are returned
  1661. * @return list of references
  1662. */
  1663. private static List<RefModel> getRefs(Repository repository, String refs, boolean fullName,
  1664. int maxCount) {
  1665. return getRefs(repository, refs, fullName, maxCount, 0);
  1666. }
  1667. /**
  1668. * Returns a list of references in the repository matching "refs". If the
  1669. * repository is null or empty, an empty list is returned.
  1670. *
  1671. * @param repository
  1672. * @param refs
  1673. * if unspecified, all refs are returned
  1674. * @param fullName
  1675. * if true, /refs/something/yadayadayada is returned. If false,
  1676. * yadayadayada is returned.
  1677. * @param maxCount
  1678. * if < 0, all references are returned
  1679. * @param offset
  1680. * if maxCount provided sets the starting point of the records to return
  1681. * @return list of references
  1682. */
  1683. private static List<RefModel> getRefs(Repository repository, String refs, boolean fullName,
  1684. int maxCount, int offset) {
  1685. List<RefModel> list = new ArrayList<RefModel>();
  1686. if (maxCount == 0) {
  1687. return list;
  1688. }
  1689. if (!hasCommits(repository)) {
  1690. return list;
  1691. }
  1692. try {
  1693. Map<String, Ref> map = repository.getRefDatabase().getRefs(refs);
  1694. RevWalk rw = new RevWalk(repository);
  1695. for (Entry<String, Ref> entry : map.entrySet()) {
  1696. Ref ref = entry.getValue();
  1697. RevObject object = rw.parseAny(ref.getObjectId());
  1698. String name = entry.getKey();
  1699. if (fullName && !StringUtils.isEmpty(refs)) {
  1700. name = refs + name;
  1701. }
  1702. list.add(new RefModel(name, ref, object));
  1703. }
  1704. rw.dispose();
  1705. Collections.sort(list);
  1706. Collections.reverse(list);
  1707. if (maxCount > 0 && list.size() > maxCount) {
  1708. if (offset < 0) {
  1709. offset = 0;
  1710. }
  1711. int endIndex = offset + maxCount;
  1712. if (endIndex > list.size()) {
  1713. endIndex = list.size();
  1714. }
  1715. list = new ArrayList<RefModel>(list.subList(offset, endIndex));
  1716. }
  1717. } catch (IOException e) {
  1718. error(e, repository, "{0} failed to retrieve {1}", refs);
  1719. }
  1720. return list;
  1721. }
  1722. /**
  1723. * Returns a RefModel for the gh-pages branch in the repository. If the
  1724. * branch can not be found, null is returned.
  1725. *
  1726. * @param repository
  1727. * @return a refmodel for the gh-pages branch or null
  1728. */
  1729. public static RefModel getPagesBranch(Repository repository) {
  1730. return getBranch(repository, "gh-pages");
  1731. }
  1732. /**
  1733. * Returns a RefModel for a specific branch name in the repository. If the
  1734. * branch can not be found, null is returned.
  1735. *
  1736. * @param repository
  1737. * @return a refmodel for the branch or null
  1738. */
  1739. public static RefModel getBranch(Repository repository, String name) {
  1740. RefModel branch = null;
  1741. try {
  1742. // search for the branch in local heads
  1743. for (RefModel ref : JGitUtils.getLocalBranches(repository, false, -1)) {
  1744. if (ref.reference.getName().endsWith(name)) {
  1745. branch = ref;
  1746. break;
  1747. }
  1748. }
  1749. // search for the branch in remote heads
  1750. if (branch == null) {
  1751. for (RefModel ref : JGitUtils.getRemoteBranches(repository, false, -1)) {
  1752. if (ref.reference.getName().endsWith(name)) {
  1753. branch = ref;
  1754. break;
  1755. }
  1756. }
  1757. }
  1758. } catch (Throwable t) {
  1759. LOGGER.error(MessageFormat.format("Failed to find {0} branch!", name), t);
  1760. }
  1761. return branch;
  1762. }
  1763. /**
  1764. * Returns the list of submodules for this repository.
  1765. *
  1766. * @param repository
  1767. * @param commit
  1768. * @return list of submodules
  1769. */
  1770. public static List<SubmoduleModel> getSubmodules(Repository repository, String commitId) {
  1771. RevCommit commit = getCommit(repository, commitId);
  1772. return getSubmodules(repository, commit.getTree());
  1773. }
  1774. /**
  1775. * Returns the list of submodules for this repository.
  1776. *
  1777. * @param repository
  1778. * @param commit
  1779. * @return list of submodules
  1780. */
  1781. public static List<SubmoduleModel> getSubmodules(Repository repository, RevTree tree) {
  1782. List<SubmoduleModel> list = new ArrayList<SubmoduleModel>();
  1783. byte [] blob = getByteContent(repository, tree, ".gitmodules", false);
  1784. if (blob == null) {
  1785. return list;
  1786. }
  1787. try {
  1788. BlobBasedConfig config = new BlobBasedConfig(repository.getConfig(), blob);
  1789. for (String module : config.getSubsections("submodule")) {
  1790. String path = config.getString("submodule", module, "path");
  1791. String url = config.getString("submodule", module, "url");
  1792. list.add(new SubmoduleModel(module, path, url));
  1793. }
  1794. } catch (ConfigInvalidException e) {
  1795. LOGGER.error("Failed to load .gitmodules file for " + repository.getDirectory(), e);
  1796. }
  1797. return list;
  1798. }
  1799. /**
  1800. * Returns the submodule definition for the specified path at the specified
  1801. * commit. If no module is defined for the path, null is returned.
  1802. *
  1803. * @param repository
  1804. * @param commit
  1805. * @param path
  1806. * @return a submodule definition or null if there is no submodule
  1807. */
  1808. public static SubmoduleModel getSubmoduleModel(Repository repository, String commitId, String path) {
  1809. for (SubmoduleModel model : getSubmodules(repository, commitId)) {
  1810. if (model.path.equals(path)) {
  1811. return model;
  1812. }
  1813. }
  1814. return null;
  1815. }
  1816. public static String getSubmoduleCommitId(Repository repository, String path, RevCommit commit) {
  1817. String commitId = null;
  1818. RevWalk rw = new RevWalk(repository);
  1819. TreeWalk tw = new TreeWalk(repository);
  1820. tw.setFilter(PathFilterGroup.createFromStrings(Collections.singleton(path)));
  1821. try {
  1822. tw.reset(commit.getTree());
  1823. while (tw.next()) {
  1824. if (tw.isSubtree() && !path.equals(tw.getPathString())) {
  1825. tw.enterSubtree();
  1826. continue;
  1827. }
  1828. if (FileMode.GITLINK == tw.getFileMode(0)) {
  1829. commitId = tw.getObjectId(0).getName();
  1830. break;
  1831. }
  1832. }
  1833. } catch (Throwable t) {
  1834. error(t, repository, "{0} can't find {1} in commit {2}", path, commit.name());
  1835. } finally {
  1836. rw.dispose();
  1837. tw.release();
  1838. }
  1839. return commitId;
  1840. }
  1841. /**
  1842. * Returns the list of notes entered about the commit from the refs/notes
  1843. * namespace. If the repository does not exist or is empty, an empty list is
  1844. * returned.
  1845. *
  1846. * @param repository
  1847. * @param commit
  1848. * @return list of notes
  1849. */
  1850. public static List<GitNote> getNotesOnCommit(Repository repository, RevCommit commit) {
  1851. List<GitNote> list = new ArrayList<GitNote>();
  1852. if (!hasCommits(repository)) {
  1853. return list;
  1854. }
  1855. List<RefModel> noteBranches = getNoteBranches(repository, true, -1);
  1856. for (RefModel notesRef : noteBranches) {
  1857. RevTree notesTree = JGitUtils.getCommit(repository, notesRef.getName()).getTree();
  1858. // flat notes list
  1859. String notePath = commit.getName();
  1860. String text = getStringContent(repository, notesTree, notePath);
  1861. if (!StringUtils.isEmpty(text)) {
  1862. List<RevCommit> history = getRevLog(repository, notesRef.getName(), notePath, 0, -1);
  1863. RefModel noteRef = new RefModel(notesRef.displayName, null, history.get(history
  1864. .size() - 1));
  1865. GitNote gitNote = new GitNote(noteRef, text);
  1866. list.add(gitNote);
  1867. continue;
  1868. }
  1869. // folder structure
  1870. StringBuilder sb = new StringBuilder(commit.getName());
  1871. sb.insert(2, '/');
  1872. notePath = sb.toString();
  1873. text = getStringContent(repository, notesTree, notePath);
  1874. if (!StringUtils.isEmpty(text)) {
  1875. List<RevCommit> history = getRevLog(repository, notesRef.getName(), notePath, 0, -1);
  1876. RefModel noteRef = new RefModel(notesRef.displayName, null, history.get(history
  1877. .size() - 1));
  1878. GitNote gitNote = new GitNote(noteRef, text);
  1879. list.add(gitNote);
  1880. }
  1881. }
  1882. return list;
  1883. }
  1884. /**
  1885. * this method creates an incremental revision number as a tag according to
  1886. * the amount of already existing tags, which start with a defined prefix.
  1887. *
  1888. * @param repository
  1889. * @param objectId
  1890. * @param tagger
  1891. * @param prefix
  1892. * @param intPattern
  1893. * @param message
  1894. * @return true if operation was successful, otherwise false
  1895. */
  1896. public static boolean createIncrementalRevisionTag(Repository repository,
  1897. String objectId, PersonIdent tagger, String prefix, String intPattern, String message) {
  1898. boolean result = false;
  1899. Iterator<Entry<String, Ref>> iterator = repository.getTags().entrySet().iterator();
  1900. long lastRev = 0;
  1901. while (iterator.hasNext()) {
  1902. Entry<String, Ref> entry = iterator.next();
  1903. if (entry.getKey().startsWith(prefix)) {
  1904. try {
  1905. long val = Long.parseLong(entry.getKey().substring(prefix.length()));
  1906. if (val > lastRev) {
  1907. lastRev = val;
  1908. }
  1909. } catch (Exception e) {
  1910. // this tag is NOT an incremental revision tag
  1911. }
  1912. }
  1913. }
  1914. DecimalFormat df = new DecimalFormat(intPattern);
  1915. result = createTag(repository, objectId, tagger, prefix + df.format((lastRev + 1)), message);
  1916. return result;
  1917. }
  1918. /**
  1919. * creates a tag in a repository
  1920. *
  1921. * @param repository
  1922. * @param objectId, the ref the tag points towards
  1923. * @param tagger, the person tagging the object
  1924. * @param tag, the string label
  1925. * @param message, the string message
  1926. * @return boolean, true if operation was successful, otherwise false
  1927. */
  1928. public static boolean createTag(Repository repository, String objectId, PersonIdent tagger, String tag, String message) {
  1929. try {
  1930. Git gitClient = Git.open(repository.getDirectory());
  1931. TagCommand tagCommand = gitClient.tag();
  1932. tagCommand.setTagger(tagger);
  1933. tagCommand.setMessage(message);
  1934. if (objectId != null) {
  1935. RevObject revObj = getCommit(repository, objectId);
  1936. tagCommand.setObjectId(revObj);
  1937. }
  1938. tagCommand.setName(tag);
  1939. Ref call = tagCommand.call();
  1940. return call != null ? true : false;
  1941. } catch (Exception e) {
  1942. error(e, repository, "Failed to create tag {1} in repository {0}", objectId, tag);
  1943. }
  1944. return false;
  1945. }
  1946. /**
  1947. * Create an orphaned branch in a repository.
  1948. *
  1949. * @param repository
  1950. * @param branchName
  1951. * @param author
  1952. * if unspecified, Gitblit will be the author of this new branch
  1953. * @return true if successful
  1954. */
  1955. public static boolean createOrphanBranch(Repository repository, String branchName,
  1956. PersonIdent author) {
  1957. boolean success = false;
  1958. String message = "Created branch " + branchName;
  1959. if (author == null) {
  1960. author = new PersonIdent("Gitblit", "gitblit@localhost");
  1961. }
  1962. try {
  1963. ObjectInserter odi = repository.newObjectInserter();
  1964. try {
  1965. // Create a blob object to insert into a tree
  1966. ObjectId blobId = odi.insert(Constants.OBJ_BLOB,
  1967. message.getBytes(Constants.CHARACTER_ENCODING));
  1968. // Create a tree object to reference from a commit
  1969. TreeFormatter tree = new TreeFormatter();
  1970. tree.append(".branch", FileMode.REGULAR_FILE, blobId);
  1971. ObjectId treeId = odi.insert(tree);
  1972. // Create a commit object
  1973. CommitBuilder commit = new CommitBuilder();
  1974. commit.setAuthor(author);
  1975. commit.setCommitter(author);
  1976. commit.setEncoding(Constants.CHARACTER_ENCODING);
  1977. commit.setMessage(message);
  1978. commit.setTreeId(treeId);
  1979. // Insert the commit into the repository
  1980. ObjectId commitId = odi.insert(commit);
  1981. odi.flush();
  1982. RevWalk revWalk = new RevWalk(repository);
  1983. try {
  1984. RevCommit revCommit = revWalk.parseCommit(commitId);
  1985. if (!branchName.startsWith("refs/")) {
  1986. branchName = "refs/heads/" + branchName;
  1987. }
  1988. RefUpdate ru = repository.updateRef(branchName);
  1989. ru.setNewObjectId(commitId);
  1990. ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
  1991. Result rc = ru.forceUpdate();
  1992. switch (rc) {
  1993. case NEW:
  1994. case FORCED:
  1995. case FAST_FORWARD:
  1996. success = true;
  1997. break;
  1998. default:
  1999. success = false;
  2000. }
  2001. } finally {
  2002. revWalk.release();
  2003. }
  2004. } finally {
  2005. odi.release();
  2006. }
  2007. } catch (Throwable t) {
  2008. error(t, repository, "Failed to create orphan branch {1} in repository {0}", branchName);
  2009. }
  2010. return success;
  2011. }
  2012. /**
  2013. * Reads the sparkleshare id, if present, from the repository.
  2014. *
  2015. * @param repository
  2016. * @return an id or null
  2017. */
  2018. public static String getSparkleshareId(Repository repository) {
  2019. byte[] content = getByteContent(repository, null, ".sparkleshare", false);
  2020. if (content == null) {
  2021. return null;
  2022. }
  2023. return StringUtils.decodeString(content);
  2024. }
  2025. /**
  2026. * Automatic repair of (some) invalid refspecs. These are the result of a
  2027. * bug in JGit cloning where a double forward-slash was injected. :(
  2028. *
  2029. * @param repository
  2030. * @return true, if the refspecs were repaired
  2031. */
  2032. public static boolean repairFetchSpecs(Repository repository) {
  2033. StoredConfig rc = repository.getConfig();
  2034. // auto-repair broken fetch ref specs
  2035. for (String name : rc.getSubsections("remote")) {
  2036. int invalidSpecs = 0;
  2037. int repairedSpecs = 0;
  2038. List<String> specs = new ArrayList<String>();
  2039. for (String spec : rc.getStringList("remote", name, "fetch")) {
  2040. try {
  2041. RefSpec rs = new RefSpec(spec);
  2042. // valid spec
  2043. specs.add(spec);
  2044. } catch (IllegalArgumentException e) {
  2045. // invalid spec
  2046. invalidSpecs++;
  2047. if (spec.contains("//")) {
  2048. // auto-repair this known spec bug
  2049. spec = spec.replace("//", "/");
  2050. specs.add(spec);
  2051. repairedSpecs++;
  2052. }
  2053. }
  2054. }
  2055. if (invalidSpecs == repairedSpecs && repairedSpecs > 0) {
  2056. // the fetch specs were automatically repaired
  2057. rc.setStringList("remote", name, "fetch", specs);
  2058. try {
  2059. rc.save();
  2060. rc.load();
  2061. LOGGER.debug("repaired {} invalid fetch refspecs for {}", repairedSpecs, repository.getDirectory());
  2062. return true;
  2063. } catch (Exception e) {
  2064. LOGGER.error(null, e);
  2065. }
  2066. } else if (invalidSpecs > 0) {
  2067. LOGGER.error("mirror executor found {} invalid fetch refspecs for {}", invalidSpecs, repository.getDirectory());
  2068. }
  2069. }
  2070. return false;
  2071. }
  2072. /**
  2073. * Returns true if the commit identified by commitId is an ancestor or the
  2074. * the commit identified by tipId.
  2075. *
  2076. * @param repository
  2077. * @param commitId
  2078. * @param tipId
  2079. * @return true if there is the commit is an ancestor of the tip
  2080. */
  2081. public static boolean isMergedInto(Repository repository, String commitId, String tipId) {
  2082. try {
  2083. return isMergedInto(repository, repository.resolve(commitId), repository.resolve(tipId));
  2084. } catch (Exception e) {
  2085. LOGGER.error("Failed to determine isMergedInto", e);
  2086. }
  2087. return false;
  2088. }
  2089. /**
  2090. * Returns true if the commit identified by commitId is an ancestor or the
  2091. * the commit identified by tipId.
  2092. *
  2093. * @param repository
  2094. * @param commitId
  2095. * @param tipId
  2096. * @return true if there is the commit is an ancestor of the tip
  2097. */
  2098. public static boolean isMergedInto(Repository repository, ObjectId commitId, ObjectId tipCommitId) {
  2099. // traverse the revlog looking for a commit chain between the endpoints
  2100. RevWalk rw = new RevWalk(repository);
  2101. try {
  2102. // must re-lookup RevCommits to workaround undocumented RevWalk bug
  2103. RevCommit tip = rw.lookupCommit(tipCommitId);
  2104. RevCommit commit = rw.lookupCommit(commitId);
  2105. return rw.isMergedInto(commit, tip);
  2106. } catch (Exception e) {
  2107. LOGGER.error("Failed to determine isMergedInto", e);
  2108. } finally {
  2109. rw.dispose();
  2110. }
  2111. return false;
  2112. }
  2113. /**
  2114. * Returns the merge base of two commits or null if there is no common
  2115. * ancestry.
  2116. *
  2117. * @param repository
  2118. * @param commitIdA
  2119. * @param commitIdB
  2120. * @return the commit id of the merge base or null if there is no common base
  2121. */
  2122. public static String getMergeBase(Repository repository, ObjectId commitIdA, ObjectId commitIdB) {
  2123. RevWalk rw = new RevWalk(repository);
  2124. try {
  2125. RevCommit a = rw.lookupCommit(commitIdA);
  2126. RevCommit b = rw.lookupCommit(commitIdB);
  2127. rw.setRevFilter(RevFilter.MERGE_BASE);
  2128. rw.markStart(a);
  2129. rw.markStart(b);
  2130. RevCommit mergeBase = rw.next();
  2131. if (mergeBase == null) {
  2132. return null;
  2133. }
  2134. return mergeBase.getName();
  2135. } catch (Exception e) {
  2136. LOGGER.error("Failed to determine merge base", e);
  2137. } finally {
  2138. rw.dispose();
  2139. }
  2140. return null;
  2141. }
  2142. public static enum MergeStatus {
  2143. NOT_MERGEABLE, FAILED, ALREADY_MERGED, MERGEABLE, MERGED;
  2144. }
  2145. /**
  2146. * Determines if we can cleanly merge one branch into another. Returns true
  2147. * if we can merge without conflict, otherwise returns false.
  2148. *
  2149. * @param repository
  2150. * @param src
  2151. * @param toBranch
  2152. * @return true if we can merge without conflict
  2153. */
  2154. public static MergeStatus canMerge(Repository repository, String src, String toBranch) {
  2155. RevWalk revWalk = null;
  2156. try {
  2157. revWalk = new RevWalk(repository);
  2158. RevCommit branchTip = revWalk.lookupCommit(repository.resolve(toBranch));
  2159. RevCommit srcTip = revWalk.lookupCommit(repository.resolve(src));
  2160. if (revWalk.isMergedInto(srcTip, branchTip)) {
  2161. // already merged
  2162. return MergeStatus.ALREADY_MERGED;
  2163. } else if (revWalk.isMergedInto(branchTip, srcTip)) {
  2164. // fast-forward
  2165. return MergeStatus.MERGEABLE;
  2166. }
  2167. RecursiveMerger merger = (RecursiveMerger) MergeStrategy.RECURSIVE.newMerger(repository, true);
  2168. boolean canMerge = merger.merge(branchTip, srcTip);
  2169. if (canMerge) {
  2170. return MergeStatus.MERGEABLE;
  2171. }
  2172. } catch (IOException e) {
  2173. LOGGER.error("Failed to determine canMerge", e);
  2174. } finally {
  2175. if (revWalk != null) {
  2176. revWalk.release();
  2177. }
  2178. }
  2179. return MergeStatus.NOT_MERGEABLE;
  2180. }
  2181. public static class MergeResult {
  2182. public final MergeStatus status;
  2183. public final String sha;
  2184. MergeResult(MergeStatus status, String sha) {
  2185. this.status = status;
  2186. this.sha = sha;
  2187. }
  2188. }
  2189. /**
  2190. * Tries to merge a commit into a branch. If there are conflicts, the merge
  2191. * will fail.
  2192. *
  2193. * @param repository
  2194. * @param src
  2195. * @param toBranch
  2196. * @param committer
  2197. * @param message
  2198. * @return the merge result
  2199. */
  2200. public static MergeResult merge(Repository repository, String src, String toBranch,
  2201. PersonIdent committer, String message) {
  2202. if (!toBranch.startsWith(Constants.R_REFS)) {
  2203. // branch ref doesn't start with ref, assume this is a branch head
  2204. toBranch = Constants.R_HEADS + toBranch;
  2205. }
  2206. RevWalk revWalk = null;
  2207. try {
  2208. revWalk = new RevWalk(repository);
  2209. RevCommit branchTip = revWalk.lookupCommit(repository.resolve(toBranch));
  2210. RevCommit srcTip = revWalk.lookupCommit(repository.resolve(src));
  2211. if (revWalk.isMergedInto(srcTip, branchTip)) {
  2212. // already merged
  2213. return new MergeResult(MergeStatus.ALREADY_MERGED, null);
  2214. }
  2215. RecursiveMerger merger = (RecursiveMerger) MergeStrategy.RECURSIVE.newMerger(repository, true);
  2216. boolean merged = merger.merge(branchTip, srcTip);
  2217. if (merged) {
  2218. // create a merge commit and a reference to track the merge commit
  2219. ObjectId treeId = merger.getResultTreeId();
  2220. ObjectInserter odi = repository.newObjectInserter();
  2221. try {
  2222. // Create a commit object
  2223. CommitBuilder commitBuilder = new CommitBuilder();
  2224. commitBuilder.setCommitter(committer);
  2225. commitBuilder.setAuthor(committer);
  2226. commitBuilder.setEncoding(Constants.CHARSET);
  2227. if (StringUtils.isEmpty(message)) {
  2228. message = MessageFormat.format("merge {0} into {1}", srcTip.getName(), branchTip.getName());
  2229. }
  2230. commitBuilder.setMessage(message);
  2231. commitBuilder.setParentIds(branchTip.getId(), srcTip.getId());
  2232. commitBuilder.setTreeId(treeId);
  2233. // Insert the merge commit into the repository
  2234. ObjectId mergeCommitId = odi.insert(commitBuilder);
  2235. odi.flush();
  2236. // set the merge ref to the merge commit
  2237. RevCommit mergeCommit = revWalk.parseCommit(mergeCommitId);
  2238. RefUpdate mergeRefUpdate = repository.updateRef(toBranch);
  2239. mergeRefUpdate.setNewObjectId(mergeCommitId);
  2240. mergeRefUpdate.setRefLogMessage("commit: " + mergeCommit.getShortMessage(), false);
  2241. RefUpdate.Result rc = mergeRefUpdate.update();
  2242. switch (rc) {
  2243. case FAST_FORWARD:
  2244. // successful, clean merge
  2245. break;
  2246. default:
  2247. throw new GitBlitException(MessageFormat.format("Unexpected result \"{0}\" when merging commit {1} into {2} in {3}",
  2248. rc.name(), srcTip.getName(), branchTip.getName(), repository.getDirectory()));
  2249. }
  2250. // return the merge commit id
  2251. return new MergeResult(MergeStatus.MERGED, mergeCommitId.getName());
  2252. } finally {
  2253. odi.release();
  2254. }
  2255. }
  2256. } catch (IOException e) {
  2257. LOGGER.error("Failed to merge", e);
  2258. } finally {
  2259. if (revWalk != null) {
  2260. revWalk.release();
  2261. }
  2262. }
  2263. return new MergeResult(MergeStatus.FAILED, null);
  2264. }
  2265. }