Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JGitUtils.java 82KB

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