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

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