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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095
  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. rw.setRetainBody(false);
  459. Object resolved = resolve(rw, revstr);
  460. if (resolved instanceof String) {
  461. final Ref ref = findRef((String) resolved);
  462. return ref != null ? ref.getLeaf().getObjectId() : null;
  463. } else {
  464. return (ObjectId) resolved;
  465. }
  466. }
  467. }
  468. /**
  469. * Simplify an expression, but unlike {@link #resolve(String)} it will not
  470. * resolve a branch passed or resulting from the expression, such as @{-}.
  471. * Thus this method can be used to process an expression to a method that
  472. * expects a branch or revision id.
  473. *
  474. * @param revstr a {@link java.lang.String} object.
  475. * @return object id or ref name from resolved expression or {@code null} if
  476. * given expression cannot be resolved
  477. * @throws org.eclipse.jgit.errors.AmbiguousObjectException
  478. * @throws java.io.IOException
  479. */
  480. @Nullable
  481. public String simplify(String revstr)
  482. throws AmbiguousObjectException, IOException {
  483. try (RevWalk rw = new RevWalk(this)) {
  484. rw.setRetainBody(true);
  485. Object resolved = resolve(rw, revstr);
  486. if (resolved != null)
  487. if (resolved instanceof String)
  488. return (String) resolved;
  489. else
  490. return ((AnyObjectId) resolved).getName();
  491. return null;
  492. }
  493. }
  494. @Nullable
  495. private Object resolve(RevWalk rw, String revstr)
  496. throws IOException {
  497. char[] revChars = revstr.toCharArray();
  498. RevObject rev = null;
  499. String name = null;
  500. int done = 0;
  501. for (int i = 0; i < revChars.length; ++i) {
  502. switch (revChars[i]) {
  503. case '^':
  504. if (rev == null) {
  505. if (name == null)
  506. if (done == 0)
  507. name = new String(revChars, done, i);
  508. else {
  509. done = i + 1;
  510. break;
  511. }
  512. rev = parseSimple(rw, name);
  513. name = null;
  514. if (rev == null)
  515. return null;
  516. }
  517. if (i + 1 < revChars.length) {
  518. switch (revChars[i + 1]) {
  519. case '0':
  520. case '1':
  521. case '2':
  522. case '3':
  523. case '4':
  524. case '5':
  525. case '6':
  526. case '7':
  527. case '8':
  528. case '9':
  529. int j;
  530. rev = rw.parseCommit(rev);
  531. for (j = i + 1; j < revChars.length; ++j) {
  532. if (!Character.isDigit(revChars[j]))
  533. break;
  534. }
  535. String parentnum = new String(revChars, i + 1, j - i
  536. - 1);
  537. int pnum;
  538. try {
  539. pnum = Integer.parseInt(parentnum);
  540. } catch (NumberFormatException e) {
  541. throw new RevisionSyntaxException(
  542. JGitText.get().invalidCommitParentNumber,
  543. revstr);
  544. }
  545. if (pnum != 0) {
  546. RevCommit commit = (RevCommit) rev;
  547. if (pnum > commit.getParentCount())
  548. rev = null;
  549. else
  550. rev = commit.getParent(pnum - 1);
  551. }
  552. i = j - 1;
  553. done = j;
  554. break;
  555. case '{':
  556. int k;
  557. String item = null;
  558. for (k = i + 2; k < revChars.length; ++k) {
  559. if (revChars[k] == '}') {
  560. item = new String(revChars, i + 2, k - i - 2);
  561. break;
  562. }
  563. }
  564. i = k;
  565. if (item != null)
  566. if (item.equals("tree")) { //$NON-NLS-1$
  567. rev = rw.parseTree(rev);
  568. } else if (item.equals("commit")) { //$NON-NLS-1$
  569. rev = rw.parseCommit(rev);
  570. } else if (item.equals("blob")) { //$NON-NLS-1$
  571. rev = rw.peel(rev);
  572. if (!(rev instanceof RevBlob))
  573. throw new IncorrectObjectTypeException(rev,
  574. Constants.TYPE_BLOB);
  575. } else if (item.isEmpty()) {
  576. rev = rw.peel(rev);
  577. } else
  578. throw new RevisionSyntaxException(revstr);
  579. else
  580. throw new RevisionSyntaxException(revstr);
  581. done = k;
  582. break;
  583. default:
  584. rev = rw.peel(rev);
  585. if (rev instanceof RevCommit) {
  586. RevCommit commit = ((RevCommit) rev);
  587. if (commit.getParentCount() == 0)
  588. rev = null;
  589. else
  590. rev = commit.getParent(0);
  591. } else
  592. throw new IncorrectObjectTypeException(rev,
  593. Constants.TYPE_COMMIT);
  594. }
  595. } else {
  596. rev = rw.peel(rev);
  597. if (rev instanceof RevCommit) {
  598. RevCommit commit = ((RevCommit) rev);
  599. if (commit.getParentCount() == 0)
  600. rev = null;
  601. else
  602. rev = commit.getParent(0);
  603. } else
  604. throw new IncorrectObjectTypeException(rev,
  605. Constants.TYPE_COMMIT);
  606. }
  607. done = i + 1;
  608. break;
  609. case '~':
  610. if (rev == null) {
  611. if (name == null)
  612. if (done == 0)
  613. name = new String(revChars, done, i);
  614. else {
  615. done = i + 1;
  616. break;
  617. }
  618. rev = parseSimple(rw, name);
  619. name = null;
  620. if (rev == null)
  621. return null;
  622. }
  623. rev = rw.peel(rev);
  624. if (!(rev instanceof RevCommit))
  625. throw new IncorrectObjectTypeException(rev,
  626. Constants.TYPE_COMMIT);
  627. int l;
  628. for (l = i + 1; l < revChars.length; ++l) {
  629. if (!Character.isDigit(revChars[l]))
  630. break;
  631. }
  632. int dist;
  633. if (l - i > 1) {
  634. String distnum = new String(revChars, i + 1, l - i - 1);
  635. try {
  636. dist = Integer.parseInt(distnum);
  637. } catch (NumberFormatException e) {
  638. throw new RevisionSyntaxException(
  639. JGitText.get().invalidAncestryLength, revstr);
  640. }
  641. } else
  642. dist = 1;
  643. while (dist > 0) {
  644. RevCommit commit = (RevCommit) rev;
  645. if (commit.getParentCount() == 0) {
  646. rev = null;
  647. break;
  648. }
  649. commit = commit.getParent(0);
  650. rw.parseHeaders(commit);
  651. rev = commit;
  652. --dist;
  653. }
  654. i = l - 1;
  655. done = l;
  656. break;
  657. case '@':
  658. if (rev != null)
  659. throw new RevisionSyntaxException(revstr);
  660. if (i + 1 == revChars.length)
  661. continue;
  662. if (i + 1 < revChars.length && revChars[i + 1] != '{')
  663. continue;
  664. int m;
  665. String time = null;
  666. for (m = i + 2; m < revChars.length; ++m) {
  667. if (revChars[m] == '}') {
  668. time = new String(revChars, i + 2, m - i - 2);
  669. break;
  670. }
  671. }
  672. if (time != null) {
  673. if (time.equals("upstream")) { //$NON-NLS-1$
  674. if (name == null)
  675. name = new String(revChars, done, i);
  676. if (name.isEmpty())
  677. // Currently checked out branch, HEAD if
  678. // detached
  679. name = Constants.HEAD;
  680. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  681. throw new RevisionSyntaxException(MessageFormat
  682. .format(JGitText.get().invalidRefName,
  683. name),
  684. revstr);
  685. Ref ref = findRef(name);
  686. name = null;
  687. if (ref == null)
  688. return null;
  689. if (ref.isSymbolic())
  690. ref = ref.getLeaf();
  691. name = ref.getName();
  692. RemoteConfig remoteConfig;
  693. try {
  694. remoteConfig = new RemoteConfig(getConfig(),
  695. "origin"); //$NON-NLS-1$
  696. } catch (URISyntaxException e) {
  697. throw new RevisionSyntaxException(revstr);
  698. }
  699. String remoteBranchName = getConfig()
  700. .getString(
  701. ConfigConstants.CONFIG_BRANCH_SECTION,
  702. Repository.shortenRefName(ref.getName()),
  703. ConfigConstants.CONFIG_KEY_MERGE);
  704. List<RefSpec> fetchRefSpecs = remoteConfig
  705. .getFetchRefSpecs();
  706. for (RefSpec refSpec : fetchRefSpecs) {
  707. if (refSpec.matchSource(remoteBranchName)) {
  708. RefSpec expandFromSource = refSpec
  709. .expandFromSource(remoteBranchName);
  710. name = expandFromSource.getDestination();
  711. break;
  712. }
  713. }
  714. if (name == null)
  715. throw new RevisionSyntaxException(revstr);
  716. } else if (time.matches("^-\\d+$")) { //$NON-NLS-1$
  717. if (name != null)
  718. throw new RevisionSyntaxException(revstr);
  719. else {
  720. String previousCheckout = resolveReflogCheckout(-Integer
  721. .parseInt(time));
  722. if (ObjectId.isId(previousCheckout))
  723. rev = parseSimple(rw, previousCheckout);
  724. else
  725. name = previousCheckout;
  726. }
  727. } else {
  728. if (name == null)
  729. name = new String(revChars, done, i);
  730. if (name.isEmpty())
  731. name = Constants.HEAD;
  732. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  733. throw new RevisionSyntaxException(MessageFormat
  734. .format(JGitText.get().invalidRefName,
  735. name),
  736. revstr);
  737. Ref ref = findRef(name);
  738. name = null;
  739. if (ref == null)
  740. return null;
  741. // @{n} means current branch, not HEAD@{1} unless
  742. // detached
  743. if (ref.isSymbolic())
  744. ref = ref.getLeaf();
  745. rev = resolveReflog(rw, ref, time);
  746. }
  747. i = m;
  748. } else
  749. throw new RevisionSyntaxException(revstr);
  750. break;
  751. case ':': {
  752. RevTree tree;
  753. if (rev == null) {
  754. if (name == null)
  755. name = new String(revChars, done, i);
  756. if (name.isEmpty())
  757. name = Constants.HEAD;
  758. rev = parseSimple(rw, name);
  759. name = null;
  760. }
  761. if (rev == null)
  762. return null;
  763. tree = rw.parseTree(rev);
  764. if (i == revChars.length - 1)
  765. return tree.copy();
  766. TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(),
  767. new String(revChars, i + 1, revChars.length - i - 1),
  768. tree);
  769. return tw != null ? tw.getObjectId(0) : null;
  770. }
  771. default:
  772. if (rev != null)
  773. throw new RevisionSyntaxException(revstr);
  774. }
  775. }
  776. if (rev != null)
  777. return rev.copy();
  778. if (name != null)
  779. return name;
  780. if (done == revstr.length())
  781. return null;
  782. name = revstr.substring(done);
  783. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  784. throw new RevisionSyntaxException(
  785. MessageFormat.format(JGitText.get().invalidRefName, name),
  786. revstr);
  787. if (findRef(name) != null)
  788. return name;
  789. return resolveSimple(name);
  790. }
  791. private static boolean isHex(char c) {
  792. return ('0' <= c && c <= '9') //
  793. || ('a' <= c && c <= 'f') //
  794. || ('A' <= c && c <= 'F');
  795. }
  796. private static boolean isAllHex(String str, int ptr) {
  797. while (ptr < str.length()) {
  798. if (!isHex(str.charAt(ptr++)))
  799. return false;
  800. }
  801. return true;
  802. }
  803. @Nullable
  804. private RevObject parseSimple(RevWalk rw, String revstr) throws IOException {
  805. ObjectId id = resolveSimple(revstr);
  806. return id != null ? rw.parseAny(id) : null;
  807. }
  808. @Nullable
  809. private ObjectId resolveSimple(String revstr) throws IOException {
  810. if (ObjectId.isId(revstr))
  811. return ObjectId.fromString(revstr);
  812. if (Repository.isValidRefName("x/" + revstr)) { //$NON-NLS-1$
  813. Ref r = getRefDatabase().findRef(revstr);
  814. if (r != null)
  815. return r.getObjectId();
  816. }
  817. if (AbbreviatedObjectId.isId(revstr))
  818. return resolveAbbreviation(revstr);
  819. int dashg = revstr.indexOf("-g"); //$NON-NLS-1$
  820. if ((dashg + 5) < revstr.length() && 0 <= dashg
  821. && isHex(revstr.charAt(dashg + 2))
  822. && isHex(revstr.charAt(dashg + 3))
  823. && isAllHex(revstr, dashg + 4)) {
  824. // Possibly output from git describe?
  825. String s = revstr.substring(dashg + 2);
  826. if (AbbreviatedObjectId.isId(s))
  827. return resolveAbbreviation(s);
  828. }
  829. return null;
  830. }
  831. @Nullable
  832. private String resolveReflogCheckout(int checkoutNo)
  833. throws IOException {
  834. ReflogReader reader = getReflogReader(Constants.HEAD);
  835. if (reader == null) {
  836. return null;
  837. }
  838. List<ReflogEntry> reflogEntries = reader.getReverseEntries();
  839. for (ReflogEntry entry : reflogEntries) {
  840. CheckoutEntry checkout = entry.parseCheckout();
  841. if (checkout != null)
  842. if (checkoutNo-- == 1)
  843. return checkout.getFromBranch();
  844. }
  845. return null;
  846. }
  847. private RevCommit resolveReflog(RevWalk rw, Ref ref, String time)
  848. throws IOException {
  849. int number;
  850. try {
  851. number = Integer.parseInt(time);
  852. } catch (NumberFormatException nfe) {
  853. throw new RevisionSyntaxException(MessageFormat.format(
  854. JGitText.get().invalidReflogRevision, time));
  855. }
  856. assert number >= 0;
  857. ReflogReader reader = getReflogReader(ref.getName());
  858. if (reader == null) {
  859. throw new RevisionSyntaxException(
  860. MessageFormat.format(JGitText.get().reflogEntryNotFound,
  861. Integer.valueOf(number), ref.getName()));
  862. }
  863. ReflogEntry entry = reader.getReverseEntry(number);
  864. if (entry == null)
  865. throw new RevisionSyntaxException(MessageFormat.format(
  866. JGitText.get().reflogEntryNotFound,
  867. Integer.valueOf(number), ref.getName()));
  868. return rw.parseCommit(entry.getNewId());
  869. }
  870. @Nullable
  871. private ObjectId resolveAbbreviation(String revstr) throws IOException,
  872. AmbiguousObjectException {
  873. AbbreviatedObjectId id = AbbreviatedObjectId.fromString(revstr);
  874. try (ObjectReader reader = newObjectReader()) {
  875. Collection<ObjectId> matches = reader.resolve(id);
  876. if (matches.size() == 0)
  877. return null;
  878. else if (matches.size() == 1)
  879. return matches.iterator().next();
  880. else
  881. throw new AmbiguousObjectException(id, matches);
  882. }
  883. }
  884. /**
  885. * Increment the use counter by one, requiring a matched {@link #close()}.
  886. */
  887. public void incrementOpen() {
  888. useCnt.incrementAndGet();
  889. }
  890. /**
  891. * {@inheritDoc}
  892. * <p>
  893. * Decrement the use count, and maybe close resources.
  894. */
  895. @Override
  896. public void close() {
  897. int newCount = useCnt.decrementAndGet();
  898. if (newCount == 0) {
  899. if (RepositoryCache.isCached(this)) {
  900. closedAt.set(System.currentTimeMillis());
  901. } else {
  902. doClose();
  903. }
  904. } else if (newCount == -1) {
  905. // should not happen, only log when useCnt became negative to
  906. // minimize number of log entries
  907. String message = MessageFormat.format(JGitText.get().corruptUseCnt,
  908. toString());
  909. if (LOG.isDebugEnabled()) {
  910. LOG.debug(message, new IllegalStateException());
  911. } else {
  912. LOG.warn(message);
  913. }
  914. if (RepositoryCache.isCached(this)) {
  915. closedAt.set(System.currentTimeMillis());
  916. }
  917. }
  918. }
  919. /**
  920. * Invoked when the use count drops to zero during {@link #close()}.
  921. * <p>
  922. * The default implementation closes the object and ref databases.
  923. */
  924. protected void doClose() {
  925. getObjectDatabase().close();
  926. getRefDatabase().close();
  927. }
  928. /** {@inheritDoc} */
  929. @Override
  930. @NonNull
  931. public String toString() {
  932. String desc;
  933. File directory = getDirectory();
  934. if (directory != null)
  935. desc = directory.getPath();
  936. else
  937. desc = getClass().getSimpleName() + "-" //$NON-NLS-1$
  938. + System.identityHashCode(this);
  939. return "Repository[" + desc + "]"; //$NON-NLS-1$ //$NON-NLS-2$
  940. }
  941. /**
  942. * Get the name of the reference that {@code HEAD} points to.
  943. * <p>
  944. * This is essentially the same as doing:
  945. *
  946. * <pre>
  947. * return exactRef(Constants.HEAD).getTarget().getName()
  948. * </pre>
  949. *
  950. * Except when HEAD is detached, in which case this method returns the
  951. * current ObjectId in hexadecimal string format.
  952. *
  953. * @return name of current branch (for example {@code refs/heads/master}),
  954. * an ObjectId in hex format if the current branch is detached, or
  955. * {@code null} if the repository is corrupt and has no HEAD
  956. * reference.
  957. * @throws java.io.IOException
  958. */
  959. @Nullable
  960. public String getFullBranch() throws IOException {
  961. Ref head = exactRef(Constants.HEAD);
  962. if (head == null) {
  963. return null;
  964. }
  965. if (head.isSymbolic()) {
  966. return head.getTarget().getName();
  967. }
  968. ObjectId objectId = head.getObjectId();
  969. if (objectId != null) {
  970. return objectId.name();
  971. }
  972. return null;
  973. }
  974. /**
  975. * Get the short name of the current branch that {@code HEAD} points to.
  976. * <p>
  977. * This is essentially the same as {@link #getFullBranch()}, except the
  978. * leading prefix {@code refs/heads/} is removed from the reference before
  979. * it is returned to the caller.
  980. *
  981. * @return name of current branch (for example {@code master}), an ObjectId
  982. * in hex format if the current branch is detached, or {@code null}
  983. * if the repository is corrupt and has no HEAD reference.
  984. * @throws java.io.IOException
  985. */
  986. @Nullable
  987. public String getBranch() throws IOException {
  988. String name = getFullBranch();
  989. if (name != null)
  990. return shortenRefName(name);
  991. return null;
  992. }
  993. /**
  994. * Objects known to exist but not expressed by {@link #getAllRefs()}.
  995. * <p>
  996. * When a repository borrows objects from another repository, it can
  997. * advertise that it safely has that other repository's references, without
  998. * exposing any other details about the other repository. This may help
  999. * a client trying to push changes avoid pushing more than it needs to.
  1000. *
  1001. * @return unmodifiable collection of other known objects.
  1002. */
  1003. @NonNull
  1004. public Set<ObjectId> getAdditionalHaves() {
  1005. return Collections.emptySet();
  1006. }
  1007. /**
  1008. * Get a ref by name.
  1009. *
  1010. * @param name
  1011. * the name of the ref to lookup. Must not be a short-hand
  1012. * form; e.g., "master" is not automatically expanded to
  1013. * "refs/heads/master".
  1014. * @return the Ref with the given name, or {@code null} if it does not exist
  1015. * @throws java.io.IOException
  1016. * @since 4.2
  1017. */
  1018. @Nullable
  1019. public final Ref exactRef(String name) throws IOException {
  1020. return getRefDatabase().exactRef(name);
  1021. }
  1022. /**
  1023. * Search for a ref by (possibly abbreviated) name.
  1024. *
  1025. * @param name
  1026. * the name of the ref to lookup. May be a short-hand form, e.g.
  1027. * "master" which is automatically expanded to
  1028. * "refs/heads/master" if "refs/heads/master" already exists.
  1029. * @return the Ref with the given name, or {@code null} if it does not exist
  1030. * @throws java.io.IOException
  1031. * @since 4.2
  1032. */
  1033. @Nullable
  1034. public final Ref findRef(String name) throws IOException {
  1035. return getRefDatabase().findRef(name);
  1036. }
  1037. /**
  1038. * Get mutable map of all known refs, including symrefs like HEAD that may
  1039. * not point to any object yet.
  1040. *
  1041. * @return mutable map of all known refs (heads, tags, remotes).
  1042. * @deprecated use {@code getRefDatabase().getRefs()} instead.
  1043. */
  1044. @Deprecated
  1045. @NonNull
  1046. public Map<String, Ref> getAllRefs() {
  1047. try {
  1048. return getRefDatabase().getRefs(RefDatabase.ALL);
  1049. } catch (IOException e) {
  1050. throw new UncheckedIOException(e);
  1051. }
  1052. }
  1053. /**
  1054. * Get mutable map of all tags
  1055. *
  1056. * @return mutable map of all tags; key is short tag name ("v1.0") and value
  1057. * of the entry contains the ref with the full tag name
  1058. * ("refs/tags/v1.0").
  1059. * @deprecated use {@code getRefDatabase().getRefsByPrefix(R_TAGS)} instead
  1060. */
  1061. @Deprecated
  1062. @NonNull
  1063. public Map<String, Ref> getTags() {
  1064. try {
  1065. return getRefDatabase().getRefs(Constants.R_TAGS);
  1066. } catch (IOException e) {
  1067. throw new UncheckedIOException(e);
  1068. }
  1069. }
  1070. /**
  1071. * Peel a possibly unpeeled reference to an annotated tag.
  1072. * <p>
  1073. * If the ref cannot be peeled (as it does not refer to an annotated tag)
  1074. * the peeled id stays null, but {@link org.eclipse.jgit.lib.Ref#isPeeled()}
  1075. * will be true.
  1076. *
  1077. * @param ref
  1078. * The ref to peel
  1079. * @return <code>ref</code> if <code>ref.isPeeled()</code> is true; else a
  1080. * new Ref object representing the same data as Ref, but isPeeled()
  1081. * will be true and getPeeledObjectId will contain the peeled object
  1082. * (or null).
  1083. * @deprecated use {@code getRefDatabase().peel(ref)} instead.
  1084. */
  1085. @Deprecated
  1086. @NonNull
  1087. public Ref peel(Ref ref) {
  1088. try {
  1089. return getRefDatabase().peel(ref);
  1090. } catch (IOException e) {
  1091. // Historical accident; if the reference cannot be peeled due
  1092. // to some sort of repository access problem we claim that the
  1093. // same as if the reference was not an annotated tag.
  1094. return ref;
  1095. }
  1096. }
  1097. /**
  1098. * Get a map with all objects referenced by a peeled ref.
  1099. *
  1100. * @return a map with all objects referenced by a peeled ref.
  1101. */
  1102. @NonNull
  1103. public Map<AnyObjectId, Set<Ref>> getAllRefsByPeeledObjectId() {
  1104. Map<String, Ref> allRefs = getAllRefs();
  1105. Map<AnyObjectId, Set<Ref>> ret = new HashMap<>(allRefs.size());
  1106. for (Ref ref : allRefs.values()) {
  1107. ref = peel(ref);
  1108. AnyObjectId target = ref.getPeeledObjectId();
  1109. if (target == null)
  1110. target = ref.getObjectId();
  1111. // We assume most Sets here are singletons
  1112. Set<Ref> oset = ret.put(target, Collections.singleton(ref));
  1113. if (oset != null) {
  1114. // that was not the case (rare)
  1115. if (oset.size() == 1) {
  1116. // Was a read-only singleton, we must copy to a new Set
  1117. oset = new HashSet<>(oset);
  1118. }
  1119. ret.put(target, oset);
  1120. oset.add(ref);
  1121. }
  1122. }
  1123. return ret;
  1124. }
  1125. /**
  1126. * Get the index file location or {@code null} if repository isn't local.
  1127. *
  1128. * @return the index file location or {@code null} if repository isn't
  1129. * local.
  1130. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1131. * if this is bare, which implies it has no working directory.
  1132. * See {@link #isBare()}.
  1133. */
  1134. @NonNull
  1135. public File getIndexFile() throws NoWorkTreeException {
  1136. if (isBare())
  1137. throw new NoWorkTreeException();
  1138. return indexFile;
  1139. }
  1140. /**
  1141. * Locate a reference to a commit and immediately parse its content.
  1142. * <p>
  1143. * This method only returns successfully if the commit object exists,
  1144. * is verified to be a commit, and was parsed without error.
  1145. *
  1146. * @param id
  1147. * name of the commit object.
  1148. * @return reference to the commit object. Never null.
  1149. * @throws org.eclipse.jgit.errors.MissingObjectException
  1150. * the supplied commit does not exist.
  1151. * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
  1152. * the supplied id is not a commit or an annotated tag.
  1153. * @throws java.io.IOException
  1154. * a pack file or loose object could not be read.
  1155. * @since 4.8
  1156. */
  1157. public RevCommit parseCommit(AnyObjectId id) throws IncorrectObjectTypeException,
  1158. IOException, MissingObjectException {
  1159. if (id instanceof RevCommit && ((RevCommit) id).getRawBuffer() != null) {
  1160. return (RevCommit) id;
  1161. }
  1162. try (RevWalk walk = new RevWalk(this)) {
  1163. return walk.parseCommit(id);
  1164. }
  1165. }
  1166. /**
  1167. * Create a new in-core index representation and read an index from disk.
  1168. * <p>
  1169. * The new index will be read before it is returned to the caller. Read
  1170. * failures are reported as exceptions and therefore prevent the method from
  1171. * returning a partially populated index.
  1172. *
  1173. * @return a cache representing the contents of the specified index file (if
  1174. * it exists) or an empty cache if the file does not exist.
  1175. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1176. * if this is bare, which implies it has no working directory.
  1177. * See {@link #isBare()}.
  1178. * @throws java.io.IOException
  1179. * the index file is present but could not be read.
  1180. * @throws org.eclipse.jgit.errors.CorruptObjectException
  1181. * the index file is using a format or extension that this
  1182. * library does not support.
  1183. */
  1184. @NonNull
  1185. public DirCache readDirCache() throws NoWorkTreeException,
  1186. CorruptObjectException, IOException {
  1187. return DirCache.read(this);
  1188. }
  1189. /**
  1190. * Create a new in-core index representation, lock it, and read from disk.
  1191. * <p>
  1192. * The new index will be locked and then read before it is returned to the
  1193. * caller. Read failures are reported as exceptions and therefore prevent
  1194. * the method from returning a partially populated index.
  1195. *
  1196. * @return a cache representing the contents of the specified index file (if
  1197. * it exists) or an empty cache if the file does not exist.
  1198. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1199. * if this is bare, which implies it has no working directory.
  1200. * See {@link #isBare()}.
  1201. * @throws java.io.IOException
  1202. * the index file is present but could not be read, or the lock
  1203. * could not be obtained.
  1204. * @throws org.eclipse.jgit.errors.CorruptObjectException
  1205. * the index file is using a format or extension that this
  1206. * library does not support.
  1207. */
  1208. @NonNull
  1209. public DirCache lockDirCache() throws NoWorkTreeException,
  1210. CorruptObjectException, IOException {
  1211. // we want DirCache to inform us so that we can inform registered
  1212. // listeners about index changes
  1213. IndexChangedListener l = new IndexChangedListener() {
  1214. @Override
  1215. public void onIndexChanged(IndexChangedEvent event) {
  1216. notifyIndexChanged(true);
  1217. }
  1218. };
  1219. return DirCache.lock(this, l);
  1220. }
  1221. /**
  1222. * Get the repository state
  1223. *
  1224. * @return the repository state
  1225. */
  1226. @NonNull
  1227. public RepositoryState getRepositoryState() {
  1228. if (isBare() || getDirectory() == null)
  1229. return RepositoryState.BARE;
  1230. // Pre Git-1.6 logic
  1231. if (new File(getWorkTree(), ".dotest").exists()) //$NON-NLS-1$
  1232. return RepositoryState.REBASING;
  1233. if (new File(getDirectory(), ".dotest-merge").exists()) //$NON-NLS-1$
  1234. return RepositoryState.REBASING_INTERACTIVE;
  1235. // From 1.6 onwards
  1236. if (new File(getDirectory(),"rebase-apply/rebasing").exists()) //$NON-NLS-1$
  1237. return RepositoryState.REBASING_REBASING;
  1238. if (new File(getDirectory(),"rebase-apply/applying").exists()) //$NON-NLS-1$
  1239. return RepositoryState.APPLY;
  1240. if (new File(getDirectory(),"rebase-apply").exists()) //$NON-NLS-1$
  1241. return RepositoryState.REBASING;
  1242. if (new File(getDirectory(),"rebase-merge/interactive").exists()) //$NON-NLS-1$
  1243. return RepositoryState.REBASING_INTERACTIVE;
  1244. if (new File(getDirectory(),"rebase-merge").exists()) //$NON-NLS-1$
  1245. return RepositoryState.REBASING_MERGE;
  1246. // Both versions
  1247. if (new File(getDirectory(), Constants.MERGE_HEAD).exists()) {
  1248. // we are merging - now check whether we have unmerged paths
  1249. try {
  1250. if (!readDirCache().hasUnmergedPaths()) {
  1251. // no unmerged paths -> return the MERGING_RESOLVED state
  1252. return RepositoryState.MERGING_RESOLVED;
  1253. }
  1254. } catch (IOException e) {
  1255. throw new UncheckedIOException(e);
  1256. }
  1257. return RepositoryState.MERGING;
  1258. }
  1259. if (new File(getDirectory(), "BISECT_LOG").exists()) //$NON-NLS-1$
  1260. return RepositoryState.BISECTING;
  1261. if (new File(getDirectory(), Constants.CHERRY_PICK_HEAD).exists()) {
  1262. try {
  1263. if (!readDirCache().hasUnmergedPaths()) {
  1264. // no unmerged paths
  1265. return RepositoryState.CHERRY_PICKING_RESOLVED;
  1266. }
  1267. } catch (IOException e) {
  1268. throw new UncheckedIOException(e);
  1269. }
  1270. return RepositoryState.CHERRY_PICKING;
  1271. }
  1272. if (new File(getDirectory(), Constants.REVERT_HEAD).exists()) {
  1273. try {
  1274. if (!readDirCache().hasUnmergedPaths()) {
  1275. // no unmerged paths
  1276. return RepositoryState.REVERTING_RESOLVED;
  1277. }
  1278. } catch (IOException e) {
  1279. throw new UncheckedIOException(e);
  1280. }
  1281. return RepositoryState.REVERTING;
  1282. }
  1283. return RepositoryState.SAFE;
  1284. }
  1285. /**
  1286. * Check validity of a ref name. It must not contain character that has
  1287. * a special meaning in a Git object reference expression. Some other
  1288. * dangerous characters are also excluded.
  1289. *
  1290. * For portability reasons '\' is excluded
  1291. *
  1292. * @param refName a {@link java.lang.String} object.
  1293. * @return true if refName is a valid ref name
  1294. */
  1295. public static boolean isValidRefName(String refName) {
  1296. final int len = refName.length();
  1297. if (len == 0) {
  1298. return false;
  1299. }
  1300. if (refName.endsWith(LOCK_SUFFIX)) {
  1301. return false;
  1302. }
  1303. // Refs may be stored as loose files so invalid paths
  1304. // on the local system must also be invalid refs.
  1305. try {
  1306. SystemReader.getInstance().checkPath(refName);
  1307. } catch (CorruptObjectException e) {
  1308. return false;
  1309. }
  1310. int components = 1;
  1311. char p = '\0';
  1312. for (int i = 0; i < len; i++) {
  1313. final char c = refName.charAt(i);
  1314. if (c <= ' ')
  1315. return false;
  1316. switch (c) {
  1317. case '.':
  1318. switch (p) {
  1319. case '\0': case '/': case '.':
  1320. return false;
  1321. }
  1322. if (i == len -1)
  1323. return false;
  1324. break;
  1325. case '/':
  1326. if (i == 0 || i == len - 1)
  1327. return false;
  1328. if (p == '/')
  1329. return false;
  1330. components++;
  1331. break;
  1332. case '{':
  1333. if (p == '@')
  1334. return false;
  1335. break;
  1336. case '~': case '^': case ':':
  1337. case '?': case '[': case '*':
  1338. case '\\':
  1339. case '\u007F':
  1340. return false;
  1341. }
  1342. p = c;
  1343. }
  1344. return components > 1;
  1345. }
  1346. /**
  1347. * Normalizes the passed branch name into a possible valid branch name. The
  1348. * validity of the returned name should be checked by a subsequent call to
  1349. * {@link #isValidRefName(String)}.
  1350. * <p>
  1351. * Future implementations of this method could be more restrictive or more
  1352. * lenient about the validity of specific characters in the returned name.
  1353. * <p>
  1354. * The current implementation returns the trimmed input string if this is
  1355. * already a valid branch name. Otherwise it returns a trimmed string with
  1356. * special characters not allowed by {@link #isValidRefName(String)}
  1357. * replaced by hyphens ('-') and blanks replaced by underscores ('_').
  1358. * Leading and trailing slashes, dots, hyphens, and underscores are removed.
  1359. *
  1360. * @param name
  1361. * to normalize
  1362. * @return The normalized name or an empty String if it is {@code null} or
  1363. * empty.
  1364. * @since 4.7
  1365. * @see #isValidRefName(String)
  1366. */
  1367. public static String normalizeBranchName(String name) {
  1368. if (name == null || name.isEmpty()) {
  1369. return ""; //$NON-NLS-1$
  1370. }
  1371. String result = name.trim();
  1372. String fullName = result.startsWith(Constants.R_HEADS) ? result
  1373. : Constants.R_HEADS + result;
  1374. if (isValidRefName(fullName)) {
  1375. return result;
  1376. }
  1377. // All Unicode blanks to underscore
  1378. result = result.replaceAll("(?:\\h|\\v)+", "_"); //$NON-NLS-1$ //$NON-NLS-2$
  1379. StringBuilder b = new StringBuilder();
  1380. char p = '/';
  1381. for (int i = 0, len = result.length(); i < len; i++) {
  1382. char c = result.charAt(i);
  1383. if (c < ' ' || c == 127) {
  1384. continue;
  1385. }
  1386. // Substitute a dash for problematic characters
  1387. switch (c) {
  1388. case '\\':
  1389. case '^':
  1390. case '~':
  1391. case ':':
  1392. case '?':
  1393. case '*':
  1394. case '[':
  1395. case '@':
  1396. case '<':
  1397. case '>':
  1398. case '|':
  1399. case '"':
  1400. c = '-';
  1401. break;
  1402. default:
  1403. break;
  1404. }
  1405. // Collapse multiple slashes, dashes, dots, underscores, and omit
  1406. // dashes, dots, and underscores following a slash.
  1407. switch (c) {
  1408. case '/':
  1409. if (p == '/') {
  1410. continue;
  1411. }
  1412. p = '/';
  1413. break;
  1414. case '.':
  1415. case '_':
  1416. case '-':
  1417. if (p == '/' || p == '-') {
  1418. continue;
  1419. }
  1420. p = '-';
  1421. break;
  1422. default:
  1423. p = c;
  1424. break;
  1425. }
  1426. b.append(c);
  1427. }
  1428. // Strip trailing special characters, and avoid the .lock extension
  1429. result = b.toString().replaceFirst("[/_.-]+$", "") //$NON-NLS-1$ //$NON-NLS-2$
  1430. .replaceAll("\\.lock($|/)", "_lock$1"); //$NON-NLS-1$ //$NON-NLS-2$
  1431. return FORBIDDEN_BRANCH_NAME_COMPONENTS.matcher(result)
  1432. .replaceAll("$1+$2$3"); //$NON-NLS-1$
  1433. }
  1434. /**
  1435. * Strip work dir and return normalized repository path.
  1436. *
  1437. * @param workDir
  1438. * Work dir
  1439. * @param file
  1440. * File whose path shall be stripped of its workdir
  1441. * @return normalized repository relative path or the empty string if the
  1442. * file is not relative to the work directory.
  1443. */
  1444. @NonNull
  1445. public static String stripWorkDir(File workDir, File file) {
  1446. final String filePath = file.getPath();
  1447. final String workDirPath = workDir.getPath();
  1448. if (filePath.length() <= workDirPath.length() ||
  1449. filePath.charAt(workDirPath.length()) != File.separatorChar ||
  1450. !filePath.startsWith(workDirPath)) {
  1451. File absWd = workDir.isAbsolute() ? workDir : workDir.getAbsoluteFile();
  1452. File absFile = file.isAbsolute() ? file : file.getAbsoluteFile();
  1453. if (absWd == workDir && absFile == file)
  1454. return ""; //$NON-NLS-1$
  1455. return stripWorkDir(absWd, absFile);
  1456. }
  1457. String relName = filePath.substring(workDirPath.length() + 1);
  1458. if (File.separatorChar != '/')
  1459. relName = relName.replace(File.separatorChar, '/');
  1460. return relName;
  1461. }
  1462. /**
  1463. * Whether this repository is bare
  1464. *
  1465. * @return true if this is bare, which implies it has no working directory.
  1466. */
  1467. public boolean isBare() {
  1468. return workTree == null;
  1469. }
  1470. /**
  1471. * Get the root directory of the working tree, where files are checked out
  1472. * for viewing and editing.
  1473. *
  1474. * @return the root directory of the working tree, where files are checked
  1475. * out for viewing and editing.
  1476. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1477. * if this is bare, which implies it has no working directory.
  1478. * See {@link #isBare()}.
  1479. */
  1480. @NonNull
  1481. public File getWorkTree() throws NoWorkTreeException {
  1482. if (isBare())
  1483. throw new NoWorkTreeException();
  1484. return workTree;
  1485. }
  1486. /**
  1487. * Force a scan for changed refs. Fires an IndexChangedEvent(false) if
  1488. * changes are detected.
  1489. *
  1490. * @throws java.io.IOException
  1491. */
  1492. public abstract void scanForRepoChanges() throws IOException;
  1493. /**
  1494. * Notify that the index changed by firing an IndexChangedEvent.
  1495. *
  1496. * @param internal
  1497. * {@code true} if the index was changed by the same
  1498. * JGit process
  1499. * @since 5.0
  1500. */
  1501. public abstract void notifyIndexChanged(boolean internal);
  1502. /**
  1503. * Get a shortened more user friendly ref name
  1504. *
  1505. * @param refName
  1506. * a {@link java.lang.String} object.
  1507. * @return a more user friendly ref name
  1508. */
  1509. @NonNull
  1510. public static String shortenRefName(String refName) {
  1511. if (refName.startsWith(Constants.R_HEADS))
  1512. return refName.substring(Constants.R_HEADS.length());
  1513. if (refName.startsWith(Constants.R_TAGS))
  1514. return refName.substring(Constants.R_TAGS.length());
  1515. if (refName.startsWith(Constants.R_REMOTES))
  1516. return refName.substring(Constants.R_REMOTES.length());
  1517. return refName;
  1518. }
  1519. /**
  1520. * Get a shortened more user friendly remote tracking branch name
  1521. *
  1522. * @param refName
  1523. * a {@link java.lang.String} object.
  1524. * @return the remote branch name part of <code>refName</code>, i.e. without
  1525. * the <code>refs/remotes/&lt;remote&gt;</code> prefix, if
  1526. * <code>refName</code> represents a remote tracking branch;
  1527. * otherwise {@code null}.
  1528. * @since 3.4
  1529. */
  1530. @Nullable
  1531. public String shortenRemoteBranchName(String refName) {
  1532. for (String remote : getRemoteNames()) {
  1533. String remotePrefix = Constants.R_REMOTES + remote + "/"; //$NON-NLS-1$
  1534. if (refName.startsWith(remotePrefix))
  1535. return refName.substring(remotePrefix.length());
  1536. }
  1537. return null;
  1538. }
  1539. /**
  1540. * Get remote name
  1541. *
  1542. * @param refName
  1543. * a {@link java.lang.String} object.
  1544. * @return the remote name part of <code>refName</code>, i.e. without the
  1545. * <code>refs/remotes/&lt;remote&gt;</code> prefix, if
  1546. * <code>refName</code> represents a remote tracking branch;
  1547. * otherwise {@code null}.
  1548. * @since 3.4
  1549. */
  1550. @Nullable
  1551. public String getRemoteName(String refName) {
  1552. for (String remote : getRemoteNames()) {
  1553. String remotePrefix = Constants.R_REMOTES + remote + "/"; //$NON-NLS-1$
  1554. if (refName.startsWith(remotePrefix))
  1555. return remote;
  1556. }
  1557. return null;
  1558. }
  1559. /**
  1560. * Read the {@code GIT_DIR/description} file for gitweb.
  1561. *
  1562. * @return description text; null if no description has been configured.
  1563. * @throws java.io.IOException
  1564. * description cannot be accessed.
  1565. * @since 4.6
  1566. */
  1567. @Nullable
  1568. public String getGitwebDescription() throws IOException {
  1569. return null;
  1570. }
  1571. /**
  1572. * Set the {@code GIT_DIR/description} file for gitweb.
  1573. *
  1574. * @param description
  1575. * new description; null to clear the description.
  1576. * @throws java.io.IOException
  1577. * description cannot be persisted.
  1578. * @since 4.6
  1579. */
  1580. public void setGitwebDescription(@Nullable String description)
  1581. throws IOException {
  1582. throw new IOException(JGitText.get().unsupportedRepositoryDescription);
  1583. }
  1584. /**
  1585. * Get the reflog reader
  1586. *
  1587. * @param refName
  1588. * a {@link java.lang.String} object.
  1589. * @return a {@link org.eclipse.jgit.lib.ReflogReader} for the supplied
  1590. * refname, or {@code null} if the named ref does not exist.
  1591. * @throws java.io.IOException
  1592. * the ref could not be accessed.
  1593. * @since 3.0
  1594. */
  1595. @Nullable
  1596. public abstract ReflogReader getReflogReader(String refName)
  1597. throws IOException;
  1598. /**
  1599. * Return the information stored in the file $GIT_DIR/MERGE_MSG. In this
  1600. * file operations triggering a merge will store a template for the commit
  1601. * message of the merge commit.
  1602. *
  1603. * @return a String containing the content of the MERGE_MSG file or
  1604. * {@code null} if this file doesn't exist
  1605. * @throws java.io.IOException
  1606. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1607. * if this is bare, which implies it has no working directory.
  1608. * See {@link #isBare()}.
  1609. */
  1610. @Nullable
  1611. public String readMergeCommitMsg() throws IOException, NoWorkTreeException {
  1612. return readCommitMsgFile(Constants.MERGE_MSG);
  1613. }
  1614. /**
  1615. * Write new content to the file $GIT_DIR/MERGE_MSG. In this file operations
  1616. * triggering a merge will store a template for the commit message of the
  1617. * merge commit. If <code>null</code> is specified as message the file will
  1618. * be deleted.
  1619. *
  1620. * @param msg
  1621. * the message which should be written or <code>null</code> to
  1622. * delete the file
  1623. * @throws java.io.IOException
  1624. */
  1625. public void writeMergeCommitMsg(String msg) throws IOException {
  1626. File mergeMsgFile = new File(gitDir, Constants.MERGE_MSG);
  1627. writeCommitMsg(mergeMsgFile, msg);
  1628. }
  1629. /**
  1630. * Return the information stored in the file $GIT_DIR/COMMIT_EDITMSG. In
  1631. * this file hooks triggered by an operation may read or modify the current
  1632. * commit message.
  1633. *
  1634. * @return a String containing the content of the COMMIT_EDITMSG file or
  1635. * {@code null} if this file doesn't exist
  1636. * @throws java.io.IOException
  1637. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1638. * if this is bare, which implies it has no working directory.
  1639. * See {@link #isBare()}.
  1640. * @since 4.0
  1641. */
  1642. @Nullable
  1643. public String readCommitEditMsg() throws IOException, NoWorkTreeException {
  1644. return readCommitMsgFile(Constants.COMMIT_EDITMSG);
  1645. }
  1646. /**
  1647. * Write new content to the file $GIT_DIR/COMMIT_EDITMSG. In this file hooks
  1648. * triggered by an operation may read or modify the current commit message.
  1649. * If {@code null} is specified as message the file will be deleted.
  1650. *
  1651. * @param msg
  1652. * the message which should be written or {@code null} to delete
  1653. * the file
  1654. * @throws java.io.IOException
  1655. * @since 4.0
  1656. */
  1657. public void writeCommitEditMsg(String msg) throws IOException {
  1658. File commiEditMsgFile = new File(gitDir, Constants.COMMIT_EDITMSG);
  1659. writeCommitMsg(commiEditMsgFile, msg);
  1660. }
  1661. /**
  1662. * Return the information stored in the file $GIT_DIR/MERGE_HEAD. In this
  1663. * file operations triggering a merge will store the IDs of all heads which
  1664. * should be merged together with HEAD.
  1665. *
  1666. * @return a list of commits which IDs are listed in the MERGE_HEAD file or
  1667. * {@code null} if this file doesn't exist. Also if the file exists
  1668. * but is empty {@code null} will be returned
  1669. * @throws java.io.IOException
  1670. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1671. * if this is bare, which implies it has no working directory.
  1672. * See {@link #isBare()}.
  1673. */
  1674. @Nullable
  1675. public List<ObjectId> readMergeHeads() throws IOException, NoWorkTreeException {
  1676. if (isBare() || getDirectory() == null)
  1677. throw new NoWorkTreeException();
  1678. byte[] raw = readGitDirectoryFile(Constants.MERGE_HEAD);
  1679. if (raw == null)
  1680. return null;
  1681. LinkedList<ObjectId> heads = new LinkedList<>();
  1682. for (int p = 0; p < raw.length;) {
  1683. heads.add(ObjectId.fromString(raw, p));
  1684. p = RawParseUtils
  1685. .nextLF(raw, p + Constants.OBJECT_ID_STRING_LENGTH);
  1686. }
  1687. return heads;
  1688. }
  1689. /**
  1690. * Write new merge-heads into $GIT_DIR/MERGE_HEAD. In this file operations
  1691. * triggering a merge will store the IDs of all heads which should be merged
  1692. * together with HEAD. If <code>null</code> is specified as list of commits
  1693. * the file will be deleted
  1694. *
  1695. * @param heads
  1696. * a list of commits which IDs should be written to
  1697. * $GIT_DIR/MERGE_HEAD or <code>null</code> to delete the file
  1698. * @throws java.io.IOException
  1699. */
  1700. public void writeMergeHeads(List<? extends ObjectId> heads) throws IOException {
  1701. writeHeadsFile(heads, Constants.MERGE_HEAD);
  1702. }
  1703. /**
  1704. * Return the information stored in the file $GIT_DIR/CHERRY_PICK_HEAD.
  1705. *
  1706. * @return object id from CHERRY_PICK_HEAD file or {@code null} if this file
  1707. * doesn't exist. Also if the file exists but is empty {@code null}
  1708. * will be returned
  1709. * @throws java.io.IOException
  1710. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1711. * if this is bare, which implies it has no working directory.
  1712. * See {@link #isBare()}.
  1713. */
  1714. @Nullable
  1715. public ObjectId readCherryPickHead() throws IOException,
  1716. NoWorkTreeException {
  1717. if (isBare() || getDirectory() == null)
  1718. throw new NoWorkTreeException();
  1719. byte[] raw = readGitDirectoryFile(Constants.CHERRY_PICK_HEAD);
  1720. if (raw == null)
  1721. return null;
  1722. return ObjectId.fromString(raw, 0);
  1723. }
  1724. /**
  1725. * Return the information stored in the file $GIT_DIR/REVERT_HEAD.
  1726. *
  1727. * @return object id from REVERT_HEAD file or {@code null} if this file
  1728. * doesn't exist. Also if the file exists but is empty {@code null}
  1729. * will be returned
  1730. * @throws java.io.IOException
  1731. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1732. * if this is bare, which implies it has no working directory.
  1733. * See {@link #isBare()}.
  1734. */
  1735. @Nullable
  1736. public ObjectId readRevertHead() throws IOException, NoWorkTreeException {
  1737. if (isBare() || getDirectory() == null)
  1738. throw new NoWorkTreeException();
  1739. byte[] raw = readGitDirectoryFile(Constants.REVERT_HEAD);
  1740. if (raw == null)
  1741. return null;
  1742. return ObjectId.fromString(raw, 0);
  1743. }
  1744. /**
  1745. * Write cherry pick commit into $GIT_DIR/CHERRY_PICK_HEAD. This is used in
  1746. * case of conflicts to store the cherry which was tried to be picked.
  1747. *
  1748. * @param head
  1749. * an object id of the cherry commit or <code>null</code> to
  1750. * delete the file
  1751. * @throws java.io.IOException
  1752. */
  1753. public void writeCherryPickHead(ObjectId head) throws IOException {
  1754. List<ObjectId> heads = (head != null) ? Collections.singletonList(head)
  1755. : null;
  1756. writeHeadsFile(heads, Constants.CHERRY_PICK_HEAD);
  1757. }
  1758. /**
  1759. * Write revert commit into $GIT_DIR/REVERT_HEAD. This is used in case of
  1760. * conflicts to store the revert which was tried to be picked.
  1761. *
  1762. * @param head
  1763. * an object id of the revert commit or <code>null</code> to
  1764. * delete the file
  1765. * @throws java.io.IOException
  1766. */
  1767. public void writeRevertHead(ObjectId head) throws IOException {
  1768. List<ObjectId> heads = (head != null) ? Collections.singletonList(head)
  1769. : null;
  1770. writeHeadsFile(heads, Constants.REVERT_HEAD);
  1771. }
  1772. /**
  1773. * Write original HEAD commit into $GIT_DIR/ORIG_HEAD.
  1774. *
  1775. * @param head
  1776. * an object id of the original HEAD commit or <code>null</code>
  1777. * to delete the file
  1778. * @throws java.io.IOException
  1779. */
  1780. public void writeOrigHead(ObjectId head) throws IOException {
  1781. List<ObjectId> heads = head != null ? Collections.singletonList(head)
  1782. : null;
  1783. writeHeadsFile(heads, Constants.ORIG_HEAD);
  1784. }
  1785. /**
  1786. * Return the information stored in the file $GIT_DIR/ORIG_HEAD.
  1787. *
  1788. * @return object id from ORIG_HEAD file or {@code null} if this file
  1789. * doesn't exist. Also if the file exists but is empty {@code null}
  1790. * will be returned
  1791. * @throws java.io.IOException
  1792. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1793. * if this is bare, which implies it has no working directory.
  1794. * See {@link #isBare()}.
  1795. */
  1796. @Nullable
  1797. public ObjectId readOrigHead() throws IOException, NoWorkTreeException {
  1798. if (isBare() || getDirectory() == null)
  1799. throw new NoWorkTreeException();
  1800. byte[] raw = readGitDirectoryFile(Constants.ORIG_HEAD);
  1801. return raw != null ? ObjectId.fromString(raw, 0) : null;
  1802. }
  1803. /**
  1804. * Return the information stored in the file $GIT_DIR/SQUASH_MSG. In this
  1805. * file operations triggering a squashed merge will store a template for the
  1806. * commit message of the squash commit.
  1807. *
  1808. * @return a String containing the content of the SQUASH_MSG file or
  1809. * {@code null} if this file doesn't exist
  1810. * @throws java.io.IOException
  1811. * @throws NoWorkTreeException
  1812. * if this is bare, which implies it has no working directory.
  1813. * See {@link #isBare()}.
  1814. */
  1815. @Nullable
  1816. public String readSquashCommitMsg() throws IOException {
  1817. return readCommitMsgFile(Constants.SQUASH_MSG);
  1818. }
  1819. /**
  1820. * Write new content to the file $GIT_DIR/SQUASH_MSG. In this file
  1821. * operations triggering a squashed merge will store a template for the
  1822. * commit message of the squash commit. If <code>null</code> is specified as
  1823. * message the file will be deleted.
  1824. *
  1825. * @param msg
  1826. * the message which should be written or <code>null</code> to
  1827. * delete the file
  1828. * @throws java.io.IOException
  1829. */
  1830. public void writeSquashCommitMsg(String msg) throws IOException {
  1831. File squashMsgFile = new File(gitDir, Constants.SQUASH_MSG);
  1832. writeCommitMsg(squashMsgFile, msg);
  1833. }
  1834. @Nullable
  1835. private String readCommitMsgFile(String msgFilename) throws IOException {
  1836. if (isBare() || getDirectory() == null)
  1837. throw new NoWorkTreeException();
  1838. File mergeMsgFile = new File(getDirectory(), msgFilename);
  1839. try {
  1840. return RawParseUtils.decode(IO.readFully(mergeMsgFile));
  1841. } catch (FileNotFoundException e) {
  1842. if (mergeMsgFile.exists()) {
  1843. throw e;
  1844. }
  1845. // the file has disappeared in the meantime ignore it
  1846. return null;
  1847. }
  1848. }
  1849. private void writeCommitMsg(File msgFile, String msg) throws IOException {
  1850. if (msg != null) {
  1851. try (FileOutputStream fos = new FileOutputStream(msgFile)) {
  1852. fos.write(msg.getBytes(UTF_8));
  1853. }
  1854. } else {
  1855. FileUtils.delete(msgFile, FileUtils.SKIP_MISSING);
  1856. }
  1857. }
  1858. /**
  1859. * Read a file from the git directory.
  1860. *
  1861. * @param filename
  1862. * @return the raw contents or {@code null} if the file doesn't exist or is
  1863. * empty
  1864. * @throws IOException
  1865. */
  1866. private byte[] readGitDirectoryFile(String filename) throws IOException {
  1867. File file = new File(getDirectory(), filename);
  1868. try {
  1869. byte[] raw = IO.readFully(file);
  1870. return raw.length > 0 ? raw : null;
  1871. } catch (FileNotFoundException notFound) {
  1872. if (file.exists()) {
  1873. throw notFound;
  1874. }
  1875. return null;
  1876. }
  1877. }
  1878. /**
  1879. * Write the given heads to a file in the git directory.
  1880. *
  1881. * @param heads
  1882. * a list of object ids to write or null if the file should be
  1883. * deleted.
  1884. * @param filename
  1885. * @throws FileNotFoundException
  1886. * @throws IOException
  1887. */
  1888. private void writeHeadsFile(List<? extends ObjectId> heads, String filename)
  1889. throws FileNotFoundException, IOException {
  1890. File headsFile = new File(getDirectory(), filename);
  1891. if (heads != null) {
  1892. try (OutputStream bos = new BufferedOutputStream(
  1893. new FileOutputStream(headsFile))) {
  1894. for (ObjectId id : heads) {
  1895. id.copyTo(bos);
  1896. bos.write('\n');
  1897. }
  1898. }
  1899. } else {
  1900. FileUtils.delete(headsFile, FileUtils.SKIP_MISSING);
  1901. }
  1902. }
  1903. /**
  1904. * Read a file formatted like the git-rebase-todo file. The "done" file is
  1905. * also formatted like the git-rebase-todo file. These files can be found in
  1906. * .git/rebase-merge/ or .git/rebase-append/ folders.
  1907. *
  1908. * @param path
  1909. * path to the file relative to the repository's git-dir. E.g.
  1910. * "rebase-merge/git-rebase-todo" or "rebase-append/done"
  1911. * @param includeComments
  1912. * <code>true</code> if also comments should be reported
  1913. * @return the list of steps
  1914. * @throws java.io.IOException
  1915. * @since 3.2
  1916. */
  1917. @NonNull
  1918. public List<RebaseTodoLine> readRebaseTodo(String path,
  1919. boolean includeComments)
  1920. throws IOException {
  1921. return new RebaseTodoFile(this).readRebaseTodo(path, includeComments);
  1922. }
  1923. /**
  1924. * Write a file formatted like a git-rebase-todo file.
  1925. *
  1926. * @param path
  1927. * path to the file relative to the repository's git-dir. E.g.
  1928. * "rebase-merge/git-rebase-todo" or "rebase-append/done"
  1929. * @param steps
  1930. * the steps to be written
  1931. * @param append
  1932. * whether to append to an existing file or to write a new file
  1933. * @throws java.io.IOException
  1934. * @since 3.2
  1935. */
  1936. public void writeRebaseTodoFile(String path, List<RebaseTodoLine> steps,
  1937. boolean append)
  1938. throws IOException {
  1939. new RebaseTodoFile(this).writeRebaseTodoFile(path, steps, append);
  1940. }
  1941. /**
  1942. * Get the names of all known remotes
  1943. *
  1944. * @return the names of all known remotes
  1945. * @since 3.4
  1946. */
  1947. @NonNull
  1948. public Set<String> getRemoteNames() {
  1949. return getConfig()
  1950. .getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
  1951. }
  1952. /**
  1953. * Check whether any housekeeping is required; if yes, run garbage
  1954. * collection; if not, exit without performing any work. Some JGit commands
  1955. * run autoGC after performing operations that could create many loose
  1956. * objects.
  1957. * <p>
  1958. * Currently this option is supported for repositories of type
  1959. * {@code FileRepository} only. See
  1960. * {@link org.eclipse.jgit.internal.storage.file.GC#setAuto(boolean)} for
  1961. * configuration details.
  1962. *
  1963. * @param monitor
  1964. * to report progress
  1965. * @since 4.6
  1966. */
  1967. public void autoGC(ProgressMonitor monitor) {
  1968. // default does nothing
  1969. }
  1970. }