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

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