You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JGitUtils.java 86KB

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