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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  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-2008, Shawn O. Pearce <spearce@spearce.org>
  6. * and other copyright owners as documented in the project's IP log.
  7. *
  8. * This program and the accompanying materials are made available
  9. * under the terms of the Eclipse Distribution License v1.0 which
  10. * accompanies this distribution, is reproduced below, and is
  11. * available at http://www.eclipse.org/org/documents/edl-v10.php
  12. *
  13. * All rights reserved.
  14. *
  15. * Redistribution and use in source and binary forms, with or
  16. * without modification, are permitted provided that the following
  17. * conditions are met:
  18. *
  19. * - Redistributions of source code must retain the above copyright
  20. * notice, this list of conditions and the following disclaimer.
  21. *
  22. * - Redistributions in binary form must reproduce the above
  23. * copyright notice, this list of conditions and the following
  24. * disclaimer in the documentation and/or other materials provided
  25. * with the distribution.
  26. *
  27. * - Neither the name of the Eclipse Foundation, Inc. nor the
  28. * names of its contributors may be used to endorse or promote
  29. * products derived from this software without specific prior
  30. * written permission.
  31. *
  32. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  33. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  34. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  35. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  36. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  37. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  38. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  39. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  40. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  41. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  42. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  43. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  44. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  45. */
  46. package org.eclipse.jgit.lib;
  47. import java.io.BufferedOutputStream;
  48. import java.io.File;
  49. import java.io.FileNotFoundException;
  50. import java.io.FileOutputStream;
  51. import java.io.IOException;
  52. import java.util.Collection;
  53. import java.util.Collections;
  54. import java.util.HashMap;
  55. import java.util.HashSet;
  56. import java.util.LinkedList;
  57. import java.util.List;
  58. import java.util.Map;
  59. import java.util.Set;
  60. import java.util.concurrent.atomic.AtomicInteger;
  61. import org.eclipse.jgit.JGitText;
  62. import org.eclipse.jgit.dircache.DirCache;
  63. import org.eclipse.jgit.errors.AmbiguousObjectException;
  64. import org.eclipse.jgit.errors.CorruptObjectException;
  65. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  66. import org.eclipse.jgit.errors.MissingObjectException;
  67. import org.eclipse.jgit.errors.NoWorkTreeException;
  68. import org.eclipse.jgit.errors.RevisionSyntaxException;
  69. import org.eclipse.jgit.events.ListenerList;
  70. import org.eclipse.jgit.events.RepositoryEvent;
  71. import org.eclipse.jgit.revwalk.RevBlob;
  72. import org.eclipse.jgit.revwalk.RevCommit;
  73. import org.eclipse.jgit.revwalk.RevObject;
  74. import org.eclipse.jgit.revwalk.RevTree;
  75. import org.eclipse.jgit.revwalk.RevWalk;
  76. import org.eclipse.jgit.storage.file.ReflogReader;
  77. import org.eclipse.jgit.treewalk.TreeWalk;
  78. import org.eclipse.jgit.util.FS;
  79. import org.eclipse.jgit.util.FileUtils;
  80. import org.eclipse.jgit.util.IO;
  81. import org.eclipse.jgit.util.RawParseUtils;
  82. /**
  83. * Represents a Git repository.
  84. * <p>
  85. * A repository holds all objects and refs used for managing source code (could
  86. * be any type of file, but source code is what SCM's are typically used for).
  87. * <p>
  88. * This class is thread-safe.
  89. */
  90. public abstract class Repository {
  91. private static final ListenerList globalListeners = new ListenerList();
  92. /** @return the global listener list observing all events in this JVM. */
  93. public static ListenerList getGlobalListenerList() {
  94. return globalListeners;
  95. }
  96. private final AtomicInteger useCnt = new AtomicInteger(1);
  97. /** Metadata directory holding the repository's critical files. */
  98. private final File gitDir;
  99. /** File abstraction used to resolve paths. */
  100. private final FS fs;
  101. private GitIndex index;
  102. private final ListenerList myListeners = new ListenerList();
  103. /** If not bare, the top level directory of the working files. */
  104. private final File workTree;
  105. /** If not bare, the index file caching the working file states. */
  106. private final File indexFile;
  107. /**
  108. * Initialize a new repository instance.
  109. *
  110. * @param options
  111. * options to configure the repository.
  112. */
  113. protected Repository(final BaseRepositoryBuilder options) {
  114. gitDir = options.getGitDir();
  115. fs = options.getFS();
  116. workTree = options.getWorkTree();
  117. indexFile = options.getIndexFile();
  118. }
  119. /** @return listeners observing only events on this repository. */
  120. public ListenerList getListenerList() {
  121. return myListeners;
  122. }
  123. /**
  124. * Fire an event to all registered listeners.
  125. * <p>
  126. * The source repository of the event is automatically set to this
  127. * repository, before the event is delivered to any listeners.
  128. *
  129. * @param event
  130. * the event to deliver.
  131. */
  132. public void fireEvent(RepositoryEvent<?> event) {
  133. event.setRepository(this);
  134. myListeners.dispatch(event);
  135. globalListeners.dispatch(event);
  136. }
  137. /**
  138. * Create a new Git repository.
  139. * <p>
  140. * Repository with working tree is created using this method. This method is
  141. * the same as {@code create(false)}.
  142. *
  143. * @throws IOException
  144. * @see #create(boolean)
  145. */
  146. public void create() throws IOException {
  147. create(false);
  148. }
  149. /**
  150. * Create a new Git repository initializing the necessary files and
  151. * directories.
  152. *
  153. * @param bare
  154. * if true, a bare repository (a repository without a working
  155. * directory) is created.
  156. * @throws IOException
  157. * in case of IO problem
  158. */
  159. public abstract void create(boolean bare) throws IOException;
  160. /** @return local metadata directory; null if repository isn't local. */
  161. public File getDirectory() {
  162. return gitDir;
  163. }
  164. /**
  165. * @return the object database which stores this repository's data.
  166. */
  167. public abstract ObjectDatabase getObjectDatabase();
  168. /** @return a new inserter to create objects in {@link #getObjectDatabase()} */
  169. public ObjectInserter newObjectInserter() {
  170. return getObjectDatabase().newInserter();
  171. }
  172. /** @return a new reader to read objects from {@link #getObjectDatabase()} */
  173. public ObjectReader newObjectReader() {
  174. return getObjectDatabase().newReader();
  175. }
  176. /** @return the reference database which stores the reference namespace. */
  177. public abstract RefDatabase getRefDatabase();
  178. /**
  179. * @return the configuration of this repository
  180. */
  181. public abstract StoredConfig getConfig();
  182. /**
  183. * @return the used file system abstraction
  184. */
  185. public FS getFS() {
  186. return fs;
  187. }
  188. /**
  189. * @param objectId
  190. * @return true if the specified object is stored in this repo or any of the
  191. * known shared repositories.
  192. */
  193. public boolean hasObject(AnyObjectId objectId) {
  194. try {
  195. return getObjectDatabase().has(objectId);
  196. } catch (IOException e) {
  197. // Legacy API, assume error means "no"
  198. return false;
  199. }
  200. }
  201. /**
  202. * Open an object from this repository.
  203. * <p>
  204. * This is a one-shot call interface which may be faster than allocating a
  205. * {@link #newObjectReader()} to perform the lookup.
  206. *
  207. * @param objectId
  208. * identity of the object to open.
  209. * @return a {@link ObjectLoader} for accessing the object.
  210. * @throws MissingObjectException
  211. * the object does not exist.
  212. * @throws IOException
  213. * the object store cannot be accessed.
  214. */
  215. public ObjectLoader open(final AnyObjectId objectId)
  216. throws MissingObjectException, IOException {
  217. return getObjectDatabase().open(objectId);
  218. }
  219. /**
  220. * Open an object from this repository.
  221. * <p>
  222. * This is a one-shot call interface which may be faster than allocating a
  223. * {@link #newObjectReader()} to perform the lookup.
  224. *
  225. * @param objectId
  226. * identity of the object to open.
  227. * @param typeHint
  228. * hint about the type of object being requested;
  229. * {@link ObjectReader#OBJ_ANY} if the object type is not known,
  230. * or does not matter to the caller.
  231. * @return a {@link ObjectLoader} for accessing the object.
  232. * @throws MissingObjectException
  233. * the object does not exist.
  234. * @throws IncorrectObjectTypeException
  235. * typeHint was not OBJ_ANY, and the object's actual type does
  236. * not match typeHint.
  237. * @throws IOException
  238. * the object store cannot be accessed.
  239. */
  240. public ObjectLoader open(AnyObjectId objectId, int typeHint)
  241. throws MissingObjectException, IncorrectObjectTypeException,
  242. IOException {
  243. return getObjectDatabase().open(objectId, typeHint);
  244. }
  245. /**
  246. * Create a command to update, create or delete a ref in this repository.
  247. *
  248. * @param ref
  249. * name of the ref the caller wants to modify.
  250. * @return an update command. The caller must finish populating this command
  251. * and then invoke one of the update methods to actually make a
  252. * change.
  253. * @throws IOException
  254. * a symbolic ref was passed in and could not be resolved back
  255. * to the base ref, as the symbolic ref could not be read.
  256. */
  257. public RefUpdate updateRef(final String ref) throws IOException {
  258. return updateRef(ref, false);
  259. }
  260. /**
  261. * Create a command to update, create or delete a ref in this repository.
  262. *
  263. * @param ref
  264. * name of the ref the caller wants to modify.
  265. * @param detach
  266. * true to create a detached head
  267. * @return an update command. The caller must finish populating this command
  268. * and then invoke one of the update methods to actually make a
  269. * change.
  270. * @throws IOException
  271. * a symbolic ref was passed in and could not be resolved back
  272. * to the base ref, as the symbolic ref could not be read.
  273. */
  274. public RefUpdate updateRef(final String ref, final boolean detach) throws IOException {
  275. return getRefDatabase().newUpdate(ref, detach);
  276. }
  277. /**
  278. * Create a command to rename a ref in this repository
  279. *
  280. * @param fromRef
  281. * name of ref to rename from
  282. * @param toRef
  283. * name of ref to rename to
  284. * @return an update command that knows how to rename a branch to another.
  285. * @throws IOException
  286. * the rename could not be performed.
  287. *
  288. */
  289. public RefRename renameRef(final String fromRef, final String toRef) throws IOException {
  290. return getRefDatabase().newRename(fromRef, toRef);
  291. }
  292. /**
  293. * Parse a git revision string and return an object id.
  294. *
  295. * Combinations of these operators are supported:
  296. * <ul>
  297. * <li><b>HEAD</b>, <b>MERGE_HEAD</b>, <b>FETCH_HEAD</b></li>
  298. * <li><b>SHA-1</b>: a complete or abbreviated SHA-1</li>
  299. * <li><b>refs/...</b>: a complete reference name</li>
  300. * <li><b>short-name</b>: a short reference name under {@code refs/heads},
  301. * {@code refs/tags}, or {@code refs/remotes} namespace</li>
  302. * <li><b>tag-NN-gABBREV</b>: output from describe, parsed by treating
  303. * {@code ABBREV} as an abbreviated SHA-1.</li>
  304. * <li><i>id</i><b>^</b>: first parent of commit <i>id</i>, this is the same
  305. * as {@code id^1}</li>
  306. * <li><i>id</i><b>^0</b>: ensure <i>id</i> is a commit</li>
  307. * <li><i>id</i><b>^n</b>: n-th parent of commit <i>id</i></li>
  308. * <li><i>id</i><b>~n</b>: n-th historical ancestor of <i>id</i>, by first
  309. * parent. {@code id~3} is equivalent to {@code id^1^1^1} or {@code id^^^}.</li>
  310. * <li><i>id</i><b>:path</b>: Lookup path under tree named by <i>id</i></li>
  311. * <li><i>id</i><b>^{commit}</b>: ensure <i>id</i> is a commit</li>
  312. * <li><i>id</i><b>^{tree}</b>: ensure <i>id</i> is a tree</li>
  313. * <li><i>id</i><b>^{tag}</b>: ensure <i>id</i> is a tag</li>
  314. * <li><i>id</i><b>^{blob}</b>: ensure <i>id</i> is a blob</li>
  315. * </ul>
  316. *
  317. * <p>
  318. * The following operators are specified by Git conventions, but are not
  319. * supported by this method:
  320. * <ul>
  321. * <li><b>ref@{n}</b>: n-th version of ref as given by its reflog</li>
  322. * <li><b>ref@{time}</b>: value of ref at the designated time</li>
  323. * </ul>
  324. *
  325. * @param revstr
  326. * A git object references expression
  327. * @return an ObjectId or null if revstr can't be resolved to any ObjectId
  328. * @throws AmbiguousObjectException
  329. * {@code revstr} contains an abbreviated ObjectId and this
  330. * repository contains more than one object which match to the
  331. * input abbreviation.
  332. * @throws IncorrectObjectTypeException
  333. * the id parsed does not meet the type required to finish
  334. * applying the operators in the expression.
  335. * @throws RevisionSyntaxException
  336. * the expression is not supported by this implementation, or
  337. * does not meet the standard syntax.
  338. * @throws IOException
  339. * on serious errors
  340. */
  341. public ObjectId resolve(final String revstr)
  342. throws AmbiguousObjectException, IOException {
  343. RevWalk rw = new RevWalk(this);
  344. try {
  345. return resolve(rw, revstr);
  346. } finally {
  347. rw.release();
  348. }
  349. }
  350. private ObjectId resolve(final RevWalk rw, final String revstr) throws IOException {
  351. char[] rev = revstr.toCharArray();
  352. RevObject ref = null;
  353. for (int i = 0; i < rev.length; ++i) {
  354. switch (rev[i]) {
  355. case '^':
  356. if (ref == null) {
  357. ref = parseSimple(rw, new String(rev, 0, i));
  358. if (ref == null)
  359. return null;
  360. }
  361. if (i + 1 < rev.length) {
  362. switch (rev[i + 1]) {
  363. case '0':
  364. case '1':
  365. case '2':
  366. case '3':
  367. case '4':
  368. case '5':
  369. case '6':
  370. case '7':
  371. case '8':
  372. case '9':
  373. int j;
  374. ref = rw.parseCommit(ref);
  375. for (j = i + 1; j < rev.length; ++j) {
  376. if (!Character.isDigit(rev[j]))
  377. break;
  378. }
  379. String parentnum = new String(rev, i + 1, j - i - 1);
  380. int pnum;
  381. try {
  382. pnum = Integer.parseInt(parentnum);
  383. } catch (NumberFormatException e) {
  384. throw new RevisionSyntaxException(
  385. JGitText.get().invalidCommitParentNumber,
  386. revstr);
  387. }
  388. if (pnum != 0) {
  389. RevCommit commit = (RevCommit) ref;
  390. if (pnum > commit.getParentCount())
  391. ref = null;
  392. else
  393. ref = commit.getParent(pnum - 1);
  394. }
  395. i = j - 1;
  396. break;
  397. case '{':
  398. int k;
  399. String item = null;
  400. for (k = i + 2; k < rev.length; ++k) {
  401. if (rev[k] == '}') {
  402. item = new String(rev, i + 2, k - i - 2);
  403. break;
  404. }
  405. }
  406. i = k;
  407. if (item != null)
  408. if (item.equals("tree")) {
  409. ref = rw.parseTree(ref);
  410. } else if (item.equals("commit")) {
  411. ref = rw.parseCommit(ref);
  412. } else if (item.equals("blob")) {
  413. ref = rw.peel(ref);
  414. if (!(ref instanceof RevBlob))
  415. throw new IncorrectObjectTypeException(ref,
  416. Constants.TYPE_BLOB);
  417. } else if (item.equals("")) {
  418. ref = rw.peel(ref);
  419. } else
  420. throw new RevisionSyntaxException(revstr);
  421. else
  422. throw new RevisionSyntaxException(revstr);
  423. break;
  424. default:
  425. ref = rw.parseAny(ref);
  426. if (ref instanceof RevCommit) {
  427. RevCommit commit = ((RevCommit) ref);
  428. if (commit.getParentCount() == 0)
  429. ref = null;
  430. else
  431. ref = commit.getParent(0);
  432. } else
  433. throw new IncorrectObjectTypeException(ref,
  434. Constants.TYPE_COMMIT);
  435. }
  436. } else {
  437. ref = rw.peel(ref);
  438. if (ref instanceof RevCommit) {
  439. RevCommit commit = ((RevCommit) ref);
  440. if (commit.getParentCount() == 0)
  441. ref = null;
  442. else
  443. ref = commit.getParent(0);
  444. } else
  445. throw new IncorrectObjectTypeException(ref,
  446. Constants.TYPE_COMMIT);
  447. }
  448. break;
  449. case '~':
  450. if (ref == null) {
  451. ref = parseSimple(rw, new String(rev, 0, i));
  452. if (ref == null)
  453. return null;
  454. }
  455. ref = rw.peel(ref);
  456. if (!(ref instanceof RevCommit))
  457. throw new IncorrectObjectTypeException(ref,
  458. Constants.TYPE_COMMIT);
  459. int l;
  460. for (l = i + 1; l < rev.length; ++l) {
  461. if (!Character.isDigit(rev[l]))
  462. break;
  463. }
  464. String distnum = new String(rev, i + 1, l - i - 1);
  465. int dist;
  466. try {
  467. dist = Integer.parseInt(distnum);
  468. } catch (NumberFormatException e) {
  469. throw new RevisionSyntaxException(
  470. JGitText.get().invalidAncestryLength, revstr);
  471. }
  472. while (dist > 0) {
  473. RevCommit commit = (RevCommit) ref;
  474. if (commit.getParentCount() == 0) {
  475. ref = null;
  476. break;
  477. }
  478. commit = commit.getParent(0);
  479. rw.parseHeaders(commit);
  480. ref = commit;
  481. --dist;
  482. }
  483. i = l - 1;
  484. break;
  485. case '@':
  486. int m;
  487. String time = null;
  488. for (m = i + 2; m < rev.length; ++m) {
  489. if (rev[m] == '}') {
  490. time = new String(rev, i + 2, m - i - 2);
  491. break;
  492. }
  493. }
  494. if (time != null)
  495. throw new RevisionSyntaxException(
  496. JGitText.get().reflogsNotYetSupportedByRevisionParser,
  497. revstr);
  498. i = m - 1;
  499. break;
  500. case ':': {
  501. RevTree tree;
  502. if (ref == null) {
  503. // We might not yet have parsed the left hand side.
  504. ObjectId id;
  505. try {
  506. if (i == 0)
  507. id = resolve(rw, Constants.HEAD);
  508. else
  509. id = resolve(rw, new String(rev, 0, i));
  510. } catch (RevisionSyntaxException badSyntax) {
  511. throw new RevisionSyntaxException(revstr);
  512. }
  513. if (id == null)
  514. return null;
  515. tree = rw.parseTree(id);
  516. } else {
  517. tree = rw.parseTree(ref);
  518. }
  519. if (i == rev.length - i)
  520. return tree.copy();
  521. TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(),
  522. new String(rev, i + 1, rev.length - i - 1), tree);
  523. return tw != null ? tw.getObjectId(0) : null;
  524. }
  525. default:
  526. if (ref != null)
  527. throw new RevisionSyntaxException(revstr);
  528. }
  529. }
  530. return ref != null ? ref.copy() : resolveSimple(revstr);
  531. }
  532. private static boolean isHex(char c) {
  533. return ('0' <= c && c <= '9') //
  534. || ('a' <= c && c <= 'f') //
  535. || ('A' <= c && c <= 'F');
  536. }
  537. private static boolean isAllHex(String str, int ptr) {
  538. while (ptr < str.length()) {
  539. if (!isHex(str.charAt(ptr++)))
  540. return false;
  541. }
  542. return true;
  543. }
  544. private RevObject parseSimple(RevWalk rw, String revstr) throws IOException {
  545. ObjectId id = resolveSimple(revstr);
  546. return id != null ? rw.parseAny(id) : null;
  547. }
  548. private ObjectId resolveSimple(final String revstr) throws IOException {
  549. if (ObjectId.isId(revstr))
  550. return ObjectId.fromString(revstr);
  551. Ref r = getRefDatabase().getRef(revstr);
  552. if (r != null)
  553. return r.getObjectId();
  554. if (AbbreviatedObjectId.isId(revstr))
  555. return resolveAbbreviation(revstr);
  556. int dashg = revstr.indexOf("-g");
  557. if (4 < revstr.length() && 0 <= dashg
  558. && isHex(revstr.charAt(dashg + 2))
  559. && isHex(revstr.charAt(dashg + 3))
  560. && isAllHex(revstr, dashg + 4)) {
  561. // Possibly output from git describe?
  562. String s = revstr.substring(dashg + 2);
  563. if (AbbreviatedObjectId.isId(s))
  564. return resolveAbbreviation(s);
  565. }
  566. return null;
  567. }
  568. private ObjectId resolveAbbreviation(final String revstr) throws IOException,
  569. AmbiguousObjectException {
  570. AbbreviatedObjectId id = AbbreviatedObjectId.fromString(revstr);
  571. ObjectReader reader = newObjectReader();
  572. try {
  573. Collection<ObjectId> matches = reader.resolve(id);
  574. if (matches.size() == 0)
  575. return null;
  576. else if (matches.size() == 1)
  577. return matches.iterator().next();
  578. else
  579. throw new AmbiguousObjectException(id, matches);
  580. } finally {
  581. reader.release();
  582. }
  583. }
  584. /** Increment the use counter by one, requiring a matched {@link #close()}. */
  585. public void incrementOpen() {
  586. useCnt.incrementAndGet();
  587. }
  588. /** Decrement the use count, and maybe close resources. */
  589. public void close() {
  590. if (useCnt.decrementAndGet() == 0) {
  591. doClose();
  592. }
  593. }
  594. /**
  595. * Invoked when the use count drops to zero during {@link #close()}.
  596. * <p>
  597. * The default implementation closes the object and ref databases.
  598. */
  599. protected void doClose() {
  600. getObjectDatabase().close();
  601. getRefDatabase().close();
  602. }
  603. public String toString() {
  604. String desc;
  605. if (getDirectory() != null)
  606. desc = getDirectory().getPath();
  607. else
  608. desc = getClass().getSimpleName() + "-"
  609. + System.identityHashCode(this);
  610. return "Repository[" + desc + "]";
  611. }
  612. /**
  613. * Get the name of the reference that {@code HEAD} points to.
  614. * <p>
  615. * This is essentially the same as doing:
  616. *
  617. * <pre>
  618. * return getRef(Constants.HEAD).getTarget().getName()
  619. * </pre>
  620. *
  621. * Except when HEAD is detached, in which case this method returns the
  622. * current ObjectId in hexadecimal string format.
  623. *
  624. * @return name of current branch (for example {@code refs/heads/master}) or
  625. * an ObjectId in hex format if the current branch is detached.
  626. * @throws IOException
  627. */
  628. public String getFullBranch() throws IOException {
  629. Ref head = getRef(Constants.HEAD);
  630. if (head == null)
  631. return null;
  632. if (head.isSymbolic())
  633. return head.getTarget().getName();
  634. if (head.getObjectId() != null)
  635. return head.getObjectId().name();
  636. return null;
  637. }
  638. /**
  639. * Get the short name of the current branch that {@code HEAD} points to.
  640. * <p>
  641. * This is essentially the same as {@link #getFullBranch()}, except the
  642. * leading prefix {@code refs/heads/} is removed from the reference before
  643. * it is returned to the caller.
  644. *
  645. * @return name of current branch (for example {@code master}), or an
  646. * ObjectId in hex format if the current branch is detached.
  647. * @throws IOException
  648. */
  649. public String getBranch() throws IOException {
  650. String name = getFullBranch();
  651. if (name != null)
  652. return shortenRefName(name);
  653. return name;
  654. }
  655. /**
  656. * Objects known to exist but not expressed by {@link #getAllRefs()}.
  657. * <p>
  658. * When a repository borrows objects from another repository, it can
  659. * advertise that it safely has that other repository's references, without
  660. * exposing any other details about the other repository. This may help
  661. * a client trying to push changes avoid pushing more than it needs to.
  662. *
  663. * @return unmodifiable collection of other known objects.
  664. */
  665. public Set<ObjectId> getAdditionalHaves() {
  666. return Collections.emptySet();
  667. }
  668. /**
  669. * Get a ref by name.
  670. *
  671. * @param name
  672. * the name of the ref to lookup. May be a short-hand form, e.g.
  673. * "master" which is is automatically expanded to
  674. * "refs/heads/master" if "refs/heads/master" already exists.
  675. * @return the Ref with the given name, or null if it does not exist
  676. * @throws IOException
  677. */
  678. public Ref getRef(final String name) throws IOException {
  679. return getRefDatabase().getRef(name);
  680. }
  681. /**
  682. * @return mutable map of all known refs (heads, tags, remotes).
  683. */
  684. public Map<String, Ref> getAllRefs() {
  685. try {
  686. return getRefDatabase().getRefs(RefDatabase.ALL);
  687. } catch (IOException e) {
  688. return new HashMap<String, Ref>();
  689. }
  690. }
  691. /**
  692. * @return mutable map of all tags; key is short tag name ("v1.0") and value
  693. * of the entry contains the ref with the full tag name
  694. * ("refs/tags/v1.0").
  695. */
  696. public Map<String, Ref> getTags() {
  697. try {
  698. return getRefDatabase().getRefs(Constants.R_TAGS);
  699. } catch (IOException e) {
  700. return new HashMap<String, Ref>();
  701. }
  702. }
  703. /**
  704. * Peel a possibly unpeeled reference to an annotated tag.
  705. * <p>
  706. * If the ref cannot be peeled (as it does not refer to an annotated tag)
  707. * the peeled id stays null, but {@link Ref#isPeeled()} will be true.
  708. *
  709. * @param ref
  710. * The ref to peel
  711. * @return <code>ref</code> if <code>ref.isPeeled()</code> is true; else a
  712. * new Ref object representing the same data as Ref, but isPeeled()
  713. * will be true and getPeeledObjectId will contain the peeled object
  714. * (or null).
  715. */
  716. public Ref peel(final Ref ref) {
  717. try {
  718. return getRefDatabase().peel(ref);
  719. } catch (IOException e) {
  720. // Historical accident; if the reference cannot be peeled due
  721. // to some sort of repository access problem we claim that the
  722. // same as if the reference was not an annotated tag.
  723. return ref;
  724. }
  725. }
  726. /**
  727. * @return a map with all objects referenced by a peeled ref.
  728. */
  729. public Map<AnyObjectId, Set<Ref>> getAllRefsByPeeledObjectId() {
  730. Map<String, Ref> allRefs = getAllRefs();
  731. Map<AnyObjectId, Set<Ref>> ret = new HashMap<AnyObjectId, Set<Ref>>(allRefs.size());
  732. for (Ref ref : allRefs.values()) {
  733. ref = peel(ref);
  734. AnyObjectId target = ref.getPeeledObjectId();
  735. if (target == null)
  736. target = ref.getObjectId();
  737. // We assume most Sets here are singletons
  738. Set<Ref> oset = ret.put(target, Collections.singleton(ref));
  739. if (oset != null) {
  740. // that was not the case (rare)
  741. if (oset.size() == 1) {
  742. // Was a read-only singleton, we must copy to a new Set
  743. oset = new HashSet<Ref>(oset);
  744. }
  745. ret.put(target, oset);
  746. oset.add(ref);
  747. }
  748. }
  749. return ret;
  750. }
  751. /**
  752. * @return a representation of the index associated with this
  753. * {@link Repository}
  754. * @throws IOException
  755. * if the index can not be read
  756. * @throws NoWorkTreeException
  757. * if this is bare, which implies it has no working directory.
  758. * See {@link #isBare()}.
  759. */
  760. public GitIndex getIndex() throws IOException, NoWorkTreeException {
  761. if (isBare())
  762. throw new NoWorkTreeException();
  763. if (index == null) {
  764. index = new GitIndex(this);
  765. index.read();
  766. } else {
  767. index.rereadIfNecessary();
  768. }
  769. return index;
  770. }
  771. /**
  772. * @return the index file location
  773. * @throws NoWorkTreeException
  774. * if this is bare, which implies it has no working directory.
  775. * See {@link #isBare()}.
  776. */
  777. public File getIndexFile() throws NoWorkTreeException {
  778. if (isBare())
  779. throw new NoWorkTreeException();
  780. return indexFile;
  781. }
  782. /**
  783. * Create a new in-core index representation and read an index from disk.
  784. * <p>
  785. * The new index will be read before it is returned to the caller. Read
  786. * failures are reported as exceptions and therefore prevent the method from
  787. * returning a partially populated index.
  788. *
  789. * @return a cache representing the contents of the specified index file (if
  790. * it exists) or an empty cache if the file does not exist.
  791. * @throws NoWorkTreeException
  792. * if this is bare, which implies it has no working directory.
  793. * See {@link #isBare()}.
  794. * @throws IOException
  795. * the index file is present but could not be read.
  796. * @throws CorruptObjectException
  797. * the index file is using a format or extension that this
  798. * library does not support.
  799. */
  800. public DirCache readDirCache() throws NoWorkTreeException,
  801. CorruptObjectException, IOException {
  802. return DirCache.read(getIndexFile(), getFS());
  803. }
  804. /**
  805. * Create a new in-core index representation, lock it, and read from disk.
  806. * <p>
  807. * The new index will be locked and then read before it is returned to the
  808. * caller. Read failures are reported as exceptions and therefore prevent
  809. * the method from returning a partially populated index.
  810. *
  811. * @return a cache representing the contents of the specified index file (if
  812. * it exists) or an empty cache if the file does not exist.
  813. * @throws NoWorkTreeException
  814. * if this is bare, which implies it has no working directory.
  815. * See {@link #isBare()}.
  816. * @throws IOException
  817. * the index file is present but could not be read, or the lock
  818. * could not be obtained.
  819. * @throws CorruptObjectException
  820. * the index file is using a format or extension that this
  821. * library does not support.
  822. */
  823. public DirCache lockDirCache() throws NoWorkTreeException,
  824. CorruptObjectException, IOException {
  825. return DirCache.lock(getIndexFile(), getFS());
  826. }
  827. static byte[] gitInternalSlash(byte[] bytes) {
  828. if (File.separatorChar == '/')
  829. return bytes;
  830. for (int i=0; i<bytes.length; ++i)
  831. if (bytes[i] == File.separatorChar)
  832. bytes[i] = '/';
  833. return bytes;
  834. }
  835. /**
  836. * @return an important state
  837. */
  838. public RepositoryState getRepositoryState() {
  839. if (isBare() || getDirectory() == null)
  840. return RepositoryState.BARE;
  841. // Pre Git-1.6 logic
  842. if (new File(getWorkTree(), ".dotest").exists())
  843. return RepositoryState.REBASING;
  844. if (new File(getDirectory(), ".dotest-merge").exists())
  845. return RepositoryState.REBASING_INTERACTIVE;
  846. // From 1.6 onwards
  847. if (new File(getDirectory(),"rebase-apply/rebasing").exists())
  848. return RepositoryState.REBASING_REBASING;
  849. if (new File(getDirectory(),"rebase-apply/applying").exists())
  850. return RepositoryState.APPLY;
  851. if (new File(getDirectory(),"rebase-apply").exists())
  852. return RepositoryState.REBASING;
  853. if (new File(getDirectory(),"rebase-merge/interactive").exists())
  854. return RepositoryState.REBASING_INTERACTIVE;
  855. if (new File(getDirectory(),"rebase-merge").exists())
  856. return RepositoryState.REBASING_MERGE;
  857. // Both versions
  858. if (new File(getDirectory(), "MERGE_HEAD").exists()) {
  859. // we are merging - now check whether we have unmerged paths
  860. try {
  861. if (!readDirCache().hasUnmergedPaths()) {
  862. // no unmerged paths -> return the MERGING_RESOLVED state
  863. return RepositoryState.MERGING_RESOLVED;
  864. }
  865. } catch (IOException e) {
  866. // Can't decide whether unmerged paths exists. Return
  867. // MERGING state to be on the safe side (in state MERGING
  868. // you are not allow to do anything)
  869. e.printStackTrace();
  870. }
  871. return RepositoryState.MERGING;
  872. }
  873. if (new File(getDirectory(), "BISECT_LOG").exists())
  874. return RepositoryState.BISECTING;
  875. return RepositoryState.SAFE;
  876. }
  877. /**
  878. * Check validity of a ref name. It must not contain character that has
  879. * a special meaning in a Git object reference expression. Some other
  880. * dangerous characters are also excluded.
  881. *
  882. * For portability reasons '\' is excluded
  883. *
  884. * @param refName
  885. *
  886. * @return true if refName is a valid ref name
  887. */
  888. public static boolean isValidRefName(final String refName) {
  889. final int len = refName.length();
  890. if (len == 0)
  891. return false;
  892. if (refName.endsWith(".lock"))
  893. return false;
  894. int components = 1;
  895. char p = '\0';
  896. for (int i = 0; i < len; i++) {
  897. final char c = refName.charAt(i);
  898. if (c <= ' ')
  899. return false;
  900. switch (c) {
  901. case '.':
  902. switch (p) {
  903. case '\0': case '/': case '.':
  904. return false;
  905. }
  906. if (i == len -1)
  907. return false;
  908. break;
  909. case '/':
  910. if (i == 0 || i == len - 1)
  911. return false;
  912. components++;
  913. break;
  914. case '{':
  915. if (p == '@')
  916. return false;
  917. break;
  918. case '~': case '^': case ':':
  919. case '?': case '[': case '*':
  920. case '\\':
  921. return false;
  922. }
  923. p = c;
  924. }
  925. return components > 1;
  926. }
  927. /**
  928. * Strip work dir and return normalized repository path.
  929. *
  930. * @param workDir Work dir
  931. * @param file File whose path shall be stripped of its workdir
  932. * @return normalized repository relative path or the empty
  933. * string if the file is not relative to the work directory.
  934. */
  935. public static String stripWorkDir(File workDir, File file) {
  936. final String filePath = file.getPath();
  937. final String workDirPath = workDir.getPath();
  938. if (filePath.length() <= workDirPath.length() ||
  939. filePath.charAt(workDirPath.length()) != File.separatorChar ||
  940. !filePath.startsWith(workDirPath)) {
  941. File absWd = workDir.isAbsolute() ? workDir : workDir.getAbsoluteFile();
  942. File absFile = file.isAbsolute() ? file : file.getAbsoluteFile();
  943. if (absWd == workDir && absFile == file)
  944. return "";
  945. return stripWorkDir(absWd, absFile);
  946. }
  947. String relName = filePath.substring(workDirPath.length() + 1);
  948. if (File.separatorChar != '/')
  949. relName = relName.replace(File.separatorChar, '/');
  950. return relName;
  951. }
  952. /**
  953. * @return true if this is bare, which implies it has no working directory.
  954. */
  955. public boolean isBare() {
  956. return workTree == null;
  957. }
  958. /**
  959. * @return the root directory of the working tree, where files are checked
  960. * out for viewing and editing.
  961. * @throws NoWorkTreeException
  962. * if this is bare, which implies it has no working directory.
  963. * See {@link #isBare()}.
  964. */
  965. public File getWorkTree() throws NoWorkTreeException {
  966. if (isBare())
  967. throw new NoWorkTreeException();
  968. return workTree;
  969. }
  970. /**
  971. * Force a scan for changed refs.
  972. *
  973. * @throws IOException
  974. */
  975. public abstract void scanForRepoChanges() throws IOException;
  976. /**
  977. * @param refName
  978. *
  979. * @return a more user friendly ref name
  980. */
  981. public static String shortenRefName(String refName) {
  982. if (refName.startsWith(Constants.R_HEADS))
  983. return refName.substring(Constants.R_HEADS.length());
  984. if (refName.startsWith(Constants.R_TAGS))
  985. return refName.substring(Constants.R_TAGS.length());
  986. if (refName.startsWith(Constants.R_REMOTES))
  987. return refName.substring(Constants.R_REMOTES.length());
  988. return refName;
  989. }
  990. /**
  991. * @param refName
  992. * @return a {@link ReflogReader} for the supplied refname, or null if the
  993. * named ref does not exist.
  994. * @throws IOException the ref could not be accessed.
  995. */
  996. public abstract ReflogReader getReflogReader(String refName)
  997. throws IOException;
  998. /**
  999. * Return the information stored in the file $GIT_DIR/MERGE_MSG. In this
  1000. * file operations triggering a merge will store a template for the commit
  1001. * message of the merge commit.
  1002. *
  1003. * @return a String containing the content of the MERGE_MSG file or
  1004. * {@code null} if this file doesn't exist
  1005. * @throws IOException
  1006. * @throws NoWorkTreeException
  1007. * if this is bare, which implies it has no working directory.
  1008. * See {@link #isBare()}.
  1009. */
  1010. public String readMergeCommitMsg() throws IOException, NoWorkTreeException {
  1011. if (isBare() || getDirectory() == null)
  1012. throw new NoWorkTreeException();
  1013. File mergeMsgFile = new File(getDirectory(), Constants.MERGE_MSG);
  1014. try {
  1015. return RawParseUtils.decode(IO.readFully(mergeMsgFile));
  1016. } catch (FileNotFoundException e) {
  1017. // MERGE_MSG file has disappeared in the meantime
  1018. // ignore it
  1019. return null;
  1020. }
  1021. }
  1022. /**
  1023. * Write new content to the file $GIT_DIR/MERGE_MSG. In this file operations
  1024. * triggering a merge will store a template for the commit message of the
  1025. * merge commit. If <code>null</code> is specified as message the file will
  1026. * be deleted
  1027. *
  1028. * @param msg
  1029. * the message which should be written or <code>null</code> to
  1030. * delete the file
  1031. *
  1032. * @throws IOException
  1033. */
  1034. public void writeMergeCommitMsg(String msg) throws IOException {
  1035. File mergeMsgFile = new File(gitDir, Constants.MERGE_MSG);
  1036. if (msg != null) {
  1037. FileOutputStream fos = new FileOutputStream(mergeMsgFile);
  1038. try {
  1039. fos.write(msg.getBytes(Constants.CHARACTER_ENCODING));
  1040. } finally {
  1041. fos.close();
  1042. }
  1043. } else {
  1044. FileUtils.delete(mergeMsgFile);
  1045. }
  1046. }
  1047. /**
  1048. * Return the information stored in the file $GIT_DIR/MERGE_HEAD. In this
  1049. * file operations triggering a merge will store the IDs of all heads which
  1050. * should be merged together with HEAD.
  1051. *
  1052. * @return a list of commits which IDs are listed in the MERGE_HEAD
  1053. * file or {@code null} if this file doesn't exist. Also if the file
  1054. * exists but is empty {@code null} will be returned
  1055. * @throws IOException
  1056. * @throws NoWorkTreeException
  1057. * if this is bare, which implies it has no working directory.
  1058. * See {@link #isBare()}.
  1059. */
  1060. public List<ObjectId> readMergeHeads() throws IOException, NoWorkTreeException {
  1061. if (isBare() || getDirectory() == null)
  1062. throw new NoWorkTreeException();
  1063. File mergeHeadFile = new File(getDirectory(), Constants.MERGE_HEAD);
  1064. byte[] raw;
  1065. try {
  1066. raw = IO.readFully(mergeHeadFile);
  1067. } catch (FileNotFoundException notFound) {
  1068. return null;
  1069. }
  1070. if (raw.length == 0)
  1071. return null;
  1072. LinkedList<ObjectId> heads = new LinkedList<ObjectId>();
  1073. for (int p = 0; p < raw.length;) {
  1074. heads.add(ObjectId.fromString(raw, p));
  1075. p = RawParseUtils
  1076. .nextLF(raw, p + Constants.OBJECT_ID_STRING_LENGTH);
  1077. }
  1078. return heads;
  1079. }
  1080. /**
  1081. * Write new merge-heads into $GIT_DIR/MERGE_HEAD. In this file operations
  1082. * triggering a merge will store the IDs of all heads which should be merged
  1083. * together with HEAD. If <code>null</code> is specified as list of commits
  1084. * the file will be deleted
  1085. *
  1086. * @param heads
  1087. * a list of commits which IDs should be written to
  1088. * $GIT_DIR/MERGE_HEAD or <code>null</code> to delete the file
  1089. * @throws IOException
  1090. */
  1091. public void writeMergeHeads(List<ObjectId> heads) throws IOException {
  1092. File mergeHeadFile = new File(gitDir, Constants.MERGE_HEAD);
  1093. if (heads != null) {
  1094. BufferedOutputStream bos = new BufferedOutputStream(
  1095. new FileOutputStream(mergeHeadFile));
  1096. try {
  1097. for (ObjectId id : heads) {
  1098. id.copyTo(bos);
  1099. bos.write('\n');
  1100. }
  1101. } finally {
  1102. bos.close();
  1103. }
  1104. } else {
  1105. FileUtils.delete(mergeHeadFile);
  1106. }
  1107. }
  1108. }