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

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