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

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