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 58KB

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