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.

RefDatabase.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. /*
  2. * Copyright (C) 2007-2009, Robin Rosenberg <robin.rosenberg@dewire.com>
  3. * Copyright (C) 2006-2008, Shawn O. Pearce <spearce@spearce.org>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.lib;
  45. import static org.eclipse.jgit.lib.Constants.R_TAGS;
  46. import java.io.BufferedReader;
  47. import java.io.File;
  48. import java.io.FileInputStream;
  49. import java.io.FileNotFoundException;
  50. import java.io.IOException;
  51. import java.io.InputStreamReader;
  52. import java.util.HashMap;
  53. import java.util.Map;
  54. import org.eclipse.jgit.errors.ObjectWritingException;
  55. import org.eclipse.jgit.lib.Ref.Storage;
  56. import org.eclipse.jgit.util.FS;
  57. import org.eclipse.jgit.util.IO;
  58. import org.eclipse.jgit.util.RawParseUtils;
  59. class RefDatabase {
  60. private static final String REFS_SLASH = "refs/";
  61. private static final String[] refSearchPaths = { "", REFS_SLASH,
  62. R_TAGS, Constants.R_HEADS, Constants.R_REMOTES };
  63. private final Repository db;
  64. private final File gitDir;
  65. private final File refsDir;
  66. private Map<String, Ref> looseRefs;
  67. private Map<String, Long> looseRefsMTime;
  68. private Map<String, String> looseSymRefs;
  69. private final File packedRefsFile;
  70. private Map<String, Ref> packedRefs;
  71. private long packedRefsLastModified;
  72. private long packedRefsLength;
  73. int lastRefModification;
  74. int lastNotifiedRefModification;
  75. private int refModificationCounter;
  76. RefDatabase(final Repository r) {
  77. db = r;
  78. gitDir = db.getDirectory();
  79. refsDir = FS.resolve(gitDir, "refs");
  80. packedRefsFile = FS.resolve(gitDir, Constants.PACKED_REFS);
  81. clearCache();
  82. }
  83. synchronized void clearCache() {
  84. looseRefs = new HashMap<String, Ref>();
  85. looseRefsMTime = new HashMap<String, Long>();
  86. packedRefs = new HashMap<String, Ref>();
  87. looseSymRefs = new HashMap<String, String>();
  88. packedRefsLastModified = 0;
  89. packedRefsLength = 0;
  90. }
  91. Repository getRepository() {
  92. return db;
  93. }
  94. void create() {
  95. refsDir.mkdir();
  96. new File(refsDir, "heads").mkdir();
  97. new File(refsDir, "tags").mkdir();
  98. }
  99. ObjectId idOf(final String name) throws IOException {
  100. refreshPackedRefs();
  101. final Ref r = readRefBasic(name, 0);
  102. return r != null ? r.getObjectId() : null;
  103. }
  104. /**
  105. * Create a command to update, create or delete a ref in this repository.
  106. *
  107. * @param name
  108. * name of the ref the caller wants to modify.
  109. * @return an update command. The caller must finish populating this command
  110. * and then invoke one of the update methods to actually make a
  111. * change.
  112. * @throws IOException
  113. * a symbolic ref was passed in and could not be resolved back
  114. * to the base ref, as the symbolic ref could not be read.
  115. */
  116. RefUpdate newUpdate(final String name) throws IOException {
  117. refreshPackedRefs();
  118. Ref r = readRefBasic(name, 0);
  119. if (r == null)
  120. r = new Ref(Ref.Storage.NEW, name, null);
  121. return new RefUpdate(this, r, fileForRef(r.getName()));
  122. }
  123. void stored(final String origName, final String name, final ObjectId id, final long time) {
  124. synchronized (this) {
  125. looseRefs.put(name, new Ref(Ref.Storage.LOOSE, name, name, id));
  126. looseRefsMTime.put(name, time);
  127. setModified();
  128. }
  129. db.fireRefsMaybeChanged();
  130. }
  131. /**
  132. * An set of update operations for renaming a ref
  133. *
  134. * @param fromRef Old ref name
  135. * @param toRef New ref name
  136. * @return a RefUpdate operation to rename a ref
  137. * @throws IOException
  138. */
  139. RefRename newRename(String fromRef, String toRef) throws IOException {
  140. refreshPackedRefs();
  141. Ref f = readRefBasic(fromRef, 0);
  142. Ref t = new Ref(Ref.Storage.NEW, toRef, null);
  143. RefUpdate refUpdateFrom = new RefUpdate(this, f, fileForRef(f.getName()));
  144. RefUpdate refUpdateTo = new RefUpdate(this, t, fileForRef(t.getName()));
  145. return new RefRename(refUpdateTo, refUpdateFrom);
  146. }
  147. /**
  148. * Writes a symref (e.g. HEAD) to disk
  149. *
  150. * @param name
  151. * symref name
  152. * @param target
  153. * pointed to ref
  154. * @throws IOException
  155. */
  156. void link(final String name, final String target) throws IOException {
  157. final byte[] content = Constants.encode("ref: " + target + "\n");
  158. lockAndWriteFile(fileForRef(name), content);
  159. synchronized (this) {
  160. looseSymRefs.remove(name);
  161. setModified();
  162. }
  163. db.fireRefsMaybeChanged();
  164. }
  165. void uncacheSymRef(String name) {
  166. synchronized(this) {
  167. looseSymRefs.remove(name);
  168. setModified();
  169. }
  170. }
  171. void uncacheRef(String name) {
  172. looseRefs.remove(name);
  173. looseRefsMTime.remove(name);
  174. packedRefs.remove(name);
  175. }
  176. private void setModified() {
  177. lastRefModification = refModificationCounter++;
  178. }
  179. Ref readRef(final String partialName) throws IOException {
  180. refreshPackedRefs();
  181. for (int k = 0; k < refSearchPaths.length; k++) {
  182. final Ref r = readRefBasic(refSearchPaths[k] + partialName, 0);
  183. if (r != null && r.getObjectId() != null)
  184. return r;
  185. }
  186. return null;
  187. }
  188. /**
  189. * @return all known refs (heads, tags, remotes).
  190. */
  191. Map<String, Ref> getAllRefs() {
  192. return readRefs();
  193. }
  194. /**
  195. * @return all tags; key is short tag name ("v1.0") and value of the entry
  196. * contains the ref with the full tag name ("refs/tags/v1.0").
  197. */
  198. Map<String, Ref> getTags() {
  199. final Map<String, Ref> tags = new HashMap<String, Ref>();
  200. for (final Ref r : readRefs().values()) {
  201. if (r.getName().startsWith(R_TAGS))
  202. tags.put(r.getName().substring(R_TAGS.length()), r);
  203. }
  204. return tags;
  205. }
  206. private Map<String, Ref> readRefs() {
  207. final HashMap<String, Ref> avail = new HashMap<String, Ref>();
  208. readPackedRefs(avail);
  209. readLooseRefs(avail, REFS_SLASH, refsDir);
  210. try {
  211. final Ref r = readRefBasic(Constants.HEAD, 0);
  212. if (r != null && r.getObjectId() != null)
  213. avail.put(Constants.HEAD, r);
  214. } catch (IOException e) {
  215. // ignore here
  216. }
  217. db.fireRefsMaybeChanged();
  218. return avail;
  219. }
  220. private synchronized void readPackedRefs(final Map<String, Ref> avail) {
  221. refreshPackedRefs();
  222. avail.putAll(packedRefs);
  223. }
  224. private void readLooseRefs(final Map<String, Ref> avail,
  225. final String prefix, final File dir) {
  226. final File[] entries = dir.listFiles();
  227. if (entries == null)
  228. return;
  229. for (final File ent : entries) {
  230. final String entName = ent.getName();
  231. if (".".equals(entName) || "..".equals(entName))
  232. continue;
  233. if (ent.isDirectory()) {
  234. readLooseRefs(avail, prefix + entName + "/", ent);
  235. } else {
  236. try {
  237. final Ref ref = readRefBasic(prefix + entName, 0);
  238. if (ref != null)
  239. avail.put(ref.getOrigName(), ref);
  240. } catch (IOException e) {
  241. continue;
  242. }
  243. }
  244. }
  245. }
  246. Ref peel(final Ref ref) {
  247. if (ref.isPeeled())
  248. return ref;
  249. ObjectId peeled = null;
  250. try {
  251. Object target = db.mapObject(ref.getObjectId(), ref.getName());
  252. while (target instanceof Tag) {
  253. final Tag tag = (Tag)target;
  254. peeled = tag.getObjId();
  255. if (Constants.TYPE_TAG.equals(tag.getType()))
  256. target = db.mapObject(tag.getObjId(), ref.getName());
  257. else
  258. break;
  259. }
  260. } catch (IOException e) {
  261. // Ignore a read error.  Callers will also get the same error
  262. // if they try to use the result of getPeeledObjectId.
  263. }
  264. return new Ref(ref.getStorage(), ref.getName(), ref.getObjectId(), peeled, true);
  265. }
  266. private File fileForRef(final String name) {
  267. if (name.startsWith(REFS_SLASH))
  268. return new File(refsDir, name.substring(REFS_SLASH.length()));
  269. return new File(gitDir, name);
  270. }
  271. private Ref readRefBasic(final String name, final int depth) throws IOException {
  272. return readRefBasic(name, name, depth);
  273. }
  274. private synchronized Ref readRefBasic(final String origName,
  275. final String name, final int depth) throws IOException {
  276. // Prefer loose ref to packed ref as the loose
  277. // file can be more up-to-date than a packed one.
  278. //
  279. Ref ref = looseRefs.get(origName);
  280. final File loose = fileForRef(name);
  281. final long mtime = loose.lastModified();
  282. if (ref != null) {
  283. Long cachedlastModified = looseRefsMTime.get(name);
  284. if (cachedlastModified != null && cachedlastModified == mtime) {
  285. if (packedRefs.containsKey(origName))
  286. return new Ref(Storage.LOOSE_PACKED, origName, ref
  287. .getObjectId(), ref.getPeeledObjectId(), ref
  288. .isPeeled());
  289. else
  290. return ref;
  291. }
  292. looseRefs.remove(origName);
  293. looseRefsMTime.remove(origName);
  294. }
  295. if (mtime == 0) {
  296. // If last modified is 0 the file does not exist.
  297. // Try packed cache.
  298. //
  299. ref = packedRefs.get(name);
  300. if (ref != null)
  301. if (!ref.getOrigName().equals(origName))
  302. ref = new Ref(Storage.LOOSE_PACKED, origName, name, ref.getObjectId());
  303. return ref;
  304. }
  305. String line = null;
  306. try {
  307. Long cachedlastModified = looseRefsMTime.get(name);
  308. if (cachedlastModified != null && cachedlastModified == mtime) {
  309. line = looseSymRefs.get(name);
  310. }
  311. if (line == null) {
  312. line = readLine(loose);
  313. looseRefsMTime.put(name, mtime);
  314. looseSymRefs.put(name, line);
  315. }
  316. } catch (FileNotFoundException notLoose) {
  317. return packedRefs.get(name);
  318. }
  319. if (line == null || line.length() == 0) {
  320. looseRefs.remove(origName);
  321. looseRefsMTime.remove(origName);
  322. return new Ref(Ref.Storage.LOOSE, origName, name, null);
  323. }
  324. if (line.startsWith("ref: ")) {
  325. if (depth >= 5) {
  326. throw new IOException("Exceeded maximum ref depth of " + depth
  327. + " at " + name + ". Circular reference?");
  328. }
  329. final String target = line.substring("ref: ".length());
  330. Ref r = readRefBasic(target, target, depth + 1);
  331. Long cachedMtime = looseRefsMTime.get(name);
  332. if (cachedMtime != null && cachedMtime != mtime)
  333. setModified();
  334. looseRefsMTime.put(name, mtime);
  335. if (r == null)
  336. return new Ref(Ref.Storage.LOOSE, origName, target, null);
  337. if (!origName.equals(r.getName()))
  338. r = new Ref(Ref.Storage.LOOSE_PACKED, origName, r.getName(), r.getObjectId(), r.getPeeledObjectId(), true);
  339. return r;
  340. }
  341. setModified();
  342. final ObjectId id;
  343. try {
  344. id = ObjectId.fromString(line);
  345. } catch (IllegalArgumentException notRef) {
  346. throw new IOException("Not a ref: " + name + ": " + line);
  347. }
  348. Storage storage;
  349. if (packedRefs.containsKey(name))
  350. storage = Ref.Storage.LOOSE_PACKED;
  351. else
  352. storage = Ref.Storage.LOOSE;
  353. ref = new Ref(storage, name, id);
  354. looseRefs.put(name, ref);
  355. looseRefsMTime.put(name, mtime);
  356. if (!origName.equals(name)) {
  357. ref = new Ref(Ref.Storage.LOOSE, origName, name, id);
  358. looseRefs.put(origName, ref);
  359. }
  360. return ref;
  361. }
  362. private synchronized void refreshPackedRefs() {
  363. final long currTime = packedRefsFile.lastModified();
  364. final long currLen = currTime == 0 ? 0 : packedRefsFile.length();
  365. if (currTime == packedRefsLastModified && currLen == packedRefsLength)
  366. return;
  367. if (currTime == 0) {
  368. packedRefsLastModified = 0;
  369. packedRefsLength = 0;
  370. packedRefs = new HashMap<String, Ref>();
  371. return;
  372. }
  373. final Map<String, Ref> newPackedRefs = new HashMap<String, Ref>();
  374. try {
  375. final BufferedReader b = openReader(packedRefsFile);
  376. try {
  377. String p;
  378. Ref last = null;
  379. while ((p = b.readLine()) != null) {
  380. if (p.charAt(0) == '#')
  381. continue;
  382. if (p.charAt(0) == '^') {
  383. if (last == null)
  384. throw new IOException("Peeled line before ref.");
  385. final ObjectId id = ObjectId.fromString(p.substring(1));
  386. last = new Ref(Ref.Storage.PACKED, last.getName(), last
  387. .getName(), last.getObjectId(), id, true);
  388. newPackedRefs.put(last.getName(), last);
  389. continue;
  390. }
  391. final int sp = p.indexOf(' ');
  392. final ObjectId id = ObjectId.fromString(p.substring(0, sp));
  393. final String name = copy(p, sp + 1, p.length());
  394. last = new Ref(Ref.Storage.PACKED, name, name, id);
  395. newPackedRefs.put(last.getName(), last);
  396. }
  397. } finally {
  398. b.close();
  399. }
  400. packedRefsLastModified = currTime;
  401. packedRefsLength = currLen;
  402. packedRefs = newPackedRefs;
  403. setModified();
  404. } catch (FileNotFoundException noPackedRefs) {
  405. // Ignore it and leave the new map empty.
  406. //
  407. packedRefsLastModified = 0;
  408. packedRefsLength = 0;
  409. packedRefs = newPackedRefs;
  410. } catch (IOException e) {
  411. throw new RuntimeException("Cannot read packed refs", e);
  412. }
  413. }
  414. private static String copy(final String src, final int off, final int end) {
  415. return new StringBuilder(end - off).append(src, off, end).toString();
  416. }
  417. private void lockAndWriteFile(File file, byte[] content) throws IOException {
  418. String name = file.getName();
  419. final LockFile lck = new LockFile(file);
  420. if (!lck.lock())
  421. throw new ObjectWritingException("Unable to lock " + name);
  422. try {
  423. lck.write(content);
  424. } catch (IOException ioe) {
  425. throw new ObjectWritingException("Unable to write " + name, ioe);
  426. }
  427. if (!lck.commit())
  428. throw new ObjectWritingException("Unable to write " + name);
  429. }
  430. synchronized void removePackedRef(String name) throws IOException {
  431. packedRefs.remove(name);
  432. writePackedRefs();
  433. }
  434. private void writePackedRefs() throws IOException {
  435. new RefWriter(packedRefs.values()) {
  436. @Override
  437. protected void writeFile(String name, byte[] content) throws IOException {
  438. lockAndWriteFile(new File(db.getDirectory(), name), content);
  439. }
  440. }.writePackedRefs();
  441. }
  442. private static String readLine(final File file)
  443. throws FileNotFoundException, IOException {
  444. final byte[] buf = IO.readFully(file, 4096);
  445. int n = buf.length;
  446. // remove trailing whitespaces
  447. while (n > 0 && Character.isWhitespace(buf[n - 1]))
  448. n--;
  449. if (n == 0)
  450. return null;
  451. return RawParseUtils.decode(buf, 0, n);
  452. }
  453. private static BufferedReader openReader(final File fileLocation)
  454. throws FileNotFoundException {
  455. return new BufferedReader(new InputStreamReader(new FileInputStream(
  456. fileLocation), Constants.CHARSET));
  457. }
  458. }