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

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