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

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