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.

Repository.java 65KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093
  1. /*
  2. * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com>
  3. * Copyright (C) 2008-2010, Google Inc.
  4. * Copyright (C) 2006-2010, Robin Rosenberg <robin.rosenberg@dewire.com>
  5. * Copyright (C) 2006-2012, Shawn O. Pearce <spearce@spearce.org>
  6. * Copyright (C) 2012, Daniel Megert <daniel_megert@ch.ibm.com>
  7. * Copyright (C) 2017, Wim Jongman <wim.jongman@remainsoftware.com>
  8. * and other copyright owners as documented in the project's IP log.
  9. *
  10. * This program and the accompanying materials are made available
  11. * under the terms of the Eclipse Distribution License v1.0 which
  12. * accompanies this distribution, is reproduced below, and is
  13. * available at http://www.eclipse.org/org/documents/edl-v10.php
  14. *
  15. * All rights reserved.
  16. *
  17. * Redistribution and use in source and binary forms, with or
  18. * without modification, are permitted provided that the following
  19. * conditions are met:
  20. *
  21. * - Redistributions of source code must retain the above copyright
  22. * notice, this list of conditions and the following disclaimer.
  23. *
  24. * - Redistributions in binary form must reproduce the above
  25. * copyright notice, this list of conditions and the following
  26. * disclaimer in the documentation and/or other materials provided
  27. * with the distribution.
  28. *
  29. * - Neither the name of the Eclipse Foundation, Inc. nor the
  30. * names of its contributors may be used to endorse or promote
  31. * products derived from this software without specific prior
  32. * written permission.
  33. *
  34. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  35. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  36. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  37. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  38. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  39. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  41. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  42. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  43. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  44. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  45. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  46. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  47. */
  48. package org.eclipse.jgit.lib;
  49. import static org.eclipse.jgit.lib.Constants.LOCK_SUFFIX;
  50. import static java.nio.charset.StandardCharsets.UTF_8;
  51. import java.io.BufferedOutputStream;
  52. import java.io.File;
  53. import java.io.FileNotFoundException;
  54. import java.io.FileOutputStream;
  55. import java.io.IOException;
  56. import java.io.OutputStream;
  57. import java.io.UncheckedIOException;
  58. import java.net.URISyntaxException;
  59. import java.text.MessageFormat;
  60. import java.util.Collection;
  61. import java.util.Collections;
  62. import java.util.HashMap;
  63. import java.util.HashSet;
  64. import java.util.LinkedList;
  65. import java.util.List;
  66. import java.util.Map;
  67. import java.util.Set;
  68. import java.util.concurrent.atomic.AtomicInteger;
  69. import java.util.concurrent.atomic.AtomicLong;
  70. import java.util.regex.Pattern;
  71. import org.eclipse.jgit.annotations.NonNull;
  72. import org.eclipse.jgit.annotations.Nullable;
  73. import org.eclipse.jgit.attributes.AttributesNodeProvider;
  74. import org.eclipse.jgit.dircache.DirCache;
  75. import org.eclipse.jgit.errors.AmbiguousObjectException;
  76. import org.eclipse.jgit.errors.CorruptObjectException;
  77. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  78. import org.eclipse.jgit.errors.MissingObjectException;
  79. import org.eclipse.jgit.errors.NoWorkTreeException;
  80. import org.eclipse.jgit.errors.RevisionSyntaxException;
  81. import org.eclipse.jgit.events.IndexChangedEvent;
  82. import org.eclipse.jgit.events.IndexChangedListener;
  83. import org.eclipse.jgit.events.ListenerList;
  84. import org.eclipse.jgit.events.RepositoryEvent;
  85. import org.eclipse.jgit.internal.JGitText;
  86. import org.eclipse.jgit.revwalk.RevBlob;
  87. import org.eclipse.jgit.revwalk.RevCommit;
  88. import org.eclipse.jgit.revwalk.RevObject;
  89. import org.eclipse.jgit.revwalk.RevTree;
  90. import org.eclipse.jgit.revwalk.RevWalk;
  91. import org.eclipse.jgit.transport.RefSpec;
  92. import org.eclipse.jgit.transport.RemoteConfig;
  93. import org.eclipse.jgit.treewalk.TreeWalk;
  94. import org.eclipse.jgit.util.FS;
  95. import org.eclipse.jgit.util.FileUtils;
  96. import org.eclipse.jgit.util.IO;
  97. import org.eclipse.jgit.util.RawParseUtils;
  98. import org.eclipse.jgit.util.SystemReader;
  99. import org.slf4j.Logger;
  100. import org.slf4j.LoggerFactory;
  101. /**
  102. * Represents a Git repository.
  103. * <p>
  104. * A repository holds all objects and refs used for managing source code (could
  105. * be any type of file, but source code is what SCM's are typically used for).
  106. * <p>
  107. * The thread-safety of a {@link org.eclipse.jgit.lib.Repository} very much
  108. * depends on the concrete implementation. Applications working with a generic
  109. * {@code Repository} type must not assume the instance is thread-safe.
  110. * <ul>
  111. * <li>{@code FileRepository} is thread-safe.
  112. * <li>{@code DfsRepository} thread-safety is determined by its subclass.
  113. * </ul>
  114. */
  115. public abstract class Repository implements AutoCloseable {
  116. private static final Logger LOG = LoggerFactory.getLogger(Repository.class);
  117. private static final ListenerList globalListeners = new ListenerList();
  118. /**
  119. * Branch names containing slashes should not have a name component that is
  120. * one of the reserved device names on Windows.
  121. *
  122. * @see #normalizeBranchName(String)
  123. */
  124. private static final Pattern FORBIDDEN_BRANCH_NAME_COMPONENTS = Pattern
  125. .compile(
  126. "(^|/)(aux|com[1-9]|con|lpt[1-9]|nul|prn)(\\.[^/]*)?", //$NON-NLS-1$
  127. Pattern.CASE_INSENSITIVE);
  128. /**
  129. * Get the global listener list observing all events in this JVM.
  130. *
  131. * @return the global listener list observing all events in this JVM.
  132. */
  133. public static ListenerList getGlobalListenerList() {
  134. return globalListeners;
  135. }
  136. /** Use counter */
  137. final AtomicInteger useCnt = new AtomicInteger(1);
  138. final AtomicLong closedAt = new AtomicLong();
  139. /** Metadata directory holding the repository's critical files. */
  140. private final File gitDir;
  141. /** File abstraction used to resolve paths. */
  142. private final FS fs;
  143. private final ListenerList myListeners = new ListenerList();
  144. /** If not bare, the top level directory of the working files. */
  145. private final File workTree;
  146. /** If not bare, the index file caching the working file states. */
  147. private final File indexFile;
  148. /**
  149. * Initialize a new repository instance.
  150. *
  151. * @param options
  152. * options to configure the repository.
  153. */
  154. protected Repository(BaseRepositoryBuilder options) {
  155. gitDir = options.getGitDir();
  156. fs = options.getFS();
  157. workTree = options.getWorkTree();
  158. indexFile = options.getIndexFile();
  159. }
  160. /**
  161. * Get listeners observing only events on this repository.
  162. *
  163. * @return listeners observing only events on this repository.
  164. */
  165. @NonNull
  166. public ListenerList getListenerList() {
  167. return myListeners;
  168. }
  169. /**
  170. * Fire an event to all registered listeners.
  171. * <p>
  172. * The source repository of the event is automatically set to this
  173. * repository, before the event is delivered to any listeners.
  174. *
  175. * @param event
  176. * the event to deliver.
  177. */
  178. public void fireEvent(RepositoryEvent<?> event) {
  179. event.setRepository(this);
  180. myListeners.dispatch(event);
  181. globalListeners.dispatch(event);
  182. }
  183. /**
  184. * Create a new Git repository.
  185. * <p>
  186. * Repository with working tree is created using this method. This method is
  187. * the same as {@code create(false)}.
  188. *
  189. * @throws java.io.IOException
  190. * @see #create(boolean)
  191. */
  192. public void create() throws IOException {
  193. create(false);
  194. }
  195. /**
  196. * Create a new Git repository initializing the necessary files and
  197. * directories.
  198. *
  199. * @param bare
  200. * if true, a bare repository (a repository without a working
  201. * directory) is created.
  202. * @throws java.io.IOException
  203. * in case of IO problem
  204. */
  205. public abstract void create(boolean bare) throws IOException;
  206. /**
  207. * Get local metadata directory
  208. *
  209. * @return local metadata directory; {@code null} if repository isn't local.
  210. */
  211. /*
  212. * TODO This method should be annotated as Nullable, because in some
  213. * specific configurations metadata is not located in the local file system
  214. * (for example in memory databases). In "usual" repositories this
  215. * annotation would only cause compiler errors at places where the actual
  216. * directory can never be null.
  217. */
  218. public File getDirectory() {
  219. return gitDir;
  220. }
  221. /**
  222. * Get the object database which stores this repository's data.
  223. *
  224. * @return the object database which stores this repository's data.
  225. */
  226. @NonNull
  227. public abstract ObjectDatabase getObjectDatabase();
  228. /**
  229. * Create a new inserter to create objects in {@link #getObjectDatabase()}.
  230. *
  231. * @return a new inserter to create objects in {@link #getObjectDatabase()}.
  232. */
  233. @NonNull
  234. public ObjectInserter newObjectInserter() {
  235. return getObjectDatabase().newInserter();
  236. }
  237. /**
  238. * Create a new reader to read objects from {@link #getObjectDatabase()}.
  239. *
  240. * @return a new reader to read objects from {@link #getObjectDatabase()}.
  241. */
  242. @NonNull
  243. public ObjectReader newObjectReader() {
  244. return getObjectDatabase().newReader();
  245. }
  246. /**
  247. * Get the reference database which stores the reference namespace.
  248. *
  249. * @return the reference database which stores the reference namespace.
  250. */
  251. @NonNull
  252. public abstract RefDatabase getRefDatabase();
  253. /**
  254. * Get the configuration of this repository.
  255. *
  256. * @return the configuration of this repository.
  257. */
  258. @NonNull
  259. public abstract StoredConfig getConfig();
  260. /**
  261. * Create a new {@link org.eclipse.jgit.attributes.AttributesNodeProvider}.
  262. *
  263. * @return a new {@link org.eclipse.jgit.attributes.AttributesNodeProvider}.
  264. * This {@link org.eclipse.jgit.attributes.AttributesNodeProvider}
  265. * is lazy loaded only once. It means that it will not be updated
  266. * after loading. Prefer creating new instance for each use.
  267. * @since 4.2
  268. */
  269. @NonNull
  270. public abstract AttributesNodeProvider createAttributesNodeProvider();
  271. /**
  272. * Get the used file system abstraction.
  273. *
  274. * @return the used file system abstraction, or {@code null} if
  275. * repository isn't local.
  276. */
  277. /*
  278. * TODO This method should be annotated as Nullable, because in some
  279. * specific configurations metadata is not located in the local file system
  280. * (for example in memory databases). In "usual" repositories this
  281. * annotation would only cause compiler errors at places where the actual
  282. * directory can never be null.
  283. */
  284. public FS getFS() {
  285. return fs;
  286. }
  287. /**
  288. * Whether the specified object is stored in this repo or any of the known
  289. * shared repositories.
  290. *
  291. * @param objectId
  292. * a {@link org.eclipse.jgit.lib.AnyObjectId} object.
  293. * @return true if the specified object is stored in this repo or any of the
  294. * known shared repositories.
  295. * @deprecated use {@code getObjectDatabase().has(objectId)}
  296. */
  297. @Deprecated
  298. public boolean hasObject(AnyObjectId objectId) {
  299. try {
  300. return getObjectDatabase().has(objectId);
  301. } catch (IOException e) {
  302. throw new UncheckedIOException(e);
  303. }
  304. }
  305. /**
  306. * Open an object from this repository.
  307. * <p>
  308. * This is a one-shot call interface which may be faster than allocating a
  309. * {@link #newObjectReader()} to perform the lookup.
  310. *
  311. * @param objectId
  312. * identity of the object to open.
  313. * @return a {@link org.eclipse.jgit.lib.ObjectLoader} for accessing the
  314. * object.
  315. * @throws org.eclipse.jgit.errors.MissingObjectException
  316. * the object does not exist.
  317. * @throws java.io.IOException
  318. * the object store cannot be accessed.
  319. */
  320. @NonNull
  321. public ObjectLoader open(AnyObjectId objectId)
  322. throws MissingObjectException, IOException {
  323. return getObjectDatabase().open(objectId);
  324. }
  325. /**
  326. * Open an object from this repository.
  327. * <p>
  328. * This is a one-shot call interface which may be faster than allocating a
  329. * {@link #newObjectReader()} to perform the lookup.
  330. *
  331. * @param objectId
  332. * identity of the object to open.
  333. * @param typeHint
  334. * hint about the type of object being requested, e.g.
  335. * {@link org.eclipse.jgit.lib.Constants#OBJ_BLOB};
  336. * {@link org.eclipse.jgit.lib.ObjectReader#OBJ_ANY} if the
  337. * object type is not known, or does not matter to the caller.
  338. * @return a {@link org.eclipse.jgit.lib.ObjectLoader} for accessing the
  339. * object.
  340. * @throws org.eclipse.jgit.errors.MissingObjectException
  341. * the object does not exist.
  342. * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
  343. * typeHint was not OBJ_ANY, and the object's actual type does
  344. * not match typeHint.
  345. * @throws java.io.IOException
  346. * the object store cannot be accessed.
  347. */
  348. @NonNull
  349. public ObjectLoader open(AnyObjectId objectId, int typeHint)
  350. throws MissingObjectException, IncorrectObjectTypeException,
  351. IOException {
  352. return getObjectDatabase().open(objectId, typeHint);
  353. }
  354. /**
  355. * Create a command to update, create or delete a ref in this repository.
  356. *
  357. * @param ref
  358. * name of the ref the caller wants to modify.
  359. * @return an update command. The caller must finish populating this command
  360. * and then invoke one of the update methods to actually make a
  361. * change.
  362. * @throws java.io.IOException
  363. * a symbolic ref was passed in and could not be resolved back
  364. * to the base ref, as the symbolic ref could not be read.
  365. */
  366. @NonNull
  367. public RefUpdate updateRef(String ref) throws IOException {
  368. return updateRef(ref, false);
  369. }
  370. /**
  371. * Create a command to update, create or delete a ref in this repository.
  372. *
  373. * @param ref
  374. * name of the ref the caller wants to modify.
  375. * @param detach
  376. * true to create a detached head
  377. * @return an update command. The caller must finish populating this command
  378. * and then invoke one of the update methods to actually make a
  379. * change.
  380. * @throws java.io.IOException
  381. * a symbolic ref was passed in and could not be resolved back
  382. * to the base ref, as the symbolic ref could not be read.
  383. */
  384. @NonNull
  385. public RefUpdate updateRef(String ref, boolean detach) throws IOException {
  386. return getRefDatabase().newUpdate(ref, detach);
  387. }
  388. /**
  389. * Create a command to rename a ref in this repository
  390. *
  391. * @param fromRef
  392. * name of ref to rename from
  393. * @param toRef
  394. * name of ref to rename to
  395. * @return an update command that knows how to rename a branch to another.
  396. * @throws java.io.IOException
  397. * the rename could not be performed.
  398. */
  399. @NonNull
  400. public RefRename renameRef(String fromRef, String toRef) throws IOException {
  401. return getRefDatabase().newRename(fromRef, toRef);
  402. }
  403. /**
  404. * Parse a git revision string and return an object id.
  405. *
  406. * Combinations of these operators are supported:
  407. * <ul>
  408. * <li><b>HEAD</b>, <b>MERGE_HEAD</b>, <b>FETCH_HEAD</b></li>
  409. * <li><b>SHA-1</b>: a complete or abbreviated SHA-1</li>
  410. * <li><b>refs/...</b>: a complete reference name</li>
  411. * <li><b>short-name</b>: a short reference name under {@code refs/heads},
  412. * {@code refs/tags}, or {@code refs/remotes} namespace</li>
  413. * <li><b>tag-NN-gABBREV</b>: output from describe, parsed by treating
  414. * {@code ABBREV} as an abbreviated SHA-1.</li>
  415. * <li><i>id</i><b>^</b>: first parent of commit <i>id</i>, this is the same
  416. * as {@code id^1}</li>
  417. * <li><i>id</i><b>^0</b>: ensure <i>id</i> is a commit</li>
  418. * <li><i>id</i><b>^n</b>: n-th parent of commit <i>id</i></li>
  419. * <li><i>id</i><b>~n</b>: n-th historical ancestor of <i>id</i>, by first
  420. * parent. {@code id~3} is equivalent to {@code id^1^1^1} or {@code id^^^}.</li>
  421. * <li><i>id</i><b>:path</b>: Lookup path under tree named by <i>id</i></li>
  422. * <li><i>id</i><b>^{commit}</b>: ensure <i>id</i> is a commit</li>
  423. * <li><i>id</i><b>^{tree}</b>: ensure <i>id</i> is a tree</li>
  424. * <li><i>id</i><b>^{tag}</b>: ensure <i>id</i> is a tag</li>
  425. * <li><i>id</i><b>^{blob}</b>: ensure <i>id</i> is a blob</li>
  426. * </ul>
  427. *
  428. * <p>
  429. * The following operators are specified by Git conventions, but are not
  430. * supported by this method:
  431. * <ul>
  432. * <li><b>ref@{n}</b>: n-th version of ref as given by its reflog</li>
  433. * <li><b>ref@{time}</b>: value of ref at the designated time</li>
  434. * </ul>
  435. *
  436. * @param revstr
  437. * A git object references expression
  438. * @return an ObjectId or {@code null} if revstr can't be resolved to any
  439. * ObjectId
  440. * @throws org.eclipse.jgit.errors.AmbiguousObjectException
  441. * {@code revstr} contains an abbreviated ObjectId and this
  442. * repository contains more than one object which match to the
  443. * input abbreviation.
  444. * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
  445. * the id parsed does not meet the type required to finish
  446. * applying the operators in the expression.
  447. * @throws org.eclipse.jgit.errors.RevisionSyntaxException
  448. * the expression is not supported by this implementation, or
  449. * does not meet the standard syntax.
  450. * @throws java.io.IOException
  451. * on serious errors
  452. */
  453. @Nullable
  454. public ObjectId resolve(String revstr)
  455. throws AmbiguousObjectException, IncorrectObjectTypeException,
  456. RevisionSyntaxException, IOException {
  457. try (RevWalk rw = new RevWalk(this)) {
  458. Object resolved = resolve(rw, revstr);
  459. if (resolved instanceof String) {
  460. final Ref ref = findRef((String) resolved);
  461. return ref != null ? ref.getLeaf().getObjectId() : null;
  462. } else {
  463. return (ObjectId) resolved;
  464. }
  465. }
  466. }
  467. /**
  468. * Simplify an expression, but unlike {@link #resolve(String)} it will not
  469. * resolve a branch passed or resulting from the expression, such as @{-}.
  470. * Thus this method can be used to process an expression to a method that
  471. * expects a branch or revision id.
  472. *
  473. * @param revstr a {@link java.lang.String} object.
  474. * @return object id or ref name from resolved expression or {@code null} if
  475. * given expression cannot be resolved
  476. * @throws org.eclipse.jgit.errors.AmbiguousObjectException
  477. * @throws java.io.IOException
  478. */
  479. @Nullable
  480. public String simplify(String revstr)
  481. throws AmbiguousObjectException, IOException {
  482. try (RevWalk rw = new RevWalk(this)) {
  483. Object resolved = resolve(rw, revstr);
  484. if (resolved != null)
  485. if (resolved instanceof String)
  486. return (String) resolved;
  487. else
  488. return ((AnyObjectId) resolved).getName();
  489. return null;
  490. }
  491. }
  492. @Nullable
  493. private Object resolve(RevWalk rw, String revstr)
  494. throws IOException {
  495. char[] revChars = revstr.toCharArray();
  496. RevObject rev = null;
  497. String name = null;
  498. int done = 0;
  499. for (int i = 0; i < revChars.length; ++i) {
  500. switch (revChars[i]) {
  501. case '^':
  502. if (rev == null) {
  503. if (name == null)
  504. if (done == 0)
  505. name = new String(revChars, done, i);
  506. else {
  507. done = i + 1;
  508. break;
  509. }
  510. rev = parseSimple(rw, name);
  511. name = null;
  512. if (rev == null)
  513. return null;
  514. }
  515. if (i + 1 < revChars.length) {
  516. switch (revChars[i + 1]) {
  517. case '0':
  518. case '1':
  519. case '2':
  520. case '3':
  521. case '4':
  522. case '5':
  523. case '6':
  524. case '7':
  525. case '8':
  526. case '9':
  527. int j;
  528. rev = rw.parseCommit(rev);
  529. for (j = i + 1; j < revChars.length; ++j) {
  530. if (!Character.isDigit(revChars[j]))
  531. break;
  532. }
  533. String parentnum = new String(revChars, i + 1, j - i
  534. - 1);
  535. int pnum;
  536. try {
  537. pnum = Integer.parseInt(parentnum);
  538. } catch (NumberFormatException e) {
  539. throw new RevisionSyntaxException(
  540. JGitText.get().invalidCommitParentNumber,
  541. revstr);
  542. }
  543. if (pnum != 0) {
  544. RevCommit commit = (RevCommit) rev;
  545. if (pnum > commit.getParentCount())
  546. rev = null;
  547. else
  548. rev = commit.getParent(pnum - 1);
  549. }
  550. i = j - 1;
  551. done = j;
  552. break;
  553. case '{':
  554. int k;
  555. String item = null;
  556. for (k = i + 2; k < revChars.length; ++k) {
  557. if (revChars[k] == '}') {
  558. item = new String(revChars, i + 2, k - i - 2);
  559. break;
  560. }
  561. }
  562. i = k;
  563. if (item != null)
  564. if (item.equals("tree")) { //$NON-NLS-1$
  565. rev = rw.parseTree(rev);
  566. } else if (item.equals("commit")) { //$NON-NLS-1$
  567. rev = rw.parseCommit(rev);
  568. } else if (item.equals("blob")) { //$NON-NLS-1$
  569. rev = rw.peel(rev);
  570. if (!(rev instanceof RevBlob))
  571. throw new IncorrectObjectTypeException(rev,
  572. Constants.TYPE_BLOB);
  573. } else if (item.equals("")) { //$NON-NLS-1$
  574. rev = rw.peel(rev);
  575. } else
  576. throw new RevisionSyntaxException(revstr);
  577. else
  578. throw new RevisionSyntaxException(revstr);
  579. done = k;
  580. break;
  581. default:
  582. rev = rw.peel(rev);
  583. if (rev instanceof RevCommit) {
  584. RevCommit commit = ((RevCommit) rev);
  585. if (commit.getParentCount() == 0)
  586. rev = null;
  587. else
  588. rev = commit.getParent(0);
  589. } else
  590. throw new IncorrectObjectTypeException(rev,
  591. Constants.TYPE_COMMIT);
  592. }
  593. } else {
  594. rev = rw.peel(rev);
  595. if (rev instanceof RevCommit) {
  596. RevCommit commit = ((RevCommit) rev);
  597. if (commit.getParentCount() == 0)
  598. rev = null;
  599. else
  600. rev = commit.getParent(0);
  601. } else
  602. throw new IncorrectObjectTypeException(rev,
  603. Constants.TYPE_COMMIT);
  604. }
  605. done = i + 1;
  606. break;
  607. case '~':
  608. if (rev == null) {
  609. if (name == null)
  610. if (done == 0)
  611. name = new String(revChars, done, i);
  612. else {
  613. done = i + 1;
  614. break;
  615. }
  616. rev = parseSimple(rw, name);
  617. name = null;
  618. if (rev == null)
  619. return null;
  620. }
  621. rev = rw.peel(rev);
  622. if (!(rev instanceof RevCommit))
  623. throw new IncorrectObjectTypeException(rev,
  624. Constants.TYPE_COMMIT);
  625. int l;
  626. for (l = i + 1; l < revChars.length; ++l) {
  627. if (!Character.isDigit(revChars[l]))
  628. break;
  629. }
  630. int dist;
  631. if (l - i > 1) {
  632. String distnum = new String(revChars, i + 1, l - i - 1);
  633. try {
  634. dist = Integer.parseInt(distnum);
  635. } catch (NumberFormatException e) {
  636. throw new RevisionSyntaxException(
  637. JGitText.get().invalidAncestryLength, revstr);
  638. }
  639. } else
  640. dist = 1;
  641. while (dist > 0) {
  642. RevCommit commit = (RevCommit) rev;
  643. if (commit.getParentCount() == 0) {
  644. rev = null;
  645. break;
  646. }
  647. commit = commit.getParent(0);
  648. rw.parseHeaders(commit);
  649. rev = commit;
  650. --dist;
  651. }
  652. i = l - 1;
  653. done = l;
  654. break;
  655. case '@':
  656. if (rev != null)
  657. throw new RevisionSyntaxException(revstr);
  658. if (i + 1 == revChars.length)
  659. continue;
  660. if (i + 1 < revChars.length && revChars[i + 1] != '{')
  661. continue;
  662. int m;
  663. String time = null;
  664. for (m = i + 2; m < revChars.length; ++m) {
  665. if (revChars[m] == '}') {
  666. time = new String(revChars, i + 2, m - i - 2);
  667. break;
  668. }
  669. }
  670. if (time != null) {
  671. if (time.equals("upstream")) { //$NON-NLS-1$
  672. if (name == null)
  673. name = new String(revChars, done, i);
  674. if (name.equals("")) //$NON-NLS-1$
  675. // Currently checked out branch, HEAD if
  676. // detached
  677. name = Constants.HEAD;
  678. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  679. throw new RevisionSyntaxException(MessageFormat
  680. .format(JGitText.get().invalidRefName,
  681. name),
  682. revstr);
  683. Ref ref = findRef(name);
  684. name = null;
  685. if (ref == null)
  686. return null;
  687. if (ref.isSymbolic())
  688. ref = ref.getLeaf();
  689. name = ref.getName();
  690. RemoteConfig remoteConfig;
  691. try {
  692. remoteConfig = new RemoteConfig(getConfig(),
  693. "origin"); //$NON-NLS-1$
  694. } catch (URISyntaxException e) {
  695. throw new RevisionSyntaxException(revstr);
  696. }
  697. String remoteBranchName = getConfig()
  698. .getString(
  699. ConfigConstants.CONFIG_BRANCH_SECTION,
  700. Repository.shortenRefName(ref.getName()),
  701. ConfigConstants.CONFIG_KEY_MERGE);
  702. List<RefSpec> fetchRefSpecs = remoteConfig
  703. .getFetchRefSpecs();
  704. for (RefSpec refSpec : fetchRefSpecs) {
  705. if (refSpec.matchSource(remoteBranchName)) {
  706. RefSpec expandFromSource = refSpec
  707. .expandFromSource(remoteBranchName);
  708. name = expandFromSource.getDestination();
  709. break;
  710. }
  711. }
  712. if (name == null)
  713. throw new RevisionSyntaxException(revstr);
  714. } else if (time.matches("^-\\d+$")) { //$NON-NLS-1$
  715. if (name != null)
  716. throw new RevisionSyntaxException(revstr);
  717. else {
  718. String previousCheckout = resolveReflogCheckout(-Integer
  719. .parseInt(time));
  720. if (ObjectId.isId(previousCheckout))
  721. rev = parseSimple(rw, previousCheckout);
  722. else
  723. name = previousCheckout;
  724. }
  725. } else {
  726. if (name == null)
  727. name = new String(revChars, done, i);
  728. if (name.equals("")) //$NON-NLS-1$
  729. name = Constants.HEAD;
  730. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  731. throw new RevisionSyntaxException(MessageFormat
  732. .format(JGitText.get().invalidRefName,
  733. name),
  734. revstr);
  735. Ref ref = findRef(name);
  736. name = null;
  737. if (ref == null)
  738. return null;
  739. // @{n} means current branch, not HEAD@{1} unless
  740. // detached
  741. if (ref.isSymbolic())
  742. ref = ref.getLeaf();
  743. rev = resolveReflog(rw, ref, time);
  744. }
  745. i = m;
  746. } else
  747. throw new RevisionSyntaxException(revstr);
  748. break;
  749. case ':': {
  750. RevTree tree;
  751. if (rev == null) {
  752. if (name == null)
  753. name = new String(revChars, done, i);
  754. if (name.equals("")) //$NON-NLS-1$
  755. name = Constants.HEAD;
  756. rev = parseSimple(rw, name);
  757. name = null;
  758. }
  759. if (rev == null)
  760. return null;
  761. tree = rw.parseTree(rev);
  762. if (i == revChars.length - 1)
  763. return tree.copy();
  764. TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(),
  765. new String(revChars, i + 1, revChars.length - i - 1),
  766. tree);
  767. return tw != null ? tw.getObjectId(0) : null;
  768. }
  769. default:
  770. if (rev != null)
  771. throw new RevisionSyntaxException(revstr);
  772. }
  773. }
  774. if (rev != null)
  775. return rev.copy();
  776. if (name != null)
  777. return name;
  778. if (done == revstr.length())
  779. return null;
  780. name = revstr.substring(done);
  781. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  782. throw new RevisionSyntaxException(
  783. MessageFormat.format(JGitText.get().invalidRefName, name),
  784. revstr);
  785. if (findRef(name) != null)
  786. return name;
  787. return resolveSimple(name);
  788. }
  789. private static boolean isHex(char c) {
  790. return ('0' <= c && c <= '9') //
  791. || ('a' <= c && c <= 'f') //
  792. || ('A' <= c && c <= 'F');
  793. }
  794. private static boolean isAllHex(String str, int ptr) {
  795. while (ptr < str.length()) {
  796. if (!isHex(str.charAt(ptr++)))
  797. return false;
  798. }
  799. return true;
  800. }
  801. @Nullable
  802. private RevObject parseSimple(RevWalk rw, String revstr) throws IOException {
  803. ObjectId id = resolveSimple(revstr);
  804. return id != null ? rw.parseAny(id) : null;
  805. }
  806. @Nullable
  807. private ObjectId resolveSimple(String revstr) throws IOException {
  808. if (ObjectId.isId(revstr))
  809. return ObjectId.fromString(revstr);
  810. if (Repository.isValidRefName("x/" + revstr)) { //$NON-NLS-1$
  811. Ref r = getRefDatabase().findRef(revstr);
  812. if (r != null)
  813. return r.getObjectId();
  814. }
  815. if (AbbreviatedObjectId.isId(revstr))
  816. return resolveAbbreviation(revstr);
  817. int dashg = revstr.indexOf("-g"); //$NON-NLS-1$
  818. if ((dashg + 5) < revstr.length() && 0 <= dashg
  819. && isHex(revstr.charAt(dashg + 2))
  820. && isHex(revstr.charAt(dashg + 3))
  821. && isAllHex(revstr, dashg + 4)) {
  822. // Possibly output from git describe?
  823. String s = revstr.substring(dashg + 2);
  824. if (AbbreviatedObjectId.isId(s))
  825. return resolveAbbreviation(s);
  826. }
  827. return null;
  828. }
  829. @Nullable
  830. private String resolveReflogCheckout(int checkoutNo)
  831. throws IOException {
  832. ReflogReader reader = getReflogReader(Constants.HEAD);
  833. if (reader == null) {
  834. return null;
  835. }
  836. List<ReflogEntry> reflogEntries = reader.getReverseEntries();
  837. for (ReflogEntry entry : reflogEntries) {
  838. CheckoutEntry checkout = entry.parseCheckout();
  839. if (checkout != null)
  840. if (checkoutNo-- == 1)
  841. return checkout.getFromBranch();
  842. }
  843. return null;
  844. }
  845. private RevCommit resolveReflog(RevWalk rw, Ref ref, String time)
  846. throws IOException {
  847. int number;
  848. try {
  849. number = Integer.parseInt(time);
  850. } catch (NumberFormatException nfe) {
  851. throw new RevisionSyntaxException(MessageFormat.format(
  852. JGitText.get().invalidReflogRevision, time));
  853. }
  854. assert number >= 0;
  855. ReflogReader reader = getReflogReader(ref.getName());
  856. if (reader == null) {
  857. throw new RevisionSyntaxException(
  858. MessageFormat.format(JGitText.get().reflogEntryNotFound,
  859. Integer.valueOf(number), ref.getName()));
  860. }
  861. ReflogEntry entry = reader.getReverseEntry(number);
  862. if (entry == null)
  863. throw new RevisionSyntaxException(MessageFormat.format(
  864. JGitText.get().reflogEntryNotFound,
  865. Integer.valueOf(number), ref.getName()));
  866. return rw.parseCommit(entry.getNewId());
  867. }
  868. @Nullable
  869. private ObjectId resolveAbbreviation(String revstr) throws IOException,
  870. AmbiguousObjectException {
  871. AbbreviatedObjectId id = AbbreviatedObjectId.fromString(revstr);
  872. try (ObjectReader reader = newObjectReader()) {
  873. Collection<ObjectId> matches = reader.resolve(id);
  874. if (matches.size() == 0)
  875. return null;
  876. else if (matches.size() == 1)
  877. return matches.iterator().next();
  878. else
  879. throw new AmbiguousObjectException(id, matches);
  880. }
  881. }
  882. /**
  883. * Increment the use counter by one, requiring a matched {@link #close()}.
  884. */
  885. public void incrementOpen() {
  886. useCnt.incrementAndGet();
  887. }
  888. /**
  889. * {@inheritDoc}
  890. * <p>
  891. * Decrement the use count, and maybe close resources.
  892. */
  893. @Override
  894. public void close() {
  895. int newCount = useCnt.decrementAndGet();
  896. if (newCount == 0) {
  897. if (RepositoryCache.isCached(this)) {
  898. closedAt.set(System.currentTimeMillis());
  899. } else {
  900. doClose();
  901. }
  902. } else if (newCount == -1) {
  903. // should not happen, only log when useCnt became negative to
  904. // minimize number of log entries
  905. String message = MessageFormat.format(JGitText.get().corruptUseCnt,
  906. toString());
  907. if (LOG.isDebugEnabled()) {
  908. LOG.debug(message, new IllegalStateException());
  909. } else {
  910. LOG.warn(message);
  911. }
  912. if (RepositoryCache.isCached(this)) {
  913. closedAt.set(System.currentTimeMillis());
  914. }
  915. }
  916. }
  917. /**
  918. * Invoked when the use count drops to zero during {@link #close()}.
  919. * <p>
  920. * The default implementation closes the object and ref databases.
  921. */
  922. protected void doClose() {
  923. getObjectDatabase().close();
  924. getRefDatabase().close();
  925. }
  926. /** {@inheritDoc} */
  927. @Override
  928. @NonNull
  929. public String toString() {
  930. String desc;
  931. File directory = getDirectory();
  932. if (directory != null)
  933. desc = directory.getPath();
  934. else
  935. desc = getClass().getSimpleName() + "-" //$NON-NLS-1$
  936. + System.identityHashCode(this);
  937. return "Repository[" + desc + "]"; //$NON-NLS-1$ //$NON-NLS-2$
  938. }
  939. /**
  940. * Get the name of the reference that {@code HEAD} points to.
  941. * <p>
  942. * This is essentially the same as doing:
  943. *
  944. * <pre>
  945. * return exactRef(Constants.HEAD).getTarget().getName()
  946. * </pre>
  947. *
  948. * Except when HEAD is detached, in which case this method returns the
  949. * current ObjectId in hexadecimal string format.
  950. *
  951. * @return name of current branch (for example {@code refs/heads/master}),
  952. * an ObjectId in hex format if the current branch is detached, or
  953. * {@code null} if the repository is corrupt and has no HEAD
  954. * reference.
  955. * @throws java.io.IOException
  956. */
  957. @Nullable
  958. public String getFullBranch() throws IOException {
  959. Ref head = exactRef(Constants.HEAD);
  960. if (head == null) {
  961. return null;
  962. }
  963. if (head.isSymbolic()) {
  964. return head.getTarget().getName();
  965. }
  966. ObjectId objectId = head.getObjectId();
  967. if (objectId != null) {
  968. return objectId.name();
  969. }
  970. return null;
  971. }
  972. /**
  973. * Get the short name of the current branch that {@code HEAD} points to.
  974. * <p>
  975. * This is essentially the same as {@link #getFullBranch()}, except the
  976. * leading prefix {@code refs/heads/} is removed from the reference before
  977. * it is returned to the caller.
  978. *
  979. * @return name of current branch (for example {@code master}), an ObjectId
  980. * in hex format if the current branch is detached, or {@code null}
  981. * if the repository is corrupt and has no HEAD reference.
  982. * @throws java.io.IOException
  983. */
  984. @Nullable
  985. public String getBranch() throws IOException {
  986. String name = getFullBranch();
  987. if (name != null)
  988. return shortenRefName(name);
  989. return null;
  990. }
  991. /**
  992. * Objects known to exist but not expressed by {@link #getAllRefs()}.
  993. * <p>
  994. * When a repository borrows objects from another repository, it can
  995. * advertise that it safely has that other repository's references, without
  996. * exposing any other details about the other repository. This may help
  997. * a client trying to push changes avoid pushing more than it needs to.
  998. *
  999. * @return unmodifiable collection of other known objects.
  1000. */
  1001. @NonNull
  1002. public Set<ObjectId> getAdditionalHaves() {
  1003. return Collections.emptySet();
  1004. }
  1005. /**
  1006. * Get a ref by name.
  1007. *
  1008. * @param name
  1009. * the name of the ref to lookup. Must not be a short-hand
  1010. * form; e.g., "master" is not automatically expanded to
  1011. * "refs/heads/master".
  1012. * @return the Ref with the given name, or {@code null} if it does not exist
  1013. * @throws java.io.IOException
  1014. * @since 4.2
  1015. */
  1016. @Nullable
  1017. public final Ref exactRef(String name) throws IOException {
  1018. return getRefDatabase().exactRef(name);
  1019. }
  1020. /**
  1021. * Search for a ref by (possibly abbreviated) name.
  1022. *
  1023. * @param name
  1024. * the name of the ref to lookup. May be a short-hand form, e.g.
  1025. * "master" which is automatically expanded to
  1026. * "refs/heads/master" if "refs/heads/master" already exists.
  1027. * @return the Ref with the given name, or {@code null} if it does not exist
  1028. * @throws java.io.IOException
  1029. * @since 4.2
  1030. */
  1031. @Nullable
  1032. public final Ref findRef(String name) throws IOException {
  1033. return getRefDatabase().findRef(name);
  1034. }
  1035. /**
  1036. * Get mutable map of all known refs, including symrefs like HEAD that may
  1037. * not point to any object yet.
  1038. *
  1039. * @return mutable map of all known refs (heads, tags, remotes).
  1040. * @deprecated use {@code getRefDatabase().getRefs()} instead.
  1041. */
  1042. @Deprecated
  1043. @NonNull
  1044. public Map<String, Ref> getAllRefs() {
  1045. try {
  1046. return getRefDatabase().getRefs(RefDatabase.ALL);
  1047. } catch (IOException e) {
  1048. throw new UncheckedIOException(e);
  1049. }
  1050. }
  1051. /**
  1052. * Get mutable map of all tags
  1053. *
  1054. * @return mutable map of all tags; key is short tag name ("v1.0") and value
  1055. * of the entry contains the ref with the full tag name
  1056. * ("refs/tags/v1.0").
  1057. * @deprecated use {@code getRefDatabase().getRefsByPrefix(R_TAGS)} instead
  1058. */
  1059. @Deprecated
  1060. @NonNull
  1061. public Map<String, Ref> getTags() {
  1062. try {
  1063. return getRefDatabase().getRefs(Constants.R_TAGS);
  1064. } catch (IOException e) {
  1065. throw new UncheckedIOException(e);
  1066. }
  1067. }
  1068. /**
  1069. * Peel a possibly unpeeled reference to an annotated tag.
  1070. * <p>
  1071. * If the ref cannot be peeled (as it does not refer to an annotated tag)
  1072. * the peeled id stays null, but {@link org.eclipse.jgit.lib.Ref#isPeeled()}
  1073. * will be true.
  1074. *
  1075. * @param ref
  1076. * The ref to peel
  1077. * @return <code>ref</code> if <code>ref.isPeeled()</code> is true; else a
  1078. * new Ref object representing the same data as Ref, but isPeeled()
  1079. * will be true and getPeeledObjectId will contain the peeled object
  1080. * (or null).
  1081. * @deprecated use {@code getRefDatabase().peel(ref)} instead.
  1082. */
  1083. @Deprecated
  1084. @NonNull
  1085. public Ref peel(Ref ref) {
  1086. try {
  1087. return getRefDatabase().peel(ref);
  1088. } catch (IOException e) {
  1089. // Historical accident; if the reference cannot be peeled due
  1090. // to some sort of repository access problem we claim that the
  1091. // same as if the reference was not an annotated tag.
  1092. return ref;
  1093. }
  1094. }
  1095. /**
  1096. * Get a map with all objects referenced by a peeled ref.
  1097. *
  1098. * @return a map with all objects referenced by a peeled ref.
  1099. */
  1100. @NonNull
  1101. public Map<AnyObjectId, Set<Ref>> getAllRefsByPeeledObjectId() {
  1102. Map<String, Ref> allRefs = getAllRefs();
  1103. Map<AnyObjectId, Set<Ref>> ret = new HashMap<>(allRefs.size());
  1104. for (Ref ref : allRefs.values()) {
  1105. ref = peel(ref);
  1106. AnyObjectId target = ref.getPeeledObjectId();
  1107. if (target == null)
  1108. target = ref.getObjectId();
  1109. // We assume most Sets here are singletons
  1110. Set<Ref> oset = ret.put(target, Collections.singleton(ref));
  1111. if (oset != null) {
  1112. // that was not the case (rare)
  1113. if (oset.size() == 1) {
  1114. // Was a read-only singleton, we must copy to a new Set
  1115. oset = new HashSet<>(oset);
  1116. }
  1117. ret.put(target, oset);
  1118. oset.add(ref);
  1119. }
  1120. }
  1121. return ret;
  1122. }
  1123. /**
  1124. * Get the index file location or {@code null} if repository isn't local.
  1125. *
  1126. * @return the index file location or {@code null} if repository isn't
  1127. * local.
  1128. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1129. * if this is bare, which implies it has no working directory.
  1130. * See {@link #isBare()}.
  1131. */
  1132. @NonNull
  1133. public File getIndexFile() throws NoWorkTreeException {
  1134. if (isBare())
  1135. throw new NoWorkTreeException();
  1136. return indexFile;
  1137. }
  1138. /**
  1139. * Locate a reference to a commit and immediately parse its content.
  1140. * <p>
  1141. * This method only returns successfully if the commit object exists,
  1142. * is verified to be a commit, and was parsed without error.
  1143. *
  1144. * @param id
  1145. * name of the commit object.
  1146. * @return reference to the commit object. Never null.
  1147. * @throws org.eclipse.jgit.errors.MissingObjectException
  1148. * the supplied commit does not exist.
  1149. * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
  1150. * the supplied id is not a commit or an annotated tag.
  1151. * @throws java.io.IOException
  1152. * a pack file or loose object could not be read.
  1153. * @since 4.8
  1154. */
  1155. public RevCommit parseCommit(AnyObjectId id) throws IncorrectObjectTypeException,
  1156. IOException, MissingObjectException {
  1157. if (id instanceof RevCommit && ((RevCommit) id).getRawBuffer() != null) {
  1158. return (RevCommit) id;
  1159. }
  1160. try (RevWalk walk = new RevWalk(this)) {
  1161. return walk.parseCommit(id);
  1162. }
  1163. }
  1164. /**
  1165. * Create a new in-core index representation and read an index from disk.
  1166. * <p>
  1167. * The new index will be read before it is returned to the caller. Read
  1168. * failures are reported as exceptions and therefore prevent the method from
  1169. * returning a partially populated index.
  1170. *
  1171. * @return a cache representing the contents of the specified index file (if
  1172. * it exists) or an empty cache if the file does not exist.
  1173. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1174. * if this is bare, which implies it has no working directory.
  1175. * See {@link #isBare()}.
  1176. * @throws java.io.IOException
  1177. * the index file is present but could not be read.
  1178. * @throws org.eclipse.jgit.errors.CorruptObjectException
  1179. * the index file is using a format or extension that this
  1180. * library does not support.
  1181. */
  1182. @NonNull
  1183. public DirCache readDirCache() throws NoWorkTreeException,
  1184. CorruptObjectException, IOException {
  1185. return DirCache.read(this);
  1186. }
  1187. /**
  1188. * Create a new in-core index representation, lock it, and read from disk.
  1189. * <p>
  1190. * The new index will be locked and then read before it is returned to the
  1191. * caller. Read failures are reported as exceptions and therefore prevent
  1192. * the method from returning a partially populated index.
  1193. *
  1194. * @return a cache representing the contents of the specified index file (if
  1195. * it exists) or an empty cache if the file does not exist.
  1196. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1197. * if this is bare, which implies it has no working directory.
  1198. * See {@link #isBare()}.
  1199. * @throws java.io.IOException
  1200. * the index file is present but could not be read, or the lock
  1201. * could not be obtained.
  1202. * @throws org.eclipse.jgit.errors.CorruptObjectException
  1203. * the index file is using a format or extension that this
  1204. * library does not support.
  1205. */
  1206. @NonNull
  1207. public DirCache lockDirCache() throws NoWorkTreeException,
  1208. CorruptObjectException, IOException {
  1209. // we want DirCache to inform us so that we can inform registered
  1210. // listeners about index changes
  1211. IndexChangedListener l = new IndexChangedListener() {
  1212. @Override
  1213. public void onIndexChanged(IndexChangedEvent event) {
  1214. notifyIndexChanged(true);
  1215. }
  1216. };
  1217. return DirCache.lock(this, l);
  1218. }
  1219. /**
  1220. * Get the repository state
  1221. *
  1222. * @return the repository state
  1223. */
  1224. @NonNull
  1225. public RepositoryState getRepositoryState() {
  1226. if (isBare() || getDirectory() == null)
  1227. return RepositoryState.BARE;
  1228. // Pre Git-1.6 logic
  1229. if (new File(getWorkTree(), ".dotest").exists()) //$NON-NLS-1$
  1230. return RepositoryState.REBASING;
  1231. if (new File(getDirectory(), ".dotest-merge").exists()) //$NON-NLS-1$
  1232. return RepositoryState.REBASING_INTERACTIVE;
  1233. // From 1.6 onwards
  1234. if (new File(getDirectory(),"rebase-apply/rebasing").exists()) //$NON-NLS-1$
  1235. return RepositoryState.REBASING_REBASING;
  1236. if (new File(getDirectory(),"rebase-apply/applying").exists()) //$NON-NLS-1$
  1237. return RepositoryState.APPLY;
  1238. if (new File(getDirectory(),"rebase-apply").exists()) //$NON-NLS-1$
  1239. return RepositoryState.REBASING;
  1240. if (new File(getDirectory(),"rebase-merge/interactive").exists()) //$NON-NLS-1$
  1241. return RepositoryState.REBASING_INTERACTIVE;
  1242. if (new File(getDirectory(),"rebase-merge").exists()) //$NON-NLS-1$
  1243. return RepositoryState.REBASING_MERGE;
  1244. // Both versions
  1245. if (new File(getDirectory(), Constants.MERGE_HEAD).exists()) {
  1246. // we are merging - now check whether we have unmerged paths
  1247. try {
  1248. if (!readDirCache().hasUnmergedPaths()) {
  1249. // no unmerged paths -> return the MERGING_RESOLVED state
  1250. return RepositoryState.MERGING_RESOLVED;
  1251. }
  1252. } catch (IOException e) {
  1253. throw new UncheckedIOException(e);
  1254. }
  1255. return RepositoryState.MERGING;
  1256. }
  1257. if (new File(getDirectory(), "BISECT_LOG").exists()) //$NON-NLS-1$
  1258. return RepositoryState.BISECTING;
  1259. if (new File(getDirectory(), Constants.CHERRY_PICK_HEAD).exists()) {
  1260. try {
  1261. if (!readDirCache().hasUnmergedPaths()) {
  1262. // no unmerged paths
  1263. return RepositoryState.CHERRY_PICKING_RESOLVED;
  1264. }
  1265. } catch (IOException e) {
  1266. throw new UncheckedIOException(e);
  1267. }
  1268. return RepositoryState.CHERRY_PICKING;
  1269. }
  1270. if (new File(getDirectory(), Constants.REVERT_HEAD).exists()) {
  1271. try {
  1272. if (!readDirCache().hasUnmergedPaths()) {
  1273. // no unmerged paths
  1274. return RepositoryState.REVERTING_RESOLVED;
  1275. }
  1276. } catch (IOException e) {
  1277. throw new UncheckedIOException(e);
  1278. }
  1279. return RepositoryState.REVERTING;
  1280. }
  1281. return RepositoryState.SAFE;
  1282. }
  1283. /**
  1284. * Check validity of a ref name. It must not contain character that has
  1285. * a special meaning in a Git object reference expression. Some other
  1286. * dangerous characters are also excluded.
  1287. *
  1288. * For portability reasons '\' is excluded
  1289. *
  1290. * @param refName a {@link java.lang.String} object.
  1291. * @return true if refName is a valid ref name
  1292. */
  1293. public static boolean isValidRefName(String refName) {
  1294. final int len = refName.length();
  1295. if (len == 0) {
  1296. return false;
  1297. }
  1298. if (refName.endsWith(LOCK_SUFFIX)) {
  1299. return false;
  1300. }
  1301. // Refs may be stored as loose files so invalid paths
  1302. // on the local system must also be invalid refs.
  1303. try {
  1304. SystemReader.getInstance().checkPath(refName);
  1305. } catch (CorruptObjectException e) {
  1306. return false;
  1307. }
  1308. int components = 1;
  1309. char p = '\0';
  1310. for (int i = 0; i < len; i++) {
  1311. final char c = refName.charAt(i);
  1312. if (c <= ' ')
  1313. return false;
  1314. switch (c) {
  1315. case '.':
  1316. switch (p) {
  1317. case '\0': case '/': case '.':
  1318. return false;
  1319. }
  1320. if (i == len -1)
  1321. return false;
  1322. break;
  1323. case '/':
  1324. if (i == 0 || i == len - 1)
  1325. return false;
  1326. if (p == '/')
  1327. return false;
  1328. components++;
  1329. break;
  1330. case '{':
  1331. if (p == '@')
  1332. return false;
  1333. break;
  1334. case '~': case '^': case ':':
  1335. case '?': case '[': case '*':
  1336. case '\\':
  1337. case '\u007F':
  1338. return false;
  1339. }
  1340. p = c;
  1341. }
  1342. return components > 1;
  1343. }
  1344. /**
  1345. * Normalizes the passed branch name into a possible valid branch name. The
  1346. * validity of the returned name should be checked by a subsequent call to
  1347. * {@link #isValidRefName(String)}.
  1348. * <p>
  1349. * Future implementations of this method could be more restrictive or more
  1350. * lenient about the validity of specific characters in the returned name.
  1351. * <p>
  1352. * The current implementation returns the trimmed input string if this is
  1353. * already a valid branch name. Otherwise it returns a trimmed string with
  1354. * special characters not allowed by {@link #isValidRefName(String)}
  1355. * replaced by hyphens ('-') and blanks replaced by underscores ('_').
  1356. * Leading and trailing slashes, dots, hyphens, and underscores are removed.
  1357. *
  1358. * @param name
  1359. * to normalize
  1360. * @return The normalized name or an empty String if it is {@code null} or
  1361. * empty.
  1362. * @since 4.7
  1363. * @see #isValidRefName(String)
  1364. */
  1365. public static String normalizeBranchName(String name) {
  1366. if (name == null || name.isEmpty()) {
  1367. return ""; //$NON-NLS-1$
  1368. }
  1369. String result = name.trim();
  1370. String fullName = result.startsWith(Constants.R_HEADS) ? result
  1371. : Constants.R_HEADS + result;
  1372. if (isValidRefName(fullName)) {
  1373. return result;
  1374. }
  1375. // All Unicode blanks to underscore
  1376. result = result.replaceAll("(?:\\h|\\v)+", "_"); //$NON-NLS-1$ //$NON-NLS-2$
  1377. StringBuilder b = new StringBuilder();
  1378. char p = '/';
  1379. for (int i = 0, len = result.length(); i < len; i++) {
  1380. char c = result.charAt(i);
  1381. if (c < ' ' || c == 127) {
  1382. continue;
  1383. }
  1384. // Substitute a dash for problematic characters
  1385. switch (c) {
  1386. case '\\':
  1387. case '^':
  1388. case '~':
  1389. case ':':
  1390. case '?':
  1391. case '*':
  1392. case '[':
  1393. case '@':
  1394. case '<':
  1395. case '>':
  1396. case '|':
  1397. case '"':
  1398. c = '-';
  1399. break;
  1400. default:
  1401. break;
  1402. }
  1403. // Collapse multiple slashes, dashes, dots, underscores, and omit
  1404. // dashes, dots, and underscores following a slash.
  1405. switch (c) {
  1406. case '/':
  1407. if (p == '/') {
  1408. continue;
  1409. }
  1410. p = '/';
  1411. break;
  1412. case '.':
  1413. case '_':
  1414. case '-':
  1415. if (p == '/' || p == '-') {
  1416. continue;
  1417. }
  1418. p = '-';
  1419. break;
  1420. default:
  1421. p = c;
  1422. break;
  1423. }
  1424. b.append(c);
  1425. }
  1426. // Strip trailing special characters, and avoid the .lock extension
  1427. result = b.toString().replaceFirst("[/_.-]+$", "") //$NON-NLS-1$ //$NON-NLS-2$
  1428. .replaceAll("\\.lock($|/)", "_lock$1"); //$NON-NLS-1$ //$NON-NLS-2$
  1429. return FORBIDDEN_BRANCH_NAME_COMPONENTS.matcher(result)
  1430. .replaceAll("$1+$2$3"); //$NON-NLS-1$
  1431. }
  1432. /**
  1433. * Strip work dir and return normalized repository path.
  1434. *
  1435. * @param workDir
  1436. * Work dir
  1437. * @param file
  1438. * File whose path shall be stripped of its workdir
  1439. * @return normalized repository relative path or the empty string if the
  1440. * file is not relative to the work directory.
  1441. */
  1442. @NonNull
  1443. public static String stripWorkDir(File workDir, File file) {
  1444. final String filePath = file.getPath();
  1445. final String workDirPath = workDir.getPath();
  1446. if (filePath.length() <= workDirPath.length() ||
  1447. filePath.charAt(workDirPath.length()) != File.separatorChar ||
  1448. !filePath.startsWith(workDirPath)) {
  1449. File absWd = workDir.isAbsolute() ? workDir : workDir.getAbsoluteFile();
  1450. File absFile = file.isAbsolute() ? file : file.getAbsoluteFile();
  1451. if (absWd == workDir && absFile == file)
  1452. return ""; //$NON-NLS-1$
  1453. return stripWorkDir(absWd, absFile);
  1454. }
  1455. String relName = filePath.substring(workDirPath.length() + 1);
  1456. if (File.separatorChar != '/')
  1457. relName = relName.replace(File.separatorChar, '/');
  1458. return relName;
  1459. }
  1460. /**
  1461. * Whether this repository is bare
  1462. *
  1463. * @return true if this is bare, which implies it has no working directory.
  1464. */
  1465. public boolean isBare() {
  1466. return workTree == null;
  1467. }
  1468. /**
  1469. * Get the root directory of the working tree, where files are checked out
  1470. * for viewing and editing.
  1471. *
  1472. * @return the root directory of the working tree, where files are checked
  1473. * out for viewing and editing.
  1474. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1475. * if this is bare, which implies it has no working directory.
  1476. * See {@link #isBare()}.
  1477. */
  1478. @NonNull
  1479. public File getWorkTree() throws NoWorkTreeException {
  1480. if (isBare())
  1481. throw new NoWorkTreeException();
  1482. return workTree;
  1483. }
  1484. /**
  1485. * Force a scan for changed refs. Fires an IndexChangedEvent(false) if
  1486. * changes are detected.
  1487. *
  1488. * @throws java.io.IOException
  1489. */
  1490. public abstract void scanForRepoChanges() throws IOException;
  1491. /**
  1492. * Notify that the index changed by firing an IndexChangedEvent.
  1493. *
  1494. * @param internal
  1495. * {@code true} if the index was changed by the same
  1496. * JGit process
  1497. * @since 5.0
  1498. */
  1499. public abstract void notifyIndexChanged(boolean internal);
  1500. /**
  1501. * Get a shortened more user friendly ref name
  1502. *
  1503. * @param refName
  1504. * a {@link java.lang.String} object.
  1505. * @return a more user friendly ref name
  1506. */
  1507. @NonNull
  1508. public static String shortenRefName(String refName) {
  1509. if (refName.startsWith(Constants.R_HEADS))
  1510. return refName.substring(Constants.R_HEADS.length());
  1511. if (refName.startsWith(Constants.R_TAGS))
  1512. return refName.substring(Constants.R_TAGS.length());
  1513. if (refName.startsWith(Constants.R_REMOTES))
  1514. return refName.substring(Constants.R_REMOTES.length());
  1515. return refName;
  1516. }
  1517. /**
  1518. * Get a shortened more user friendly remote tracking branch name
  1519. *
  1520. * @param refName
  1521. * a {@link java.lang.String} object.
  1522. * @return the remote branch name part of <code>refName</code>, i.e. without
  1523. * the <code>refs/remotes/&lt;remote&gt;</code> prefix, if
  1524. * <code>refName</code> represents a remote tracking branch;
  1525. * otherwise {@code null}.
  1526. * @since 3.4
  1527. */
  1528. @Nullable
  1529. public String shortenRemoteBranchName(String refName) {
  1530. for (String remote : getRemoteNames()) {
  1531. String remotePrefix = Constants.R_REMOTES + remote + "/"; //$NON-NLS-1$
  1532. if (refName.startsWith(remotePrefix))
  1533. return refName.substring(remotePrefix.length());
  1534. }
  1535. return null;
  1536. }
  1537. /**
  1538. * Get remote name
  1539. *
  1540. * @param refName
  1541. * a {@link java.lang.String} object.
  1542. * @return the remote name part of <code>refName</code>, i.e. without the
  1543. * <code>refs/remotes/&lt;remote&gt;</code> prefix, if
  1544. * <code>refName</code> represents a remote tracking branch;
  1545. * otherwise {@code null}.
  1546. * @since 3.4
  1547. */
  1548. @Nullable
  1549. public String getRemoteName(String refName) {
  1550. for (String remote : getRemoteNames()) {
  1551. String remotePrefix = Constants.R_REMOTES + remote + "/"; //$NON-NLS-1$
  1552. if (refName.startsWith(remotePrefix))
  1553. return remote;
  1554. }
  1555. return null;
  1556. }
  1557. /**
  1558. * Read the {@code GIT_DIR/description} file for gitweb.
  1559. *
  1560. * @return description text; null if no description has been configured.
  1561. * @throws java.io.IOException
  1562. * description cannot be accessed.
  1563. * @since 4.6
  1564. */
  1565. @Nullable
  1566. public String getGitwebDescription() throws IOException {
  1567. return null;
  1568. }
  1569. /**
  1570. * Set the {@code GIT_DIR/description} file for gitweb.
  1571. *
  1572. * @param description
  1573. * new description; null to clear the description.
  1574. * @throws java.io.IOException
  1575. * description cannot be persisted.
  1576. * @since 4.6
  1577. */
  1578. public void setGitwebDescription(@Nullable String description)
  1579. throws IOException {
  1580. throw new IOException(JGitText.get().unsupportedRepositoryDescription);
  1581. }
  1582. /**
  1583. * Get the reflog reader
  1584. *
  1585. * @param refName
  1586. * a {@link java.lang.String} object.
  1587. * @return a {@link org.eclipse.jgit.lib.ReflogReader} for the supplied
  1588. * refname, or {@code null} if the named ref does not exist.
  1589. * @throws java.io.IOException
  1590. * the ref could not be accessed.
  1591. * @since 3.0
  1592. */
  1593. @Nullable
  1594. public abstract ReflogReader getReflogReader(String refName)
  1595. throws IOException;
  1596. /**
  1597. * Return the information stored in the file $GIT_DIR/MERGE_MSG. In this
  1598. * file operations triggering a merge will store a template for the commit
  1599. * message of the merge commit.
  1600. *
  1601. * @return a String containing the content of the MERGE_MSG file or
  1602. * {@code null} if this file doesn't exist
  1603. * @throws java.io.IOException
  1604. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1605. * if this is bare, which implies it has no working directory.
  1606. * See {@link #isBare()}.
  1607. */
  1608. @Nullable
  1609. public String readMergeCommitMsg() throws IOException, NoWorkTreeException {
  1610. return readCommitMsgFile(Constants.MERGE_MSG);
  1611. }
  1612. /**
  1613. * Write new content to the file $GIT_DIR/MERGE_MSG. In this file operations
  1614. * triggering a merge will store a template for the commit message of the
  1615. * merge commit. If <code>null</code> is specified as message the file will
  1616. * be deleted.
  1617. *
  1618. * @param msg
  1619. * the message which should be written or <code>null</code> to
  1620. * delete the file
  1621. * @throws java.io.IOException
  1622. */
  1623. public void writeMergeCommitMsg(String msg) throws IOException {
  1624. File mergeMsgFile = new File(gitDir, Constants.MERGE_MSG);
  1625. writeCommitMsg(mergeMsgFile, msg);
  1626. }
  1627. /**
  1628. * Return the information stored in the file $GIT_DIR/COMMIT_EDITMSG. In
  1629. * this file hooks triggered by an operation may read or modify the current
  1630. * commit message.
  1631. *
  1632. * @return a String containing the content of the COMMIT_EDITMSG file or
  1633. * {@code null} if this file doesn't exist
  1634. * @throws java.io.IOException
  1635. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1636. * if this is bare, which implies it has no working directory.
  1637. * See {@link #isBare()}.
  1638. * @since 4.0
  1639. */
  1640. @Nullable
  1641. public String readCommitEditMsg() throws IOException, NoWorkTreeException {
  1642. return readCommitMsgFile(Constants.COMMIT_EDITMSG);
  1643. }
  1644. /**
  1645. * Write new content to the file $GIT_DIR/COMMIT_EDITMSG. In this file hooks
  1646. * triggered by an operation may read or modify the current commit message.
  1647. * If {@code null} is specified as message the file will be deleted.
  1648. *
  1649. * @param msg
  1650. * the message which should be written or {@code null} to delete
  1651. * the file
  1652. * @throws java.io.IOException
  1653. * @since 4.0
  1654. */
  1655. public void writeCommitEditMsg(String msg) throws IOException {
  1656. File commiEditMsgFile = new File(gitDir, Constants.COMMIT_EDITMSG);
  1657. writeCommitMsg(commiEditMsgFile, msg);
  1658. }
  1659. /**
  1660. * Return the information stored in the file $GIT_DIR/MERGE_HEAD. In this
  1661. * file operations triggering a merge will store the IDs of all heads which
  1662. * should be merged together with HEAD.
  1663. *
  1664. * @return a list of commits which IDs are listed in the MERGE_HEAD file or
  1665. * {@code null} if this file doesn't exist. Also if the file exists
  1666. * but is empty {@code null} will be returned
  1667. * @throws java.io.IOException
  1668. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1669. * if this is bare, which implies it has no working directory.
  1670. * See {@link #isBare()}.
  1671. */
  1672. @Nullable
  1673. public List<ObjectId> readMergeHeads() throws IOException, NoWorkTreeException {
  1674. if (isBare() || getDirectory() == null)
  1675. throw new NoWorkTreeException();
  1676. byte[] raw = readGitDirectoryFile(Constants.MERGE_HEAD);
  1677. if (raw == null)
  1678. return null;
  1679. LinkedList<ObjectId> heads = new LinkedList<>();
  1680. for (int p = 0; p < raw.length;) {
  1681. heads.add(ObjectId.fromString(raw, p));
  1682. p = RawParseUtils
  1683. .nextLF(raw, p + Constants.OBJECT_ID_STRING_LENGTH);
  1684. }
  1685. return heads;
  1686. }
  1687. /**
  1688. * Write new merge-heads into $GIT_DIR/MERGE_HEAD. In this file operations
  1689. * triggering a merge will store the IDs of all heads which should be merged
  1690. * together with HEAD. If <code>null</code> is specified as list of commits
  1691. * the file will be deleted
  1692. *
  1693. * @param heads
  1694. * a list of commits which IDs should be written to
  1695. * $GIT_DIR/MERGE_HEAD or <code>null</code> to delete the file
  1696. * @throws java.io.IOException
  1697. */
  1698. public void writeMergeHeads(List<? extends ObjectId> heads) throws IOException {
  1699. writeHeadsFile(heads, Constants.MERGE_HEAD);
  1700. }
  1701. /**
  1702. * Return the information stored in the file $GIT_DIR/CHERRY_PICK_HEAD.
  1703. *
  1704. * @return object id from CHERRY_PICK_HEAD file or {@code null} if this file
  1705. * doesn't exist. Also if the file exists but is empty {@code null}
  1706. * will be returned
  1707. * @throws java.io.IOException
  1708. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1709. * if this is bare, which implies it has no working directory.
  1710. * See {@link #isBare()}.
  1711. */
  1712. @Nullable
  1713. public ObjectId readCherryPickHead() throws IOException,
  1714. NoWorkTreeException {
  1715. if (isBare() || getDirectory() == null)
  1716. throw new NoWorkTreeException();
  1717. byte[] raw = readGitDirectoryFile(Constants.CHERRY_PICK_HEAD);
  1718. if (raw == null)
  1719. return null;
  1720. return ObjectId.fromString(raw, 0);
  1721. }
  1722. /**
  1723. * Return the information stored in the file $GIT_DIR/REVERT_HEAD.
  1724. *
  1725. * @return object id from REVERT_HEAD file or {@code null} if this file
  1726. * doesn't exist. Also if the file exists but is empty {@code null}
  1727. * will be returned
  1728. * @throws java.io.IOException
  1729. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1730. * if this is bare, which implies it has no working directory.
  1731. * See {@link #isBare()}.
  1732. */
  1733. @Nullable
  1734. public ObjectId readRevertHead() throws IOException, NoWorkTreeException {
  1735. if (isBare() || getDirectory() == null)
  1736. throw new NoWorkTreeException();
  1737. byte[] raw = readGitDirectoryFile(Constants.REVERT_HEAD);
  1738. if (raw == null)
  1739. return null;
  1740. return ObjectId.fromString(raw, 0);
  1741. }
  1742. /**
  1743. * Write cherry pick commit into $GIT_DIR/CHERRY_PICK_HEAD. This is used in
  1744. * case of conflicts to store the cherry which was tried to be picked.
  1745. *
  1746. * @param head
  1747. * an object id of the cherry commit or <code>null</code> to
  1748. * delete the file
  1749. * @throws java.io.IOException
  1750. */
  1751. public void writeCherryPickHead(ObjectId head) throws IOException {
  1752. List<ObjectId> heads = (head != null) ? Collections.singletonList(head)
  1753. : null;
  1754. writeHeadsFile(heads, Constants.CHERRY_PICK_HEAD);
  1755. }
  1756. /**
  1757. * Write revert commit into $GIT_DIR/REVERT_HEAD. This is used in case of
  1758. * conflicts to store the revert which was tried to be picked.
  1759. *
  1760. * @param head
  1761. * an object id of the revert commit or <code>null</code> to
  1762. * delete the file
  1763. * @throws java.io.IOException
  1764. */
  1765. public void writeRevertHead(ObjectId head) throws IOException {
  1766. List<ObjectId> heads = (head != null) ? Collections.singletonList(head)
  1767. : null;
  1768. writeHeadsFile(heads, Constants.REVERT_HEAD);
  1769. }
  1770. /**
  1771. * Write original HEAD commit into $GIT_DIR/ORIG_HEAD.
  1772. *
  1773. * @param head
  1774. * an object id of the original HEAD commit or <code>null</code>
  1775. * to delete the file
  1776. * @throws java.io.IOException
  1777. */
  1778. public void writeOrigHead(ObjectId head) throws IOException {
  1779. List<ObjectId> heads = head != null ? Collections.singletonList(head)
  1780. : null;
  1781. writeHeadsFile(heads, Constants.ORIG_HEAD);
  1782. }
  1783. /**
  1784. * Return the information stored in the file $GIT_DIR/ORIG_HEAD.
  1785. *
  1786. * @return object id from ORIG_HEAD file or {@code null} if this file
  1787. * doesn't exist. Also if the file exists but is empty {@code null}
  1788. * will be returned
  1789. * @throws java.io.IOException
  1790. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1791. * if this is bare, which implies it has no working directory.
  1792. * See {@link #isBare()}.
  1793. */
  1794. @Nullable
  1795. public ObjectId readOrigHead() throws IOException, NoWorkTreeException {
  1796. if (isBare() || getDirectory() == null)
  1797. throw new NoWorkTreeException();
  1798. byte[] raw = readGitDirectoryFile(Constants.ORIG_HEAD);
  1799. return raw != null ? ObjectId.fromString(raw, 0) : null;
  1800. }
  1801. /**
  1802. * Return the information stored in the file $GIT_DIR/SQUASH_MSG. In this
  1803. * file operations triggering a squashed merge will store a template for the
  1804. * commit message of the squash commit.
  1805. *
  1806. * @return a String containing the content of the SQUASH_MSG file or
  1807. * {@code null} if this file doesn't exist
  1808. * @throws java.io.IOException
  1809. * @throws NoWorkTreeException
  1810. * if this is bare, which implies it has no working directory.
  1811. * See {@link #isBare()}.
  1812. */
  1813. @Nullable
  1814. public String readSquashCommitMsg() throws IOException {
  1815. return readCommitMsgFile(Constants.SQUASH_MSG);
  1816. }
  1817. /**
  1818. * Write new content to the file $GIT_DIR/SQUASH_MSG. In this file
  1819. * operations triggering a squashed merge will store a template for the
  1820. * commit message of the squash commit. If <code>null</code> is specified as
  1821. * message the file will be deleted.
  1822. *
  1823. * @param msg
  1824. * the message which should be written or <code>null</code> to
  1825. * delete the file
  1826. * @throws java.io.IOException
  1827. */
  1828. public void writeSquashCommitMsg(String msg) throws IOException {
  1829. File squashMsgFile = new File(gitDir, Constants.SQUASH_MSG);
  1830. writeCommitMsg(squashMsgFile, msg);
  1831. }
  1832. @Nullable
  1833. private String readCommitMsgFile(String msgFilename) throws IOException {
  1834. if (isBare() || getDirectory() == null)
  1835. throw new NoWorkTreeException();
  1836. File mergeMsgFile = new File(getDirectory(), msgFilename);
  1837. try {
  1838. return RawParseUtils.decode(IO.readFully(mergeMsgFile));
  1839. } catch (FileNotFoundException e) {
  1840. if (mergeMsgFile.exists()) {
  1841. throw e;
  1842. }
  1843. // the file has disappeared in the meantime ignore it
  1844. return null;
  1845. }
  1846. }
  1847. private void writeCommitMsg(File msgFile, String msg) throws IOException {
  1848. if (msg != null) {
  1849. try (FileOutputStream fos = new FileOutputStream(msgFile)) {
  1850. fos.write(msg.getBytes(UTF_8));
  1851. }
  1852. } else {
  1853. FileUtils.delete(msgFile, FileUtils.SKIP_MISSING);
  1854. }
  1855. }
  1856. /**
  1857. * Read a file from the git directory.
  1858. *
  1859. * @param filename
  1860. * @return the raw contents or {@code null} if the file doesn't exist or is
  1861. * empty
  1862. * @throws IOException
  1863. */
  1864. private byte[] readGitDirectoryFile(String filename) throws IOException {
  1865. File file = new File(getDirectory(), filename);
  1866. try {
  1867. byte[] raw = IO.readFully(file);
  1868. return raw.length > 0 ? raw : null;
  1869. } catch (FileNotFoundException notFound) {
  1870. if (file.exists()) {
  1871. throw notFound;
  1872. }
  1873. return null;
  1874. }
  1875. }
  1876. /**
  1877. * Write the given heads to a file in the git directory.
  1878. *
  1879. * @param heads
  1880. * a list of object ids to write or null if the file should be
  1881. * deleted.
  1882. * @param filename
  1883. * @throws FileNotFoundException
  1884. * @throws IOException
  1885. */
  1886. private void writeHeadsFile(List<? extends ObjectId> heads, String filename)
  1887. throws FileNotFoundException, IOException {
  1888. File headsFile = new File(getDirectory(), filename);
  1889. if (heads != null) {
  1890. try (OutputStream bos = new BufferedOutputStream(
  1891. new FileOutputStream(headsFile))) {
  1892. for (ObjectId id : heads) {
  1893. id.copyTo(bos);
  1894. bos.write('\n');
  1895. }
  1896. }
  1897. } else {
  1898. FileUtils.delete(headsFile, FileUtils.SKIP_MISSING);
  1899. }
  1900. }
  1901. /**
  1902. * Read a file formatted like the git-rebase-todo file. The "done" file is
  1903. * also formatted like the git-rebase-todo file. These files can be found in
  1904. * .git/rebase-merge/ or .git/rebase-append/ folders.
  1905. *
  1906. * @param path
  1907. * path to the file relative to the repository's git-dir. E.g.
  1908. * "rebase-merge/git-rebase-todo" or "rebase-append/done"
  1909. * @param includeComments
  1910. * <code>true</code> if also comments should be reported
  1911. * @return the list of steps
  1912. * @throws java.io.IOException
  1913. * @since 3.2
  1914. */
  1915. @NonNull
  1916. public List<RebaseTodoLine> readRebaseTodo(String path,
  1917. boolean includeComments)
  1918. throws IOException {
  1919. return new RebaseTodoFile(this).readRebaseTodo(path, includeComments);
  1920. }
  1921. /**
  1922. * Write a file formatted like a git-rebase-todo file.
  1923. *
  1924. * @param path
  1925. * path to the file relative to the repository's git-dir. E.g.
  1926. * "rebase-merge/git-rebase-todo" or "rebase-append/done"
  1927. * @param steps
  1928. * the steps to be written
  1929. * @param append
  1930. * whether to append to an existing file or to write a new file
  1931. * @throws java.io.IOException
  1932. * @since 3.2
  1933. */
  1934. public void writeRebaseTodoFile(String path, List<RebaseTodoLine> steps,
  1935. boolean append)
  1936. throws IOException {
  1937. new RebaseTodoFile(this).writeRebaseTodoFile(path, steps, append);
  1938. }
  1939. /**
  1940. * Get the names of all known remotes
  1941. *
  1942. * @return the names of all known remotes
  1943. * @since 3.4
  1944. */
  1945. @NonNull
  1946. public Set<String> getRemoteNames() {
  1947. return getConfig()
  1948. .getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
  1949. }
  1950. /**
  1951. * Check whether any housekeeping is required; if yes, run garbage
  1952. * collection; if not, exit without performing any work. Some JGit commands
  1953. * run autoGC after performing operations that could create many loose
  1954. * objects.
  1955. * <p>
  1956. * Currently this option is supported for repositories of type
  1957. * {@code FileRepository} only. See
  1958. * {@link org.eclipse.jgit.internal.storage.file.GC#setAuto(boolean)} for
  1959. * configuration details.
  1960. *
  1961. * @param monitor
  1962. * to report progress
  1963. * @since 4.6
  1964. */
  1965. public void autoGC(ProgressMonitor monitor) {
  1966. // default does nothing
  1967. }
  1968. }