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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100
  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 java.io.BufferedOutputStream;
  51. import java.io.File;
  52. import java.io.FileNotFoundException;
  53. import java.io.FileOutputStream;
  54. import java.io.IOException;
  55. import java.io.OutputStream;
  56. import java.net.URISyntaxException;
  57. import java.text.MessageFormat;
  58. import java.util.Collection;
  59. import java.util.Collections;
  60. import java.util.HashMap;
  61. import java.util.HashSet;
  62. import java.util.LinkedList;
  63. import java.util.List;
  64. import java.util.Map;
  65. import java.util.Set;
  66. import java.util.concurrent.atomic.AtomicInteger;
  67. import java.util.concurrent.atomic.AtomicLong;
  68. import java.util.regex.Pattern;
  69. import org.eclipse.jgit.annotations.NonNull;
  70. import org.eclipse.jgit.annotations.Nullable;
  71. import org.eclipse.jgit.attributes.AttributesNodeProvider;
  72. import org.eclipse.jgit.dircache.DirCache;
  73. import org.eclipse.jgit.errors.AmbiguousObjectException;
  74. import org.eclipse.jgit.errors.CorruptObjectException;
  75. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  76. import org.eclipse.jgit.errors.MissingObjectException;
  77. import org.eclipse.jgit.errors.NoWorkTreeException;
  78. import org.eclipse.jgit.errors.RevisionSyntaxException;
  79. import org.eclipse.jgit.events.IndexChangedEvent;
  80. import org.eclipse.jgit.events.IndexChangedListener;
  81. import org.eclipse.jgit.events.ListenerList;
  82. import org.eclipse.jgit.events.RepositoryEvent;
  83. import org.eclipse.jgit.internal.JGitText;
  84. import org.eclipse.jgit.revwalk.RevBlob;
  85. import org.eclipse.jgit.revwalk.RevCommit;
  86. import org.eclipse.jgit.revwalk.RevObject;
  87. import org.eclipse.jgit.revwalk.RevTree;
  88. import org.eclipse.jgit.revwalk.RevWalk;
  89. import org.eclipse.jgit.transport.RefSpec;
  90. import org.eclipse.jgit.transport.RemoteConfig;
  91. import org.eclipse.jgit.treewalk.TreeWalk;
  92. import org.eclipse.jgit.util.FS;
  93. import org.eclipse.jgit.util.FileUtils;
  94. import org.eclipse.jgit.util.IO;
  95. import org.eclipse.jgit.util.RawParseUtils;
  96. import org.eclipse.jgit.util.SystemReader;
  97. import org.slf4j.Logger;
  98. import org.slf4j.LoggerFactory;
  99. /**
  100. * Represents a Git repository.
  101. * <p>
  102. * A repository holds all objects and refs used for managing source code (could
  103. * be any type of file, but source code is what SCM's are typically used for).
  104. * <p>
  105. * The thread-safety of a {@link org.eclipse.jgit.lib.Repository} very much
  106. * depends on the concrete implementation. Applications working with a generic
  107. * {@code Repository} type must not assume the instance is thread-safe.
  108. * <ul>
  109. * <li>{@code FileRepository} is thread-safe.
  110. * <li>{@code DfsRepository} thread-safety is determined by its subclass.
  111. * </ul>
  112. */
  113. public abstract class Repository implements AutoCloseable {
  114. private static final Logger LOG = LoggerFactory.getLogger(Repository.class);
  115. private static final ListenerList globalListeners = new ListenerList();
  116. /**
  117. * Branch names containing slashes should not have a name component that is
  118. * one of the reserved device names on Windows.
  119. *
  120. * @see #normalizeBranchName(String)
  121. */
  122. private static final Pattern FORBIDDEN_BRANCH_NAME_COMPONENTS = Pattern
  123. .compile(
  124. "(^|/)(aux|com[1-9]|con|lpt[1-9]|nul|prn)(\\.[^/]*)?", //$NON-NLS-1$
  125. Pattern.CASE_INSENSITIVE);
  126. /**
  127. * Get the global listener list observing all events in this JVM.
  128. *
  129. * @return the global listener list observing all events in this JVM.
  130. */
  131. public static ListenerList getGlobalListenerList() {
  132. return globalListeners;
  133. }
  134. /** Use counter */
  135. final AtomicInteger useCnt = new AtomicInteger(1);
  136. final AtomicLong closedAt = new AtomicLong();
  137. /** Metadata directory holding the repository's critical files. */
  138. private final File gitDir;
  139. /** File abstraction used to resolve paths. */
  140. private final FS fs;
  141. private final ListenerList myListeners = new ListenerList();
  142. /** If not bare, the top level directory of the working files. */
  143. private final File workTree;
  144. /** If not bare, the index file caching the working file states. */
  145. private final File indexFile;
  146. /**
  147. * Initialize a new repository instance.
  148. *
  149. * @param options
  150. * options to configure the repository.
  151. */
  152. protected Repository(final BaseRepositoryBuilder options) {
  153. gitDir = options.getGitDir();
  154. fs = options.getFS();
  155. workTree = options.getWorkTree();
  156. indexFile = options.getIndexFile();
  157. }
  158. /**
  159. * Get listeners observing only events on this repository.
  160. *
  161. * @return listeners observing only events on this repository.
  162. */
  163. @NonNull
  164. public ListenerList getListenerList() {
  165. return myListeners;
  166. }
  167. /**
  168. * Fire an event to all registered listeners.
  169. * <p>
  170. * The source repository of the event is automatically set to this
  171. * repository, before the event is delivered to any listeners.
  172. *
  173. * @param event
  174. * the event to deliver.
  175. */
  176. public void fireEvent(RepositoryEvent<?> event) {
  177. event.setRepository(this);
  178. myListeners.dispatch(event);
  179. globalListeners.dispatch(event);
  180. }
  181. /**
  182. * Create a new Git repository.
  183. * <p>
  184. * Repository with working tree is created using this method. This method is
  185. * the same as {@code create(false)}.
  186. *
  187. * @throws java.io.IOException
  188. * @see #create(boolean)
  189. */
  190. public void create() throws IOException {
  191. create(false);
  192. }
  193. /**
  194. * Create a new Git repository initializing the necessary files and
  195. * directories.
  196. *
  197. * @param bare
  198. * if true, a bare repository (a repository without a working
  199. * directory) is created.
  200. * @throws java.io.IOException
  201. * in case of IO problem
  202. */
  203. public abstract void create(boolean bare) throws IOException;
  204. /**
  205. * Get local metadata directory
  206. *
  207. * @return local metadata directory; {@code null} if repository isn't local.
  208. */
  209. /*
  210. * TODO This method should be annotated as Nullable, because in some
  211. * specific configurations metadata is not located in the local file system
  212. * (for example in memory databases). In "usual" repositories this
  213. * annotation would only cause compiler errors at places where the actual
  214. * directory can never be null.
  215. */
  216. public File getDirectory() {
  217. return gitDir;
  218. }
  219. /**
  220. * Get the object database which stores this repository's data.
  221. *
  222. * @return the object database which stores this repository's data.
  223. */
  224. @NonNull
  225. public abstract ObjectDatabase getObjectDatabase();
  226. /**
  227. * Create a new inserter to create objects in {@link #getObjectDatabase()}.
  228. *
  229. * @return a new inserter to create objects in {@link #getObjectDatabase()}.
  230. */
  231. @NonNull
  232. public ObjectInserter newObjectInserter() {
  233. return getObjectDatabase().newInserter();
  234. }
  235. /**
  236. * Create a new reader to read objects from {@link #getObjectDatabase()}.
  237. *
  238. * @return a new reader to read objects from {@link #getObjectDatabase()}.
  239. */
  240. @NonNull
  241. public ObjectReader newObjectReader() {
  242. return getObjectDatabase().newReader();
  243. }
  244. /**
  245. * Get the reference database which stores the reference namespace.
  246. *
  247. * @return the reference database which stores the reference namespace.
  248. */
  249. @NonNull
  250. public abstract RefDatabase getRefDatabase();
  251. /**
  252. * Get the configuration of this repository.
  253. *
  254. * @return the configuration of this repository.
  255. */
  256. @NonNull
  257. public abstract StoredConfig getConfig();
  258. /**
  259. * Create a new {@link org.eclipse.jgit.attributes.AttributesNodeProvider}.
  260. *
  261. * @return a new {@link org.eclipse.jgit.attributes.AttributesNodeProvider}.
  262. * This {@link org.eclipse.jgit.attributes.AttributesNodeProvider}
  263. * is lazy loaded only once. It means that it will not be updated
  264. * after loading. Prefer creating new instance for each use.
  265. * @since 4.2
  266. */
  267. @NonNull
  268. public abstract AttributesNodeProvider createAttributesNodeProvider();
  269. /**
  270. * Get the used file system abstraction.
  271. *
  272. * @return the used file system abstraction, or or {@code null} if
  273. * repository isn't local.
  274. */
  275. /*
  276. * TODO This method should be annotated as Nullable, because in some
  277. * specific configurations metadata is not located in the local file system
  278. * (for example in memory databases). In "usual" repositories this
  279. * annotation would only cause compiler errors at places where the actual
  280. * directory can never be null.
  281. */
  282. public FS getFS() {
  283. return fs;
  284. }
  285. /**
  286. * Whether the specified object is stored in this repo or any of the known
  287. * shared repositories.
  288. *
  289. * @param objectId
  290. * a {@link org.eclipse.jgit.lib.AnyObjectId} object.
  291. * @return true if the specified object is stored in this repo or any of the
  292. * known shared repositories.
  293. */
  294. public boolean hasObject(AnyObjectId objectId) {
  295. try {
  296. return getObjectDatabase().has(objectId);
  297. } catch (IOException e) {
  298. // Legacy API, assume error means "no"
  299. return false;
  300. }
  301. }
  302. /**
  303. * Open an object from this repository.
  304. * <p>
  305. * This is a one-shot call interface which may be faster than allocating a
  306. * {@link #newObjectReader()} to perform the lookup.
  307. *
  308. * @param objectId
  309. * identity of the object to open.
  310. * @return a {@link org.eclipse.jgit.lib.ObjectLoader} for accessing the
  311. * object.
  312. * @throws org.eclipse.jgit.errors.MissingObjectException
  313. * the object does not exist.
  314. * @throws java.io.IOException
  315. * the object store cannot be accessed.
  316. */
  317. @NonNull
  318. public ObjectLoader open(final AnyObjectId objectId)
  319. throws MissingObjectException, IOException {
  320. return getObjectDatabase().open(objectId);
  321. }
  322. /**
  323. * Open an object from this repository.
  324. * <p>
  325. * This is a one-shot call interface which may be faster than allocating a
  326. * {@link #newObjectReader()} to perform the lookup.
  327. *
  328. * @param objectId
  329. * identity of the object to open.
  330. * @param typeHint
  331. * hint about the type of object being requested, e.g.
  332. * {@link org.eclipse.jgit.lib.Constants#OBJ_BLOB};
  333. * {@link org.eclipse.jgit.lib.ObjectReader#OBJ_ANY} if the
  334. * object type is not known, or does not matter to the caller.
  335. * @return a {@link org.eclipse.jgit.lib.ObjectLoader} for accessing the
  336. * object.
  337. * @throws org.eclipse.jgit.errors.MissingObjectException
  338. * the object does not exist.
  339. * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
  340. * typeHint was not OBJ_ANY, and the object's actual type does
  341. * not match typeHint.
  342. * @throws java.io.IOException
  343. * the object store cannot be accessed.
  344. */
  345. @NonNull
  346. public ObjectLoader open(AnyObjectId objectId, int typeHint)
  347. throws MissingObjectException, IncorrectObjectTypeException,
  348. IOException {
  349. return getObjectDatabase().open(objectId, typeHint);
  350. }
  351. /**
  352. * Create a command to update, create or delete a ref in this repository.
  353. *
  354. * @param ref
  355. * name of the ref the caller wants to modify.
  356. * @return an update command. The caller must finish populating this command
  357. * and then invoke one of the update methods to actually make a
  358. * change.
  359. * @throws java.io.IOException
  360. * a symbolic ref was passed in and could not be resolved back
  361. * to the base ref, as the symbolic ref could not be read.
  362. */
  363. @NonNull
  364. public RefUpdate updateRef(final String ref) throws IOException {
  365. return updateRef(ref, false);
  366. }
  367. /**
  368. * Create a command to update, create or delete a ref in this repository.
  369. *
  370. * @param ref
  371. * name of the ref the caller wants to modify.
  372. * @param detach
  373. * true to create a detached head
  374. * @return an update command. The caller must finish populating this command
  375. * and then invoke one of the update methods to actually make a
  376. * change.
  377. * @throws java.io.IOException
  378. * a symbolic ref was passed in and could not be resolved back
  379. * to the base ref, as the symbolic ref could not be read.
  380. */
  381. @NonNull
  382. public RefUpdate updateRef(final String ref, final boolean detach) throws IOException {
  383. return getRefDatabase().newUpdate(ref, detach);
  384. }
  385. /**
  386. * Create a command to rename a ref in this repository
  387. *
  388. * @param fromRef
  389. * name of ref to rename from
  390. * @param toRef
  391. * name of ref to rename to
  392. * @return an update command that knows how to rename a branch to another.
  393. * @throws java.io.IOException
  394. * the rename could not be performed.
  395. */
  396. @NonNull
  397. public RefRename renameRef(final String fromRef, final String toRef) throws IOException {
  398. return getRefDatabase().newRename(fromRef, toRef);
  399. }
  400. /**
  401. * Parse a git revision string and return an object id.
  402. *
  403. * Combinations of these operators are supported:
  404. * <ul>
  405. * <li><b>HEAD</b>, <b>MERGE_HEAD</b>, <b>FETCH_HEAD</b></li>
  406. * <li><b>SHA-1</b>: a complete or abbreviated SHA-1</li>
  407. * <li><b>refs/...</b>: a complete reference name</li>
  408. * <li><b>short-name</b>: a short reference name under {@code refs/heads},
  409. * {@code refs/tags}, or {@code refs/remotes} namespace</li>
  410. * <li><b>tag-NN-gABBREV</b>: output from describe, parsed by treating
  411. * {@code ABBREV} as an abbreviated SHA-1.</li>
  412. * <li><i>id</i><b>^</b>: first parent of commit <i>id</i>, this is the same
  413. * as {@code id^1}</li>
  414. * <li><i>id</i><b>^0</b>: ensure <i>id</i> is a commit</li>
  415. * <li><i>id</i><b>^n</b>: n-th parent of commit <i>id</i></li>
  416. * <li><i>id</i><b>~n</b>: n-th historical ancestor of <i>id</i>, by first
  417. * parent. {@code id~3} is equivalent to {@code id^1^1^1} or {@code id^^^}.</li>
  418. * <li><i>id</i><b>:path</b>: Lookup path under tree named by <i>id</i></li>
  419. * <li><i>id</i><b>^{commit}</b>: ensure <i>id</i> is a commit</li>
  420. * <li><i>id</i><b>^{tree}</b>: ensure <i>id</i> is a tree</li>
  421. * <li><i>id</i><b>^{tag}</b>: ensure <i>id</i> is a tag</li>
  422. * <li><i>id</i><b>^{blob}</b>: ensure <i>id</i> is a blob</li>
  423. * </ul>
  424. *
  425. * <p>
  426. * The following operators are specified by Git conventions, but are not
  427. * supported by this method:
  428. * <ul>
  429. * <li><b>ref@{n}</b>: n-th version of ref as given by its reflog</li>
  430. * <li><b>ref@{time}</b>: value of ref at the designated time</li>
  431. * </ul>
  432. *
  433. * @param revstr
  434. * A git object references expression
  435. * @return an ObjectId or {@code null} if revstr can't be resolved to any
  436. * ObjectId
  437. * @throws org.eclipse.jgit.errors.AmbiguousObjectException
  438. * {@code revstr} contains an abbreviated ObjectId and this
  439. * repository contains more than one object which match to the
  440. * input abbreviation.
  441. * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
  442. * the id parsed does not meet the type required to finish
  443. * applying the operators in the expression.
  444. * @throws org.eclipse.jgit.errors.RevisionSyntaxException
  445. * the expression is not supported by this implementation, or
  446. * does not meet the standard syntax.
  447. * @throws java.io.IOException
  448. * on serious errors
  449. */
  450. @Nullable
  451. public ObjectId resolve(final String revstr)
  452. throws AmbiguousObjectException, IncorrectObjectTypeException,
  453. RevisionSyntaxException, IOException {
  454. try (RevWalk rw = new RevWalk(this)) {
  455. Object resolved = resolve(rw, revstr);
  456. if (resolved instanceof String) {
  457. final Ref ref = getRef((String)resolved);
  458. return ref != null ? ref.getLeaf().getObjectId() : null;
  459. } else {
  460. return (ObjectId) resolved;
  461. }
  462. }
  463. }
  464. /**
  465. * Simplify an expression, but unlike {@link #resolve(String)} it will not
  466. * resolve a branch passed or resulting from the expression, such as @{-}.
  467. * Thus this method can be used to process an expression to a method that
  468. * expects a branch or revision id.
  469. *
  470. * @param revstr a {@link java.lang.String} object.
  471. * @return object id or ref name from resolved expression or {@code null} if
  472. * given expression cannot be resolved
  473. * @throws org.eclipse.jgit.errors.AmbiguousObjectException
  474. * @throws java.io.IOException
  475. */
  476. @Nullable
  477. public String simplify(final String revstr)
  478. throws AmbiguousObjectException, IOException {
  479. try (RevWalk rw = new RevWalk(this)) {
  480. Object resolved = resolve(rw, revstr);
  481. if (resolved != null)
  482. if (resolved instanceof String)
  483. return (String) resolved;
  484. else
  485. return ((AnyObjectId) resolved).getName();
  486. return null;
  487. }
  488. }
  489. @Nullable
  490. private Object resolve(final RevWalk rw, final String revstr)
  491. throws IOException {
  492. char[] revChars = revstr.toCharArray();
  493. RevObject rev = null;
  494. String name = null;
  495. int done = 0;
  496. for (int i = 0; i < revChars.length; ++i) {
  497. switch (revChars[i]) {
  498. case '^':
  499. if (rev == null) {
  500. if (name == null)
  501. if (done == 0)
  502. name = new String(revChars, done, i);
  503. else {
  504. done = i + 1;
  505. break;
  506. }
  507. rev = parseSimple(rw, name);
  508. name = null;
  509. if (rev == null)
  510. return null;
  511. }
  512. if (i + 1 < revChars.length) {
  513. switch (revChars[i + 1]) {
  514. case '0':
  515. case '1':
  516. case '2':
  517. case '3':
  518. case '4':
  519. case '5':
  520. case '6':
  521. case '7':
  522. case '8':
  523. case '9':
  524. int j;
  525. rev = rw.parseCommit(rev);
  526. for (j = i + 1; j < revChars.length; ++j) {
  527. if (!Character.isDigit(revChars[j]))
  528. break;
  529. }
  530. String parentnum = new String(revChars, i + 1, j - i
  531. - 1);
  532. int pnum;
  533. try {
  534. pnum = Integer.parseInt(parentnum);
  535. } catch (NumberFormatException e) {
  536. throw new RevisionSyntaxException(
  537. JGitText.get().invalidCommitParentNumber,
  538. revstr);
  539. }
  540. if (pnum != 0) {
  541. RevCommit commit = (RevCommit) rev;
  542. if (pnum > commit.getParentCount())
  543. rev = null;
  544. else
  545. rev = commit.getParent(pnum - 1);
  546. }
  547. i = j - 1;
  548. done = j;
  549. break;
  550. case '{':
  551. int k;
  552. String item = null;
  553. for (k = i + 2; k < revChars.length; ++k) {
  554. if (revChars[k] == '}') {
  555. item = new String(revChars, i + 2, k - i - 2);
  556. break;
  557. }
  558. }
  559. i = k;
  560. if (item != null)
  561. if (item.equals("tree")) { //$NON-NLS-1$
  562. rev = rw.parseTree(rev);
  563. } else if (item.equals("commit")) { //$NON-NLS-1$
  564. rev = rw.parseCommit(rev);
  565. } else if (item.equals("blob")) { //$NON-NLS-1$
  566. rev = rw.peel(rev);
  567. if (!(rev instanceof RevBlob))
  568. throw new IncorrectObjectTypeException(rev,
  569. Constants.TYPE_BLOB);
  570. } else if (item.equals("")) { //$NON-NLS-1$
  571. rev = rw.peel(rev);
  572. } else
  573. throw new RevisionSyntaxException(revstr);
  574. else
  575. throw new RevisionSyntaxException(revstr);
  576. done = k;
  577. break;
  578. default:
  579. rev = rw.peel(rev);
  580. if (rev instanceof RevCommit) {
  581. RevCommit commit = ((RevCommit) rev);
  582. if (commit.getParentCount() == 0)
  583. rev = null;
  584. else
  585. rev = commit.getParent(0);
  586. } else
  587. throw new IncorrectObjectTypeException(rev,
  588. Constants.TYPE_COMMIT);
  589. }
  590. } else {
  591. rev = rw.peel(rev);
  592. if (rev instanceof RevCommit) {
  593. RevCommit commit = ((RevCommit) rev);
  594. if (commit.getParentCount() == 0)
  595. rev = null;
  596. else
  597. rev = commit.getParent(0);
  598. } else
  599. throw new IncorrectObjectTypeException(rev,
  600. Constants.TYPE_COMMIT);
  601. }
  602. done = i + 1;
  603. break;
  604. case '~':
  605. if (rev == null) {
  606. if (name == null)
  607. if (done == 0)
  608. name = new String(revChars, done, i);
  609. else {
  610. done = i + 1;
  611. break;
  612. }
  613. rev = parseSimple(rw, name);
  614. name = null;
  615. if (rev == null)
  616. return null;
  617. }
  618. rev = rw.peel(rev);
  619. if (!(rev instanceof RevCommit))
  620. throw new IncorrectObjectTypeException(rev,
  621. Constants.TYPE_COMMIT);
  622. int l;
  623. for (l = i + 1; l < revChars.length; ++l) {
  624. if (!Character.isDigit(revChars[l]))
  625. break;
  626. }
  627. int dist;
  628. if (l - i > 1) {
  629. String distnum = new String(revChars, i + 1, l - i - 1);
  630. try {
  631. dist = Integer.parseInt(distnum);
  632. } catch (NumberFormatException e) {
  633. throw new RevisionSyntaxException(
  634. JGitText.get().invalidAncestryLength, revstr);
  635. }
  636. } else
  637. dist = 1;
  638. while (dist > 0) {
  639. RevCommit commit = (RevCommit) rev;
  640. if (commit.getParentCount() == 0) {
  641. rev = null;
  642. break;
  643. }
  644. commit = commit.getParent(0);
  645. rw.parseHeaders(commit);
  646. rev = commit;
  647. --dist;
  648. }
  649. i = l - 1;
  650. done = l;
  651. break;
  652. case '@':
  653. if (rev != null)
  654. throw new RevisionSyntaxException(revstr);
  655. if (i + 1 < revChars.length && revChars[i + 1] != '{')
  656. continue;
  657. int m;
  658. String time = null;
  659. for (m = i + 2; m < revChars.length; ++m) {
  660. if (revChars[m] == '}') {
  661. time = new String(revChars, i + 2, m - i - 2);
  662. break;
  663. }
  664. }
  665. if (time != null) {
  666. if (time.equals("upstream")) { //$NON-NLS-1$
  667. if (name == null)
  668. name = new String(revChars, done, i);
  669. if (name.equals("")) //$NON-NLS-1$
  670. // Currently checked out branch, HEAD if
  671. // detached
  672. name = Constants.HEAD;
  673. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  674. throw new RevisionSyntaxException(MessageFormat
  675. .format(JGitText.get().invalidRefName,
  676. name),
  677. revstr);
  678. Ref ref = getRef(name);
  679. name = null;
  680. if (ref == null)
  681. return null;
  682. if (ref.isSymbolic())
  683. ref = ref.getLeaf();
  684. name = ref.getName();
  685. RemoteConfig remoteConfig;
  686. try {
  687. remoteConfig = new RemoteConfig(getConfig(),
  688. "origin"); //$NON-NLS-1$
  689. } catch (URISyntaxException e) {
  690. throw new RevisionSyntaxException(revstr);
  691. }
  692. String remoteBranchName = getConfig()
  693. .getString(
  694. ConfigConstants.CONFIG_BRANCH_SECTION,
  695. Repository.shortenRefName(ref.getName()),
  696. ConfigConstants.CONFIG_KEY_MERGE);
  697. List<RefSpec> fetchRefSpecs = remoteConfig
  698. .getFetchRefSpecs();
  699. for (RefSpec refSpec : fetchRefSpecs) {
  700. if (refSpec.matchSource(remoteBranchName)) {
  701. RefSpec expandFromSource = refSpec
  702. .expandFromSource(remoteBranchName);
  703. name = expandFromSource.getDestination();
  704. break;
  705. }
  706. }
  707. if (name == null)
  708. throw new RevisionSyntaxException(revstr);
  709. } else if (time.matches("^-\\d+$")) { //$NON-NLS-1$
  710. if (name != null)
  711. throw new RevisionSyntaxException(revstr);
  712. else {
  713. String previousCheckout = resolveReflogCheckout(-Integer
  714. .parseInt(time));
  715. if (ObjectId.isId(previousCheckout))
  716. rev = parseSimple(rw, previousCheckout);
  717. else
  718. name = previousCheckout;
  719. }
  720. } else {
  721. if (name == null)
  722. name = new String(revChars, done, i);
  723. if (name.equals("")) //$NON-NLS-1$
  724. name = Constants.HEAD;
  725. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  726. throw new RevisionSyntaxException(MessageFormat
  727. .format(JGitText.get().invalidRefName,
  728. name),
  729. revstr);
  730. Ref ref = getRef(name);
  731. name = null;
  732. if (ref == null)
  733. return null;
  734. // @{n} means current branch, not HEAD@{1} unless
  735. // detached
  736. if (ref.isSymbolic())
  737. ref = ref.getLeaf();
  738. rev = resolveReflog(rw, ref, time);
  739. }
  740. i = m;
  741. } else
  742. throw new RevisionSyntaxException(revstr);
  743. break;
  744. case ':': {
  745. RevTree tree;
  746. if (rev == null) {
  747. if (name == null)
  748. name = new String(revChars, done, i);
  749. if (name.equals("")) //$NON-NLS-1$
  750. name = Constants.HEAD;
  751. rev = parseSimple(rw, name);
  752. name = null;
  753. }
  754. if (rev == null)
  755. return null;
  756. tree = rw.parseTree(rev);
  757. if (i == revChars.length - 1)
  758. return tree.copy();
  759. TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(),
  760. new String(revChars, i + 1, revChars.length - i - 1),
  761. tree);
  762. return tw != null ? tw.getObjectId(0) : null;
  763. }
  764. default:
  765. if (rev != null)
  766. throw new RevisionSyntaxException(revstr);
  767. }
  768. }
  769. if (rev != null)
  770. return rev.copy();
  771. if (name != null)
  772. return name;
  773. if (done == revstr.length())
  774. return null;
  775. name = revstr.substring(done);
  776. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  777. throw new RevisionSyntaxException(
  778. MessageFormat.format(JGitText.get().invalidRefName, name),
  779. revstr);
  780. if (getRef(name) != null)
  781. return name;
  782. return resolveSimple(name);
  783. }
  784. private static boolean isHex(char c) {
  785. return ('0' <= c && c <= '9') //
  786. || ('a' <= c && c <= 'f') //
  787. || ('A' <= c && c <= 'F');
  788. }
  789. private static boolean isAllHex(String str, int ptr) {
  790. while (ptr < str.length()) {
  791. if (!isHex(str.charAt(ptr++)))
  792. return false;
  793. }
  794. return true;
  795. }
  796. @Nullable
  797. private RevObject parseSimple(RevWalk rw, String revstr) throws IOException {
  798. ObjectId id = resolveSimple(revstr);
  799. return id != null ? rw.parseAny(id) : null;
  800. }
  801. @Nullable
  802. private ObjectId resolveSimple(final String revstr) throws IOException {
  803. if (ObjectId.isId(revstr))
  804. return ObjectId.fromString(revstr);
  805. if (Repository.isValidRefName("x/" + revstr)) { //$NON-NLS-1$
  806. Ref r = getRefDatabase().getRef(revstr);
  807. if (r != null)
  808. return r.getObjectId();
  809. }
  810. if (AbbreviatedObjectId.isId(revstr))
  811. return resolveAbbreviation(revstr);
  812. int dashg = revstr.indexOf("-g"); //$NON-NLS-1$
  813. if ((dashg + 5) < revstr.length() && 0 <= dashg
  814. && isHex(revstr.charAt(dashg + 2))
  815. && isHex(revstr.charAt(dashg + 3))
  816. && isAllHex(revstr, dashg + 4)) {
  817. // Possibly output from git describe?
  818. String s = revstr.substring(dashg + 2);
  819. if (AbbreviatedObjectId.isId(s))
  820. return resolveAbbreviation(s);
  821. }
  822. return null;
  823. }
  824. @Nullable
  825. private String resolveReflogCheckout(int checkoutNo)
  826. throws IOException {
  827. ReflogReader reader = getReflogReader(Constants.HEAD);
  828. if (reader == null) {
  829. return null;
  830. }
  831. List<ReflogEntry> reflogEntries = reader.getReverseEntries();
  832. for (ReflogEntry entry : reflogEntries) {
  833. CheckoutEntry checkout = entry.parseCheckout();
  834. if (checkout != null)
  835. if (checkoutNo-- == 1)
  836. return checkout.getFromBranch();
  837. }
  838. return null;
  839. }
  840. private RevCommit resolveReflog(RevWalk rw, Ref ref, String time)
  841. throws IOException {
  842. int number;
  843. try {
  844. number = Integer.parseInt(time);
  845. } catch (NumberFormatException nfe) {
  846. throw new RevisionSyntaxException(MessageFormat.format(
  847. JGitText.get().invalidReflogRevision, time));
  848. }
  849. assert number >= 0;
  850. ReflogReader reader = getReflogReader(ref.getName());
  851. if (reader == null) {
  852. throw new RevisionSyntaxException(
  853. MessageFormat.format(JGitText.get().reflogEntryNotFound,
  854. Integer.valueOf(number), ref.getName()));
  855. }
  856. ReflogEntry entry = reader.getReverseEntry(number);
  857. if (entry == null)
  858. throw new RevisionSyntaxException(MessageFormat.format(
  859. JGitText.get().reflogEntryNotFound,
  860. Integer.valueOf(number), ref.getName()));
  861. return rw.parseCommit(entry.getNewId());
  862. }
  863. @Nullable
  864. private ObjectId resolveAbbreviation(final String revstr) throws IOException,
  865. AmbiguousObjectException {
  866. AbbreviatedObjectId id = AbbreviatedObjectId.fromString(revstr);
  867. try (ObjectReader reader = newObjectReader()) {
  868. Collection<ObjectId> matches = reader.resolve(id);
  869. if (matches.size() == 0)
  870. return null;
  871. else if (matches.size() == 1)
  872. return matches.iterator().next();
  873. else
  874. throw new AmbiguousObjectException(id, matches);
  875. }
  876. }
  877. /**
  878. * Increment the use counter by one, requiring a matched {@link #close()}.
  879. */
  880. public void incrementOpen() {
  881. useCnt.incrementAndGet();
  882. }
  883. /**
  884. * {@inheritDoc}
  885. * <p>
  886. * Decrement the use count, and maybe close resources.
  887. */
  888. @Override
  889. public void close() {
  890. int newCount = useCnt.decrementAndGet();
  891. if (newCount == 0) {
  892. if (RepositoryCache.isCached(this)) {
  893. closedAt.set(System.currentTimeMillis());
  894. } else {
  895. doClose();
  896. }
  897. } else if (newCount == -1) {
  898. // should not happen, only log when useCnt became negative to
  899. // minimize number of log entries
  900. String message = MessageFormat.format(JGitText.get().corruptUseCnt,
  901. toString());
  902. if (LOG.isDebugEnabled()) {
  903. LOG.debug(message, new IllegalStateException());
  904. } else {
  905. LOG.warn(message);
  906. }
  907. if (RepositoryCache.isCached(this)) {
  908. closedAt.set(System.currentTimeMillis());
  909. }
  910. }
  911. }
  912. /**
  913. * Invoked when the use count drops to zero during {@link #close()}.
  914. * <p>
  915. * The default implementation closes the object and ref databases.
  916. */
  917. protected void doClose() {
  918. getObjectDatabase().close();
  919. getRefDatabase().close();
  920. }
  921. /** {@inheritDoc} */
  922. @Override
  923. @NonNull
  924. public String toString() {
  925. String desc;
  926. File directory = getDirectory();
  927. if (directory != null)
  928. desc = directory.getPath();
  929. else
  930. desc = getClass().getSimpleName() + "-" //$NON-NLS-1$
  931. + System.identityHashCode(this);
  932. return "Repository[" + desc + "]"; //$NON-NLS-1$ //$NON-NLS-2$
  933. }
  934. /**
  935. * Get the name of the reference that {@code HEAD} points to.
  936. * <p>
  937. * This is essentially the same as doing:
  938. *
  939. * <pre>
  940. * return exactRef(Constants.HEAD).getTarget().getName()
  941. * </pre>
  942. *
  943. * Except when HEAD is detached, in which case this method returns the
  944. * current ObjectId in hexadecimal string format.
  945. *
  946. * @return name of current branch (for example {@code refs/heads/master}),
  947. * an ObjectId in hex format if the current branch is detached, or
  948. * {@code null} if the repository is corrupt and has no HEAD
  949. * reference.
  950. * @throws java.io.IOException
  951. */
  952. @Nullable
  953. public String getFullBranch() throws IOException {
  954. Ref head = exactRef(Constants.HEAD);
  955. if (head == null) {
  956. return null;
  957. }
  958. if (head.isSymbolic()) {
  959. return head.getTarget().getName();
  960. }
  961. ObjectId objectId = head.getObjectId();
  962. if (objectId != null) {
  963. return objectId.name();
  964. }
  965. return null;
  966. }
  967. /**
  968. * Get the short name of the current branch that {@code HEAD} points to.
  969. * <p>
  970. * This is essentially the same as {@link #getFullBranch()}, except the
  971. * leading prefix {@code refs/heads/} is removed from the reference before
  972. * it is returned to the caller.
  973. *
  974. * @return name of current branch (for example {@code master}), an ObjectId
  975. * in hex format if the current branch is detached, or {@code null}
  976. * if the repository is corrupt and has no HEAD reference.
  977. * @throws java.io.IOException
  978. */
  979. @Nullable
  980. public String getBranch() throws IOException {
  981. String name = getFullBranch();
  982. if (name != null)
  983. return shortenRefName(name);
  984. return null;
  985. }
  986. /**
  987. * Objects known to exist but not expressed by {@link #getAllRefs()}.
  988. * <p>
  989. * When a repository borrows objects from another repository, it can
  990. * advertise that it safely has that other repository's references, without
  991. * exposing any other details about the other repository. This may help
  992. * a client trying to push changes avoid pushing more than it needs to.
  993. *
  994. * @return unmodifiable collection of other known objects.
  995. */
  996. @NonNull
  997. public Set<ObjectId> getAdditionalHaves() {
  998. return Collections.emptySet();
  999. }
  1000. /**
  1001. * Get a ref by name.
  1002. *
  1003. * @param name
  1004. * the name of the ref to lookup. May be a short-hand form, e.g.
  1005. * "master" which is is automatically expanded to
  1006. * "refs/heads/master" if "refs/heads/master" already exists.
  1007. * @return the Ref with the given name, or {@code null} if it does not exist
  1008. * @throws java.io.IOException
  1009. * @deprecated Use {@link #exactRef(String)} or {@link #findRef(String)}
  1010. * instead.
  1011. */
  1012. @Deprecated
  1013. @Nullable
  1014. public Ref getRef(final String name) throws IOException {
  1015. return findRef(name);
  1016. }
  1017. /**
  1018. * Get a ref by name.
  1019. *
  1020. * @param name
  1021. * the name of the ref to lookup. Must not be a short-hand
  1022. * form; e.g., "master" is not automatically expanded to
  1023. * "refs/heads/master".
  1024. * @return the Ref with the given name, or {@code null} if it does not exist
  1025. * @throws java.io.IOException
  1026. * @since 4.2
  1027. */
  1028. @Nullable
  1029. public Ref exactRef(String name) throws IOException {
  1030. return getRefDatabase().exactRef(name);
  1031. }
  1032. /**
  1033. * Search for a ref by (possibly abbreviated) name.
  1034. *
  1035. * @param name
  1036. * the name of the ref to lookup. May be a short-hand form, e.g.
  1037. * "master" which is is automatically expanded to
  1038. * "refs/heads/master" if "refs/heads/master" already exists.
  1039. * @return the Ref with the given name, or {@code null} if it does not exist
  1040. * @throws java.io.IOException
  1041. * @since 4.2
  1042. */
  1043. @Nullable
  1044. public Ref findRef(String name) throws IOException {
  1045. return getRefDatabase().getRef(name);
  1046. }
  1047. /**
  1048. * Get mutable map of all known refs, including symrefs like HEAD that may
  1049. * not point to any object yet.
  1050. *
  1051. * @return mutable map of all known refs (heads, tags, remotes).
  1052. */
  1053. @NonNull
  1054. public Map<String, Ref> getAllRefs() {
  1055. try {
  1056. return getRefDatabase().getRefs(RefDatabase.ALL);
  1057. } catch (IOException e) {
  1058. return new HashMap<>();
  1059. }
  1060. }
  1061. /**
  1062. * Get mutable map of all tags
  1063. *
  1064. * @return mutable map of all tags; key is short tag name ("v1.0") and value
  1065. * of the entry contains the ref with the full tag name
  1066. * ("refs/tags/v1.0").
  1067. */
  1068. @NonNull
  1069. public Map<String, Ref> getTags() {
  1070. try {
  1071. return getRefDatabase().getRefs(Constants.R_TAGS);
  1072. } catch (IOException e) {
  1073. return new HashMap<>();
  1074. }
  1075. }
  1076. /**
  1077. * Peel a possibly unpeeled reference to an annotated tag.
  1078. * <p>
  1079. * If the ref cannot be peeled (as it does not refer to an annotated tag)
  1080. * the peeled id stays null, but {@link org.eclipse.jgit.lib.Ref#isPeeled()}
  1081. * will be true.
  1082. *
  1083. * @param ref
  1084. * The ref to peel
  1085. * @return <code>ref</code> if <code>ref.isPeeled()</code> is true; else a
  1086. * new Ref object representing the same data as Ref, but isPeeled()
  1087. * will be true and getPeeledObjectId will contain the peeled object
  1088. * (or null).
  1089. */
  1090. @NonNull
  1091. public Ref peel(final Ref ref) {
  1092. try {
  1093. return getRefDatabase().peel(ref);
  1094. } catch (IOException e) {
  1095. // Historical accident; if the reference cannot be peeled due
  1096. // to some sort of repository access problem we claim that the
  1097. // same as if the reference was not an annotated tag.
  1098. return ref;
  1099. }
  1100. }
  1101. /**
  1102. * Get a map with all objects referenced by a peeled ref.
  1103. *
  1104. * @return a map with all objects referenced by a peeled ref.
  1105. */
  1106. @NonNull
  1107. public Map<AnyObjectId, Set<Ref>> getAllRefsByPeeledObjectId() {
  1108. Map<String, Ref> allRefs = getAllRefs();
  1109. Map<AnyObjectId, Set<Ref>> ret = new HashMap<>(allRefs.size());
  1110. for (Ref ref : allRefs.values()) {
  1111. ref = peel(ref);
  1112. AnyObjectId target = ref.getPeeledObjectId();
  1113. if (target == null)
  1114. target = ref.getObjectId();
  1115. // We assume most Sets here are singletons
  1116. Set<Ref> oset = ret.put(target, Collections.singleton(ref));
  1117. if (oset != null) {
  1118. // that was not the case (rare)
  1119. if (oset.size() == 1) {
  1120. // Was a read-only singleton, we must copy to a new Set
  1121. oset = new HashSet<>(oset);
  1122. }
  1123. ret.put(target, oset);
  1124. oset.add(ref);
  1125. }
  1126. }
  1127. return ret;
  1128. }
  1129. /**
  1130. * Get the index file location or {@code null} if repository isn't local.
  1131. *
  1132. * @return the index file location or {@code null} if repository isn't
  1133. * local.
  1134. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1135. * if this is bare, which implies it has no working directory.
  1136. * See {@link #isBare()}.
  1137. */
  1138. @NonNull
  1139. public File getIndexFile() throws NoWorkTreeException {
  1140. if (isBare())
  1141. throw new NoWorkTreeException();
  1142. return indexFile;
  1143. }
  1144. /**
  1145. * Locate a reference to a commit and immediately parse its content.
  1146. * <p>
  1147. * This method only returns successfully if the commit object exists,
  1148. * is verified to be a commit, and was parsed without error.
  1149. *
  1150. * @param id
  1151. * name of the commit object.
  1152. * @return reference to the commit object. Never null.
  1153. * @throws org.eclipse.jgit.errors.MissingObjectException
  1154. * the supplied commit does not exist.
  1155. * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
  1156. * the supplied id is not a commit or an annotated tag.
  1157. * @throws java.io.IOException
  1158. * a pack file or loose object could not be read.
  1159. * @since 4.8
  1160. */
  1161. public RevCommit parseCommit(AnyObjectId id) throws IncorrectObjectTypeException,
  1162. IOException, MissingObjectException {
  1163. if (id instanceof RevCommit && ((RevCommit) id).getRawBuffer() != null) {
  1164. return (RevCommit) id;
  1165. }
  1166. try (RevWalk walk = new RevWalk(this)) {
  1167. return walk.parseCommit(id);
  1168. }
  1169. }
  1170. /**
  1171. * Create a new in-core index representation and read an index from disk.
  1172. * <p>
  1173. * The new index will be read before it is returned to the caller. Read
  1174. * failures are reported as exceptions and therefore prevent the method from
  1175. * returning a partially populated index.
  1176. *
  1177. * @return a cache representing the contents of the specified index file (if
  1178. * it exists) or an empty cache if the file does not exist.
  1179. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1180. * if this is bare, which implies it has no working directory.
  1181. * See {@link #isBare()}.
  1182. * @throws java.io.IOException
  1183. * the index file is present but could not be read.
  1184. * @throws org.eclipse.jgit.errors.CorruptObjectException
  1185. * the index file is using a format or extension that this
  1186. * library does not support.
  1187. */
  1188. @NonNull
  1189. public DirCache readDirCache() throws NoWorkTreeException,
  1190. CorruptObjectException, IOException {
  1191. return DirCache.read(this);
  1192. }
  1193. /**
  1194. * Create a new in-core index representation, lock it, and read from disk.
  1195. * <p>
  1196. * The new index will be locked and then read before it is returned to the
  1197. * caller. Read failures are reported as exceptions and therefore prevent
  1198. * the method from returning a partially populated index.
  1199. *
  1200. * @return a cache representing the contents of the specified index file (if
  1201. * it exists) or an empty cache if the file does not exist.
  1202. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1203. * if this is bare, which implies it has no working directory.
  1204. * See {@link #isBare()}.
  1205. * @throws java.io.IOException
  1206. * the index file is present but could not be read, or the lock
  1207. * could not be obtained.
  1208. * @throws org.eclipse.jgit.errors.CorruptObjectException
  1209. * the index file is using a format or extension that this
  1210. * library does not support.
  1211. */
  1212. @NonNull
  1213. public DirCache lockDirCache() throws NoWorkTreeException,
  1214. CorruptObjectException, IOException {
  1215. // we want DirCache to inform us so that we can inform registered
  1216. // listeners about index changes
  1217. IndexChangedListener l = new IndexChangedListener() {
  1218. @Override
  1219. public void onIndexChanged(IndexChangedEvent event) {
  1220. notifyIndexChanged();
  1221. }
  1222. };
  1223. return DirCache.lock(this, l);
  1224. }
  1225. /**
  1226. * Get the repository state
  1227. *
  1228. * @return the repository state
  1229. */
  1230. @NonNull
  1231. public RepositoryState getRepositoryState() {
  1232. if (isBare() || getDirectory() == null)
  1233. return RepositoryState.BARE;
  1234. // Pre Git-1.6 logic
  1235. if (new File(getWorkTree(), ".dotest").exists()) //$NON-NLS-1$
  1236. return RepositoryState.REBASING;
  1237. if (new File(getDirectory(), ".dotest-merge").exists()) //$NON-NLS-1$
  1238. return RepositoryState.REBASING_INTERACTIVE;
  1239. // From 1.6 onwards
  1240. if (new File(getDirectory(),"rebase-apply/rebasing").exists()) //$NON-NLS-1$
  1241. return RepositoryState.REBASING_REBASING;
  1242. if (new File(getDirectory(),"rebase-apply/applying").exists()) //$NON-NLS-1$
  1243. return RepositoryState.APPLY;
  1244. if (new File(getDirectory(),"rebase-apply").exists()) //$NON-NLS-1$
  1245. return RepositoryState.REBASING;
  1246. if (new File(getDirectory(),"rebase-merge/interactive").exists()) //$NON-NLS-1$
  1247. return RepositoryState.REBASING_INTERACTIVE;
  1248. if (new File(getDirectory(),"rebase-merge").exists()) //$NON-NLS-1$
  1249. return RepositoryState.REBASING_MERGE;
  1250. // Both versions
  1251. if (new File(getDirectory(), Constants.MERGE_HEAD).exists()) {
  1252. // we are merging - now check whether we have unmerged paths
  1253. try {
  1254. if (!readDirCache().hasUnmergedPaths()) {
  1255. // no unmerged paths -> return the MERGING_RESOLVED state
  1256. return RepositoryState.MERGING_RESOLVED;
  1257. }
  1258. } catch (IOException e) {
  1259. // Can't decide whether unmerged paths exists. Return
  1260. // MERGING state to be on the safe side (in state MERGING
  1261. // you are not allow to do anything)
  1262. }
  1263. return RepositoryState.MERGING;
  1264. }
  1265. if (new File(getDirectory(), "BISECT_LOG").exists()) //$NON-NLS-1$
  1266. return RepositoryState.BISECTING;
  1267. if (new File(getDirectory(), Constants.CHERRY_PICK_HEAD).exists()) {
  1268. try {
  1269. if (!readDirCache().hasUnmergedPaths()) {
  1270. // no unmerged paths
  1271. return RepositoryState.CHERRY_PICKING_RESOLVED;
  1272. }
  1273. } catch (IOException e) {
  1274. // fall through to CHERRY_PICKING
  1275. }
  1276. return RepositoryState.CHERRY_PICKING;
  1277. }
  1278. if (new File(getDirectory(), Constants.REVERT_HEAD).exists()) {
  1279. try {
  1280. if (!readDirCache().hasUnmergedPaths()) {
  1281. // no unmerged paths
  1282. return RepositoryState.REVERTING_RESOLVED;
  1283. }
  1284. } catch (IOException e) {
  1285. // fall through to REVERTING
  1286. }
  1287. return RepositoryState.REVERTING;
  1288. }
  1289. return RepositoryState.SAFE;
  1290. }
  1291. /**
  1292. * Check validity of a ref name. It must not contain character that has
  1293. * a special meaning in a Git object reference expression. Some other
  1294. * dangerous characters are also excluded.
  1295. *
  1296. * For portability reasons '\' is excluded
  1297. *
  1298. * @param refName a {@link java.lang.String} object.
  1299. * @return true if refName is a valid ref name
  1300. */
  1301. public static boolean isValidRefName(final String refName) {
  1302. final int len = refName.length();
  1303. if (len == 0) {
  1304. return false;
  1305. }
  1306. if (refName.endsWith(LOCK_SUFFIX)) {
  1307. return false;
  1308. }
  1309. // Refs may be stored as loose files so invalid paths
  1310. // on the local system must also be invalid refs.
  1311. try {
  1312. SystemReader.getInstance().checkPath(refName);
  1313. } catch (CorruptObjectException e) {
  1314. return false;
  1315. }
  1316. int components = 1;
  1317. char p = '\0';
  1318. for (int i = 0; i < len; i++) {
  1319. final char c = refName.charAt(i);
  1320. if (c <= ' ')
  1321. return false;
  1322. switch (c) {
  1323. case '.':
  1324. switch (p) {
  1325. case '\0': case '/': case '.':
  1326. return false;
  1327. }
  1328. if (i == len -1)
  1329. return false;
  1330. break;
  1331. case '/':
  1332. if (i == 0 || i == len - 1)
  1333. return false;
  1334. if (p == '/')
  1335. return false;
  1336. components++;
  1337. break;
  1338. case '{':
  1339. if (p == '@')
  1340. return false;
  1341. break;
  1342. case '~': case '^': case ':':
  1343. case '?': case '[': case '*':
  1344. case '\\':
  1345. case '\u007F':
  1346. return false;
  1347. }
  1348. p = c;
  1349. }
  1350. return components > 1;
  1351. }
  1352. /**
  1353. * Normalizes the passed branch name into a possible valid branch name. The
  1354. * validity of the returned name should be checked by a subsequent call to
  1355. * {@link #isValidRefName(String)}.
  1356. * <p>
  1357. * Future implementations of this method could be more restrictive or more
  1358. * lenient about the validity of specific characters in the returned name.
  1359. * <p>
  1360. * The current implementation returns the trimmed input string if this is
  1361. * already a valid branch name. Otherwise it returns a trimmed string with
  1362. * special characters not allowed by {@link #isValidRefName(String)}
  1363. * replaced by hyphens ('-') and blanks replaced by underscores ('_').
  1364. * Leading and trailing slashes, dots, hyphens, and underscores are removed.
  1365. *
  1366. * @param name
  1367. * to normalize
  1368. * @return The normalized name or an empty String if it is {@code null} or
  1369. * empty.
  1370. * @since 4.7
  1371. * @see #isValidRefName(String)
  1372. */
  1373. public static String normalizeBranchName(String name) {
  1374. if (name == null || name.isEmpty()) {
  1375. return ""; //$NON-NLS-1$
  1376. }
  1377. String result = name.trim();
  1378. String fullName = result.startsWith(Constants.R_HEADS) ? result
  1379. : Constants.R_HEADS + result;
  1380. if (isValidRefName(fullName)) {
  1381. return result;
  1382. }
  1383. // All Unicode blanks to underscore
  1384. result = result.replaceAll("(?:\\h|\\v)+", "_"); //$NON-NLS-1$ //$NON-NLS-2$
  1385. StringBuilder b = new StringBuilder();
  1386. char p = '/';
  1387. for (int i = 0, len = result.length(); i < len; i++) {
  1388. char c = result.charAt(i);
  1389. if (c < ' ' || c == 127) {
  1390. continue;
  1391. }
  1392. // Substitute a dash for problematic characters
  1393. switch (c) {
  1394. case '\\':
  1395. case '^':
  1396. case '~':
  1397. case ':':
  1398. case '?':
  1399. case '*':
  1400. case '[':
  1401. case '@':
  1402. case '<':
  1403. case '>':
  1404. case '|':
  1405. case '"':
  1406. c = '-';
  1407. break;
  1408. default:
  1409. break;
  1410. }
  1411. // Collapse multiple slashes, dashes, dots, underscores, and omit
  1412. // dashes, dots, and underscores following a slash.
  1413. switch (c) {
  1414. case '/':
  1415. if (p == '/') {
  1416. continue;
  1417. }
  1418. p = '/';
  1419. break;
  1420. case '.':
  1421. case '_':
  1422. case '-':
  1423. if (p == '/' || p == '-') {
  1424. continue;
  1425. }
  1426. p = '-';
  1427. break;
  1428. default:
  1429. p = c;
  1430. break;
  1431. }
  1432. b.append(c);
  1433. }
  1434. // Strip trailing special characters, and avoid the .lock extension
  1435. result = b.toString().replaceFirst("[/_.-]+$", "") //$NON-NLS-1$ //$NON-NLS-2$
  1436. .replaceAll("\\.lock($|/)", "_lock$1"); //$NON-NLS-1$ //$NON-NLS-2$
  1437. return FORBIDDEN_BRANCH_NAME_COMPONENTS.matcher(result)
  1438. .replaceAll("$1+$2$3"); //$NON-NLS-1$
  1439. }
  1440. /**
  1441. * Strip work dir and return normalized repository path.
  1442. *
  1443. * @param workDir
  1444. * Work dir
  1445. * @param file
  1446. * File whose path shall be stripped of its workdir
  1447. * @return normalized repository relative path or the empty string if the
  1448. * file is not relative to the work directory.
  1449. */
  1450. @NonNull
  1451. public static String stripWorkDir(File workDir, File file) {
  1452. final String filePath = file.getPath();
  1453. final String workDirPath = workDir.getPath();
  1454. if (filePath.length() <= workDirPath.length() ||
  1455. filePath.charAt(workDirPath.length()) != File.separatorChar ||
  1456. !filePath.startsWith(workDirPath)) {
  1457. File absWd = workDir.isAbsolute() ? workDir : workDir.getAbsoluteFile();
  1458. File absFile = file.isAbsolute() ? file : file.getAbsoluteFile();
  1459. if (absWd == workDir && absFile == file)
  1460. return ""; //$NON-NLS-1$
  1461. return stripWorkDir(absWd, absFile);
  1462. }
  1463. String relName = filePath.substring(workDirPath.length() + 1);
  1464. if (File.separatorChar != '/')
  1465. relName = relName.replace(File.separatorChar, '/');
  1466. return relName;
  1467. }
  1468. /**
  1469. * Whether this repository is bare
  1470. *
  1471. * @return true if this is bare, which implies it has no working directory.
  1472. */
  1473. public boolean isBare() {
  1474. return workTree == null;
  1475. }
  1476. /**
  1477. * Get the root directory of the working tree, where files are checked out
  1478. * for viewing and editing.
  1479. *
  1480. * @return the root directory of the working tree, where files are checked
  1481. * out for viewing and editing.
  1482. * @throws org.eclipse.jgit.errors.NoWorkTreeException
  1483. * if this is bare, which implies it has no working directory.
  1484. * See {@link #isBare()}.
  1485. */
  1486. @NonNull
  1487. public File getWorkTree() throws NoWorkTreeException {
  1488. if (isBare())
  1489. throw new NoWorkTreeException();
  1490. return workTree;
  1491. }
  1492. /**
  1493. * Force a scan for changed refs.
  1494. *
  1495. * @throws java.io.IOException
  1496. */
  1497. public abstract void scanForRepoChanges() throws IOException;
  1498. /**
  1499. * Notify that the index changed
  1500. */
  1501. public abstract void notifyIndexChanged();
  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. FileOutputStream fos = new FileOutputStream(msgFile);
  1852. try {
  1853. fos.write(msg.getBytes(Constants.CHARACTER_ENCODING));
  1854. } finally {
  1855. fos.close();
  1856. }
  1857. } else {
  1858. FileUtils.delete(msgFile, FileUtils.SKIP_MISSING);
  1859. }
  1860. }
  1861. /**
  1862. * Read a file from the git directory.
  1863. *
  1864. * @param filename
  1865. * @return the raw contents or {@code null} if the file doesn't exist or is
  1866. * empty
  1867. * @throws IOException
  1868. */
  1869. @Nullable
  1870. private byte[] readGitDirectoryFile(String filename) throws IOException {
  1871. File file = new File(getDirectory(), filename);
  1872. try {
  1873. byte[] raw = IO.readFully(file);
  1874. return raw.length > 0 ? raw : null;
  1875. } catch (FileNotFoundException notFound) {
  1876. if (file.exists()) {
  1877. throw notFound;
  1878. }
  1879. return null;
  1880. }
  1881. }
  1882. /**
  1883. * Write the given heads to a file in the git directory.
  1884. *
  1885. * @param heads
  1886. * a list of object ids to write or null if the file should be
  1887. * deleted.
  1888. * @param filename
  1889. * @throws FileNotFoundException
  1890. * @throws IOException
  1891. */
  1892. private void writeHeadsFile(List<? extends ObjectId> heads, String filename)
  1893. throws FileNotFoundException, IOException {
  1894. File headsFile = new File(getDirectory(), filename);
  1895. if (heads != null) {
  1896. try (OutputStream bos = new BufferedOutputStream(
  1897. new FileOutputStream(headsFile))) {
  1898. for (ObjectId id : heads) {
  1899. id.copyTo(bos);
  1900. bos.write('\n');
  1901. }
  1902. }
  1903. } else {
  1904. FileUtils.delete(headsFile, FileUtils.SKIP_MISSING);
  1905. }
  1906. }
  1907. /**
  1908. * Read a file formatted like the git-rebase-todo file. The "done" file is
  1909. * also formatted like the git-rebase-todo file. These files can be found in
  1910. * .git/rebase-merge/ or .git/rebase-append/ folders.
  1911. *
  1912. * @param path
  1913. * path to the file relative to the repository's git-dir. E.g.
  1914. * "rebase-merge/git-rebase-todo" or "rebase-append/done"
  1915. * @param includeComments
  1916. * <code>true</code> if also comments should be reported
  1917. * @return the list of steps
  1918. * @throws java.io.IOException
  1919. * @since 3.2
  1920. */
  1921. @NonNull
  1922. public List<RebaseTodoLine> readRebaseTodo(String path,
  1923. boolean includeComments)
  1924. throws IOException {
  1925. return new RebaseTodoFile(this).readRebaseTodo(path, includeComments);
  1926. }
  1927. /**
  1928. * Write a file formatted like a git-rebase-todo file.
  1929. *
  1930. * @param path
  1931. * path to the file relative to the repository's git-dir. E.g.
  1932. * "rebase-merge/git-rebase-todo" or "rebase-append/done"
  1933. * @param steps
  1934. * the steps to be written
  1935. * @param append
  1936. * whether to append to an existing file or to write a new file
  1937. * @throws java.io.IOException
  1938. * @since 3.2
  1939. */
  1940. public void writeRebaseTodoFile(String path, List<RebaseTodoLine> steps,
  1941. boolean append)
  1942. throws IOException {
  1943. new RebaseTodoFile(this).writeRebaseTodoFile(path, steps, append);
  1944. }
  1945. /**
  1946. * Get the names of all known remotes
  1947. *
  1948. * @return the names of all known remotes
  1949. * @since 3.4
  1950. */
  1951. @NonNull
  1952. public Set<String> getRemoteNames() {
  1953. return getConfig()
  1954. .getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
  1955. }
  1956. /**
  1957. * Check whether any housekeeping is required; if yes, run garbage
  1958. * collection; if not, exit without performing any work. Some JGit commands
  1959. * run autoGC after performing operations that could create many loose
  1960. * objects.
  1961. * <p>
  1962. * Currently this option is supported for repositories of type
  1963. * {@code FileRepository} only. See
  1964. * {@link org.eclipse.jgit.internal.storage.file.GC#setAuto(boolean)} for
  1965. * configuration details.
  1966. *
  1967. * @param monitor
  1968. * to report progress
  1969. * @since 4.6
  1970. */
  1971. public void autoGC(ProgressMonitor monitor) {
  1972. // default does nothing
  1973. }
  1974. }