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.

RefUpdate.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. /*
  2. * Copyright (C) 2008, Charles O'Farrell <charleso@charleso.org>
  3. * Copyright (C) 2008-2009, Google Inc.
  4. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  5. * and other copyright owners as documented in the project's IP log.
  6. *
  7. * This program and the accompanying materials are made available
  8. * under the terms of the Eclipse Distribution License v1.0 which
  9. * accompanies this distribution, is reproduced below, and is
  10. * available at http://www.eclipse.org/org/documents/edl-v10.php
  11. *
  12. * All rights reserved.
  13. *
  14. * Redistribution and use in source and binary forms, with or
  15. * without modification, are permitted provided that the following
  16. * conditions are met:
  17. *
  18. * - Redistributions of source code must retain the above copyright
  19. * notice, this list of conditions and the following disclaimer.
  20. *
  21. * - Redistributions in binary form must reproduce the above
  22. * copyright notice, this list of conditions and the following
  23. * disclaimer in the documentation and/or other materials provided
  24. * with the distribution.
  25. *
  26. * - Neither the name of the Eclipse Foundation, Inc. nor the
  27. * names of its contributors may be used to endorse or promote
  28. * products derived from this software without specific prior
  29. * written permission.
  30. *
  31. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  32. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  33. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  34. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  35. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  36. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  37. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  38. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  39. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  40. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  41. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  42. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  43. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  44. */
  45. package org.eclipse.jgit.lib;
  46. import java.io.File;
  47. import java.io.IOException;
  48. import org.eclipse.jgit.errors.MissingObjectException;
  49. import org.eclipse.jgit.lib.Ref.Storage;
  50. import org.eclipse.jgit.revwalk.RevCommit;
  51. import org.eclipse.jgit.revwalk.RevObject;
  52. import org.eclipse.jgit.revwalk.RevWalk;
  53. /**
  54. * Updates any locally stored ref.
  55. */
  56. public class RefUpdate {
  57. /** Status of an update request. */
  58. public static enum Result {
  59. /** The ref update/delete has not been attempted by the caller. */
  60. NOT_ATTEMPTED,
  61. /**
  62. * The ref could not be locked for update/delete.
  63. * <p>
  64. * This is generally a transient failure and is usually caused by
  65. * another process trying to access the ref at the same time as this
  66. * process was trying to update it. It is possible a future operation
  67. * will be successful.
  68. */
  69. LOCK_FAILURE,
  70. /**
  71. * Same value already stored.
  72. * <p>
  73. * Both the old value and the new value are identical. No change was
  74. * necessary for an update. For delete the branch is removed.
  75. */
  76. NO_CHANGE,
  77. /**
  78. * The ref was created locally for an update, but ignored for delete.
  79. * <p>
  80. * The ref did not exist when the update started, but it was created
  81. * successfully with the new value.
  82. */
  83. NEW,
  84. /**
  85. * The ref had to be forcefully updated/deleted.
  86. * <p>
  87. * The ref already existed but its old value was not fully merged into
  88. * the new value. The configuration permitted a forced update to take
  89. * place, so ref now contains the new value. History associated with the
  90. * objects not merged may no longer be reachable.
  91. */
  92. FORCED,
  93. /**
  94. * The ref was updated/deleted in a fast-forward way.
  95. * <p>
  96. * The tracking ref already existed and its old value was fully merged
  97. * into the new value. No history was made unreachable.
  98. */
  99. FAST_FORWARD,
  100. /**
  101. * Not a fast-forward and not stored.
  102. * <p>
  103. * The tracking ref already existed but its old value was not fully
  104. * merged into the new value. The configuration did not allow a forced
  105. * update/delete to take place, so ref still contains the old value. No
  106. * previous history was lost.
  107. */
  108. REJECTED,
  109. /**
  110. * Rejected because trying to delete the current branch.
  111. * <p>
  112. * Has no meaning for update.
  113. */
  114. REJECTED_CURRENT_BRANCH,
  115. /**
  116. * The ref was probably not updated/deleted because of I/O error.
  117. * <p>
  118. * Unexpected I/O error occurred when writing new ref. Such error may
  119. * result in uncertain state, but most probably ref was not updated.
  120. * <p>
  121. * This kind of error doesn't include {@link #LOCK_FAILURE}, which is a
  122. * different case.
  123. */
  124. IO_FAILURE,
  125. /**
  126. * The ref was renamed from another name
  127. * <p>
  128. */
  129. RENAMED
  130. }
  131. /** Repository the ref is stored in. */
  132. final RefDatabase db;
  133. /** Location of the loose file holding the value of this ref. */
  134. final File looseFile;
  135. /** New value the caller wants this ref to have. */
  136. private ObjectId newValue;
  137. /** Does this specification ask for forced updated (rewind/reset)? */
  138. private boolean force;
  139. /** Identity to record action as within the reflog. */
  140. private PersonIdent refLogIdent;
  141. /** Message the caller wants included in the reflog. */
  142. private String refLogMessage;
  143. /** Should the Result value be appended to {@link #refLogMessage}. */
  144. private boolean refLogIncludeResult;
  145. /** Old value of the ref, obtained after we lock it. */
  146. private ObjectId oldValue;
  147. /** If non-null, the value {@link #oldValue} must have to continue. */
  148. private ObjectId expValue;
  149. /** Result of the update operation. */
  150. Result result = Result.NOT_ATTEMPTED;
  151. private final Ref ref;
  152. RefUpdate(final RefDatabase r, final Ref ref, final File f) {
  153. db = r;
  154. this.ref = ref;
  155. oldValue = ref.getObjectId();
  156. looseFile = f;
  157. refLogMessage = "";
  158. }
  159. /** @return the repository the updated ref resides in */
  160. public Repository getRepository() {
  161. return db.getRepository();
  162. }
  163. /**
  164. * Get the name of the ref this update will operate on.
  165. *
  166. * @return name of underlying ref.
  167. */
  168. public String getName() {
  169. return ref.getName();
  170. }
  171. /**
  172. * Get the requested name of the ref thit update will operate on
  173. *
  174. * @return original (requested) name of the underlying ref.
  175. */
  176. public String getOrigName() {
  177. return ref.getOrigName();
  178. }
  179. /**
  180. * Get the new value the ref will be (or was) updated to.
  181. *
  182. * @return new value. Null if the caller has not configured it.
  183. */
  184. public ObjectId getNewObjectId() {
  185. return newValue;
  186. }
  187. /**
  188. * Set the new value the ref will update to.
  189. *
  190. * @param id
  191. * the new value.
  192. */
  193. public void setNewObjectId(final AnyObjectId id) {
  194. newValue = id.copy();
  195. }
  196. /**
  197. * @return the expected value of the ref after the lock is taken, but before
  198. * update occurs. Null to avoid the compare and swap test. Use
  199. * {@link ObjectId#zeroId()} to indicate expectation of a
  200. * non-existant ref.
  201. */
  202. public ObjectId getExpectedOldObjectId() {
  203. return expValue;
  204. }
  205. /**
  206. * @param id
  207. * the expected value of the ref after the lock is taken, but
  208. * before update occurs. Null to avoid the compare and swap test.
  209. * Use {@link ObjectId#zeroId()} to indicate expectation of a
  210. * non-existant ref.
  211. */
  212. public void setExpectedOldObjectId(final AnyObjectId id) {
  213. expValue = id != null ? id.toObjectId() : null;
  214. }
  215. /**
  216. * Check if this update wants to forcefully change the ref.
  217. *
  218. * @return true if this update should ignore merge tests.
  219. */
  220. public boolean isForceUpdate() {
  221. return force;
  222. }
  223. /**
  224. * Set if this update wants to forcefully change the ref.
  225. *
  226. * @param b
  227. * true if this update should ignore merge tests.
  228. */
  229. public void setForceUpdate(final boolean b) {
  230. force = b;
  231. }
  232. /** @return identity of the user making the change in the reflog. */
  233. public PersonIdent getRefLogIdent() {
  234. return refLogIdent;
  235. }
  236. /**
  237. * Set the identity of the user appearing in the reflog.
  238. * <p>
  239. * The timestamp portion of the identity is ignored. A new identity with the
  240. * current timestamp will be created automatically when the update occurs
  241. * and the log record is written.
  242. *
  243. * @param pi
  244. * identity of the user. If null the identity will be
  245. * automatically determined based on the repository
  246. * configuration.
  247. */
  248. public void setRefLogIdent(final PersonIdent pi) {
  249. refLogIdent = pi;
  250. }
  251. /**
  252. * Get the message to include in the reflog.
  253. *
  254. * @return message the caller wants to include in the reflog; null if the
  255. * update should not be logged.
  256. */
  257. public String getRefLogMessage() {
  258. return refLogMessage;
  259. }
  260. /**
  261. * Set the message to include in the reflog.
  262. *
  263. * @param msg
  264. * the message to describe this change. It may be null
  265. * if appendStatus is null in order not to append to the reflog
  266. * @param appendStatus
  267. * true if the status of the ref change (fast-forward or
  268. * forced-update) should be appended to the user supplied
  269. * message.
  270. */
  271. public void setRefLogMessage(final String msg, final boolean appendStatus) {
  272. if (msg == null && !appendStatus)
  273. disableRefLog();
  274. else if (msg == null && appendStatus) {
  275. refLogMessage = "";
  276. refLogIncludeResult = true;
  277. } else {
  278. refLogMessage = msg;
  279. refLogIncludeResult = appendStatus;
  280. }
  281. }
  282. /** Don't record this update in the ref's associated reflog. */
  283. public void disableRefLog() {
  284. refLogMessage = null;
  285. refLogIncludeResult = false;
  286. }
  287. /**
  288. * The old value of the ref, prior to the update being attempted.
  289. * <p>
  290. * This value may differ before and after the update method. Initially it is
  291. * populated with the value of the ref before the lock is taken, but the old
  292. * value may change if someone else modified the ref between the time we
  293. * last read it and when the ref was locked for update.
  294. *
  295. * @return the value of the ref prior to the update being attempted; null if
  296. * the updated has not been attempted yet.
  297. */
  298. public ObjectId getOldObjectId() {
  299. return oldValue;
  300. }
  301. /**
  302. * Get the status of this update.
  303. * <p>
  304. * The same value that was previously returned from an update method.
  305. *
  306. * @return the status of the update.
  307. */
  308. public Result getResult() {
  309. return result;
  310. }
  311. private void requireCanDoUpdate() {
  312. if (newValue == null)
  313. throw new IllegalStateException("A NewObjectId is required.");
  314. }
  315. /**
  316. * Force the ref to take the new value.
  317. * <p>
  318. * This is just a convenient helper for setting the force flag, and as such
  319. * the merge test is performed.
  320. *
  321. * @return the result status of the update.
  322. * @throws IOException
  323. * an unexpected IO error occurred while writing changes.
  324. */
  325. public Result forceUpdate() throws IOException {
  326. force = true;
  327. return update();
  328. }
  329. /**
  330. * Gracefully update the ref to the new value.
  331. * <p>
  332. * Merge test will be performed according to {@link #isForceUpdate()}.
  333. * <p>
  334. * This is the same as:
  335. *
  336. * <pre>
  337. * return update(new RevWalk(repository));
  338. * </pre>
  339. *
  340. * @return the result status of the update.
  341. * @throws IOException
  342. * an unexpected IO error occurred while writing changes.
  343. */
  344. public Result update() throws IOException {
  345. return update(new RevWalk(db.getRepository()));
  346. }
  347. /**
  348. * Gracefully update the ref to the new value.
  349. * <p>
  350. * Merge test will be performed according to {@link #isForceUpdate()}.
  351. *
  352. * @param walk
  353. * a RevWalk instance this update command can borrow to perform
  354. * the merge test. The walk will be reset to perform the test.
  355. * @return the result status of the update.
  356. * @throws IOException
  357. * an unexpected IO error occurred while writing changes.
  358. */
  359. public Result update(final RevWalk walk) throws IOException {
  360. requireCanDoUpdate();
  361. try {
  362. return result = updateImpl(walk, new UpdateStore());
  363. } catch (IOException x) {
  364. result = Result.IO_FAILURE;
  365. throw x;
  366. }
  367. }
  368. /**
  369. * Delete the ref.
  370. * <p>
  371. * This is the same as:
  372. *
  373. * <pre>
  374. * return delete(new RevWalk(repository));
  375. * </pre>
  376. *
  377. * @return the result status of the delete.
  378. * @throws IOException
  379. */
  380. public Result delete() throws IOException {
  381. return delete(new RevWalk(db.getRepository()));
  382. }
  383. /**
  384. * Delete the ref.
  385. *
  386. * @param walk
  387. * a RevWalk instance this delete command can borrow to perform
  388. * the merge test. The walk will be reset to perform the test.
  389. * @return the result status of the delete.
  390. * @throws IOException
  391. */
  392. public Result delete(final RevWalk walk) throws IOException {
  393. if (getName().startsWith(Constants.R_HEADS)) {
  394. final Ref head = db.readRef(Constants.HEAD);
  395. if (head != null && getName().equals(head.getName()))
  396. return result = Result.REJECTED_CURRENT_BRANCH;
  397. }
  398. try {
  399. return result = updateImpl(walk, new DeleteStore());
  400. } catch (IOException x) {
  401. result = Result.IO_FAILURE;
  402. throw x;
  403. }
  404. }
  405. private Result updateImpl(final RevWalk walk, final Store store)
  406. throws IOException {
  407. final LockFile lock;
  408. RevObject newObj;
  409. RevObject oldObj;
  410. if (isNameConflicting())
  411. return Result.LOCK_FAILURE;
  412. lock = new LockFile(looseFile);
  413. if (!lock.lock())
  414. return Result.LOCK_FAILURE;
  415. try {
  416. oldValue = db.idOf(getName());
  417. if (expValue != null) {
  418. final ObjectId o;
  419. o = oldValue != null ? oldValue : ObjectId.zeroId();
  420. if (!AnyObjectId.equals(expValue, o))
  421. return Result.LOCK_FAILURE;
  422. }
  423. if (oldValue == null)
  424. return store.store(lock, Result.NEW);
  425. newObj = safeParse(walk, newValue);
  426. oldObj = safeParse(walk, oldValue);
  427. if (newObj == oldObj)
  428. return store.store(lock, Result.NO_CHANGE);
  429. if (newObj instanceof RevCommit && oldObj instanceof RevCommit) {
  430. if (walk.isMergedInto((RevCommit) oldObj, (RevCommit) newObj))
  431. return store.store(lock, Result.FAST_FORWARD);
  432. }
  433. if (isForceUpdate())
  434. return store.store(lock, Result.FORCED);
  435. return Result.REJECTED;
  436. } finally {
  437. lock.unlock();
  438. }
  439. }
  440. private boolean isNameConflicting() throws IOException {
  441. final String myName = getName();
  442. final int lastSlash = myName.lastIndexOf('/');
  443. if (lastSlash > 0)
  444. if (db.getRepository().getRef(myName.substring(0, lastSlash)) != null)
  445. return true;
  446. final String rName = myName + "/";
  447. for (Ref r : db.getAllRefs().values()) {
  448. if (r.getName().startsWith(rName))
  449. return true;
  450. }
  451. return false;
  452. }
  453. private static RevObject safeParse(final RevWalk rw, final AnyObjectId id)
  454. throws IOException {
  455. try {
  456. return id != null ? rw.parseAny(id) : null;
  457. } catch (MissingObjectException e) {
  458. // We can expect some objects to be missing, like if we are
  459. // trying to force a deletion of a branch and the object it
  460. // points to has been pruned from the database due to freak
  461. // corruption accidents (it happens with 'git new-work-dir').
  462. //
  463. return null;
  464. }
  465. }
  466. private Result updateStore(final LockFile lock, final Result status)
  467. throws IOException {
  468. if (status == Result.NO_CHANGE)
  469. return status;
  470. lock.setNeedStatInformation(true);
  471. lock.write(newValue);
  472. String msg = getRefLogMessage();
  473. if (msg != null) {
  474. if (refLogIncludeResult) {
  475. String strResult = toResultString(status);
  476. if (strResult != null) {
  477. if (msg.length() > 0)
  478. msg = msg + ": " + strResult;
  479. else
  480. msg = strResult;
  481. }
  482. }
  483. RefLogWriter.append(this, msg);
  484. }
  485. if (!lock.commit())
  486. return Result.LOCK_FAILURE;
  487. db.stored(this.ref.getOrigName(), ref.getName(), newValue, lock.getCommitLastModified());
  488. return status;
  489. }
  490. private static String toResultString(final Result status) {
  491. switch (status) {
  492. case FORCED:
  493. return "forced-update";
  494. case FAST_FORWARD:
  495. return "fast forward";
  496. case NEW:
  497. return "created";
  498. default:
  499. return null;
  500. }
  501. }
  502. /**
  503. * Handle the abstraction of storing a ref update. This is because both
  504. * updating and deleting of a ref have merge testing in common.
  505. */
  506. private abstract class Store {
  507. abstract Result store(final LockFile lock, final Result status)
  508. throws IOException;
  509. }
  510. class UpdateStore extends Store {
  511. @Override
  512. Result store(final LockFile lock, final Result status)
  513. throws IOException {
  514. return updateStore(lock, status);
  515. }
  516. }
  517. class DeleteStore extends Store {
  518. @Override
  519. Result store(LockFile lock, Result status) throws IOException {
  520. Storage storage = ref.getStorage();
  521. if (storage == Storage.NEW)
  522. return status;
  523. if (storage.isPacked())
  524. db.removePackedRef(ref.getName());
  525. final int levels = count(ref.getName(), '/') - 2;
  526. // Delete logs _before_ unlocking
  527. final File gitDir = db.getRepository().getDirectory();
  528. final File logDir = new File(gitDir, Constants.LOGS);
  529. deleteFileAndEmptyDir(new File(logDir, ref.getName()), levels);
  530. // We have to unlock before (maybe) deleting the parent directories
  531. lock.unlock();
  532. if (storage.isLoose())
  533. deleteFileAndEmptyDir(looseFile, levels);
  534. db.uncacheRef(ref.getName());
  535. return status;
  536. }
  537. private void deleteFileAndEmptyDir(final File file, final int depth)
  538. throws IOException {
  539. if (file.isFile()) {
  540. if (!file.delete())
  541. throw new IOException("File cannot be deleted: " + file);
  542. File dir = file.getParentFile();
  543. for (int i = 0; i < depth; ++i) {
  544. if (!dir.delete())
  545. break; // ignore problem here
  546. dir = dir.getParentFile();
  547. }
  548. }
  549. }
  550. }
  551. UpdateStore newUpdateStore() {
  552. return new UpdateStore();
  553. }
  554. DeleteStore newDeleteStore() {
  555. return new DeleteStore();
  556. }
  557. static void deleteEmptyDir(File dir, int depth) {
  558. for (; depth > 0 && dir != null; depth--) {
  559. if (dir.exists() && !dir.delete())
  560. break;
  561. dir = dir.getParentFile();
  562. }
  563. }
  564. static int count(final String s, final char c) {
  565. int count = 0;
  566. for (int p = s.indexOf(c); p >= 0; p = s.indexOf(c, p + 1)) {
  567. count++;
  568. }
  569. return count;
  570. }
  571. }