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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. /*
  2. * Copyright (C) 2008-2010, Google Inc.
  3. * Copyright (C) 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 java.io.IOException;
  46. import java.text.MessageFormat;
  47. import org.eclipse.jgit.JGitText;
  48. import org.eclipse.jgit.errors.MissingObjectException;
  49. import org.eclipse.jgit.revwalk.RevCommit;
  50. import org.eclipse.jgit.revwalk.RevObject;
  51. import org.eclipse.jgit.revwalk.RevWalk;
  52. /**
  53. * Creates, updates or deletes any reference.
  54. */
  55. public abstract class RefUpdate {
  56. /** Status of an update request. */
  57. public static enum Result {
  58. /** The ref update/delete has not been attempted by the caller. */
  59. NOT_ATTEMPTED,
  60. /**
  61. * The ref could not be locked for update/delete.
  62. * <p>
  63. * This is generally a transient failure and is usually caused by
  64. * another process trying to access the ref at the same time as this
  65. * process was trying to update it. It is possible a future operation
  66. * will be successful.
  67. */
  68. LOCK_FAILURE,
  69. /**
  70. * Same value already stored.
  71. * <p>
  72. * Both the old value and the new value are identical. No change was
  73. * necessary for an update. For delete the branch is removed.
  74. */
  75. NO_CHANGE,
  76. /**
  77. * The ref was created locally for an update, but ignored for delete.
  78. * <p>
  79. * The ref did not exist when the update started, but it was created
  80. * successfully with the new value.
  81. */
  82. NEW,
  83. /**
  84. * The ref had to be forcefully updated/deleted.
  85. * <p>
  86. * The ref already existed but its old value was not fully merged into
  87. * the new value. The configuration permitted a forced update to take
  88. * place, so ref now contains the new value. History associated with the
  89. * objects not merged may no longer be reachable.
  90. */
  91. FORCED,
  92. /**
  93. * The ref was updated/deleted in a fast-forward way.
  94. * <p>
  95. * The tracking ref already existed and its old value was fully merged
  96. * into the new value. No history was made unreachable.
  97. */
  98. FAST_FORWARD,
  99. /**
  100. * Not a fast-forward and not stored.
  101. * <p>
  102. * The tracking ref already existed but its old value was not fully
  103. * merged into the new value. The configuration did not allow a forced
  104. * update/delete to take place, so ref still contains the old value. No
  105. * previous history was lost.
  106. */
  107. REJECTED,
  108. /**
  109. * Rejected because trying to delete the current branch.
  110. * <p>
  111. * Has no meaning for update.
  112. */
  113. REJECTED_CURRENT_BRANCH,
  114. /**
  115. * The ref was probably not updated/deleted because of I/O error.
  116. * <p>
  117. * Unexpected I/O error occurred when writing new ref. Such error may
  118. * result in uncertain state, but most probably ref was not updated.
  119. * <p>
  120. * This kind of error doesn't include {@link #LOCK_FAILURE}, which is a
  121. * different case.
  122. */
  123. IO_FAILURE,
  124. /**
  125. * The ref was renamed from another name
  126. * <p>
  127. */
  128. RENAMED
  129. }
  130. /** New value the caller wants this ref to have. */
  131. private ObjectId newValue;
  132. /** Does this specification ask for forced updated (rewind/reset)? */
  133. private boolean force;
  134. /** Identity to record action as within the reflog. */
  135. private PersonIdent refLogIdent;
  136. /** Message the caller wants included in the reflog. */
  137. private String refLogMessage;
  138. /** Should the Result value be appended to {@link #refLogMessage}. */
  139. private boolean refLogIncludeResult;
  140. /** Old value of the ref, obtained after we lock it. */
  141. private ObjectId oldValue;
  142. /** If non-null, the value {@link #oldValue} must have to continue. */
  143. private ObjectId expValue;
  144. /** Result of the update operation. */
  145. private Result result = Result.NOT_ATTEMPTED;
  146. private final Ref ref;
  147. /**
  148. * Construct a new update operation for the reference.
  149. * <p>
  150. * {@code ref.getObjectId()} will be used to seed {@link #getOldObjectId()},
  151. * which callers can use as part of their own update logic.
  152. *
  153. * @param ref
  154. * the reference that will be updated by this operation.
  155. */
  156. protected RefUpdate(final Ref ref) {
  157. this.ref = ref;
  158. oldValue = ref.getObjectId();
  159. refLogMessage = "";
  160. }
  161. /** @return the reference database this update modifies. */
  162. protected abstract RefDatabase getRefDatabase();
  163. /** @return the repository storing the database's objects. */
  164. protected abstract Repository getRepository();
  165. /**
  166. * Try to acquire the lock on the reference.
  167. * <p>
  168. * If the locking was successful the implementor must set the current
  169. * identity value by calling {@link #setOldObjectId(ObjectId)}.
  170. *
  171. * @param deref
  172. * true if the lock should be taken against the leaf level
  173. * reference; false if it should be taken exactly against the
  174. * current reference.
  175. * @return true if the lock was acquired and the reference is likely
  176. * protected from concurrent modification; false if it failed.
  177. * @throws IOException
  178. * the lock couldn't be taken due to an unexpected storage
  179. * failure, and not because of a concurrent update.
  180. */
  181. protected abstract boolean tryLock(boolean deref) throws IOException;
  182. /** Releases the lock taken by {@link #tryLock} if it succeeded. */
  183. protected abstract void unlock();
  184. /**
  185. * @param desiredResult
  186. * @return {@code result}
  187. * @throws IOException
  188. */
  189. protected abstract Result doUpdate(Result desiredResult) throws IOException;
  190. /**
  191. * @param desiredResult
  192. * @return {@code result}
  193. * @throws IOException
  194. */
  195. protected abstract Result doDelete(Result desiredResult) throws IOException;
  196. /**
  197. * @param target
  198. * @return {@link Result#NEW} on success.
  199. * @throws IOException
  200. */
  201. protected abstract Result doLink(String target) throws IOException;
  202. /**
  203. * Get the name of the ref this update will operate on.
  204. *
  205. * @return name of underlying ref.
  206. */
  207. public String getName() {
  208. return getRef().getName();
  209. }
  210. /** @return the reference this update will create or modify. */
  211. public Ref getRef() {
  212. return ref;
  213. }
  214. /**
  215. * Get the new value the ref will be (or was) updated to.
  216. *
  217. * @return new value. Null if the caller has not configured it.
  218. */
  219. public ObjectId getNewObjectId() {
  220. return newValue;
  221. }
  222. /**
  223. * Set the new value the ref will update to.
  224. *
  225. * @param id
  226. * the new value.
  227. */
  228. public void setNewObjectId(final AnyObjectId id) {
  229. newValue = id.copy();
  230. }
  231. /**
  232. * @return the expected value of the ref after the lock is taken, but before
  233. * update occurs. Null to avoid the compare and swap test. Use
  234. * {@link ObjectId#zeroId()} to indicate expectation of a
  235. * non-existant ref.
  236. */
  237. public ObjectId getExpectedOldObjectId() {
  238. return expValue;
  239. }
  240. /**
  241. * @param id
  242. * the expected value of the ref after the lock is taken, but
  243. * before update occurs. Null to avoid the compare and swap test.
  244. * Use {@link ObjectId#zeroId()} to indicate expectation of a
  245. * non-existant ref.
  246. */
  247. public void setExpectedOldObjectId(final AnyObjectId id) {
  248. expValue = id != null ? id.toObjectId() : null;
  249. }
  250. /**
  251. * Check if this update wants to forcefully change the ref.
  252. *
  253. * @return true if this update should ignore merge tests.
  254. */
  255. public boolean isForceUpdate() {
  256. return force;
  257. }
  258. /**
  259. * Set if this update wants to forcefully change the ref.
  260. *
  261. * @param b
  262. * true if this update should ignore merge tests.
  263. */
  264. public void setForceUpdate(final boolean b) {
  265. force = b;
  266. }
  267. /** @return identity of the user making the change in the reflog. */
  268. public PersonIdent getRefLogIdent() {
  269. return refLogIdent;
  270. }
  271. /**
  272. * Set the identity of the user appearing in the reflog.
  273. * <p>
  274. * The timestamp portion of the identity is ignored. A new identity with the
  275. * current timestamp will be created automatically when the update occurs
  276. * and the log record is written.
  277. *
  278. * @param pi
  279. * identity of the user. If null the identity will be
  280. * automatically determined based on the repository
  281. * configuration.
  282. */
  283. public void setRefLogIdent(final PersonIdent pi) {
  284. refLogIdent = pi;
  285. }
  286. /**
  287. * Get the message to include in the reflog.
  288. *
  289. * @return message the caller wants to include in the reflog; null if the
  290. * update should not be logged.
  291. */
  292. public String getRefLogMessage() {
  293. return refLogMessage;
  294. }
  295. /** @return {@code true} if the ref log message should show the result. */
  296. protected boolean isRefLogIncludingResult() {
  297. return refLogIncludeResult;
  298. }
  299. /**
  300. * Set the message to include in the reflog.
  301. *
  302. * @param msg
  303. * the message to describe this change. It may be null if
  304. * appendStatus is null in order not to append to the reflog
  305. * @param appendStatus
  306. * true if the status of the ref change (fast-forward or
  307. * forced-update) should be appended to the user supplied
  308. * message.
  309. */
  310. public void setRefLogMessage(final String msg, final boolean appendStatus) {
  311. if (msg == null && !appendStatus)
  312. disableRefLog();
  313. else if (msg == null && appendStatus) {
  314. refLogMessage = "";
  315. refLogIncludeResult = true;
  316. } else {
  317. refLogMessage = msg;
  318. refLogIncludeResult = appendStatus;
  319. }
  320. }
  321. /** Don't record this update in the ref's associated reflog. */
  322. public void disableRefLog() {
  323. refLogMessage = null;
  324. refLogIncludeResult = false;
  325. }
  326. /**
  327. * The old value of the ref, prior to the update being attempted.
  328. * <p>
  329. * This value may differ before and after the update method. Initially it is
  330. * populated with the value of the ref before the lock is taken, but the old
  331. * value may change if someone else modified the ref between the time we
  332. * last read it and when the ref was locked for update.
  333. *
  334. * @return the value of the ref prior to the update being attempted; null if
  335. * the updated has not been attempted yet.
  336. */
  337. public ObjectId getOldObjectId() {
  338. return oldValue;
  339. }
  340. /**
  341. * Set the old value of the ref.
  342. *
  343. * @param old
  344. * the old value.
  345. */
  346. protected void setOldObjectId(ObjectId old) {
  347. oldValue = old;
  348. }
  349. /**
  350. * Get the status of this update.
  351. * <p>
  352. * The same value that was previously returned from an update method.
  353. *
  354. * @return the status of the update.
  355. */
  356. public Result getResult() {
  357. return result;
  358. }
  359. private void requireCanDoUpdate() {
  360. if (newValue == null)
  361. throw new IllegalStateException(JGitText.get().aNewObjectIdIsRequired);
  362. }
  363. /**
  364. * Force the ref to take the new value.
  365. * <p>
  366. * This is just a convenient helper for setting the force flag, and as such
  367. * the merge test is performed.
  368. *
  369. * @return the result status of the update.
  370. * @throws IOException
  371. * an unexpected IO error occurred while writing changes.
  372. */
  373. public Result forceUpdate() throws IOException {
  374. force = true;
  375. return update();
  376. }
  377. /**
  378. * Gracefully update the ref to the new value.
  379. * <p>
  380. * Merge test will be performed according to {@link #isForceUpdate()}.
  381. * <p>
  382. * This is the same as:
  383. *
  384. * <pre>
  385. * return update(new RevWalk(getRepository()));
  386. * </pre>
  387. *
  388. * @return the result status of the update.
  389. * @throws IOException
  390. * an unexpected IO error occurred while writing changes.
  391. */
  392. public Result update() throws IOException {
  393. RevWalk rw = new RevWalk(getRepository());
  394. try {
  395. return update(rw);
  396. } finally {
  397. rw.release();
  398. }
  399. }
  400. /**
  401. * Gracefully update the ref to the new value.
  402. * <p>
  403. * Merge test will be performed according to {@link #isForceUpdate()}.
  404. *
  405. * @param walk
  406. * a RevWalk instance this update command can borrow to perform
  407. * the merge test. The walk will be reset to perform the test.
  408. * @return the result status of the update.
  409. * @throws IOException
  410. * an unexpected IO error occurred while writing changes.
  411. */
  412. public Result update(final RevWalk walk) throws IOException {
  413. requireCanDoUpdate();
  414. try {
  415. return result = updateImpl(walk, new Store() {
  416. @Override
  417. Result execute(Result status) throws IOException {
  418. if (status == Result.NO_CHANGE)
  419. return status;
  420. return doUpdate(status);
  421. }
  422. });
  423. } catch (IOException x) {
  424. result = Result.IO_FAILURE;
  425. throw x;
  426. }
  427. }
  428. /**
  429. * Delete the ref.
  430. * <p>
  431. * This is the same as:
  432. *
  433. * <pre>
  434. * return delete(new RevWalk(getRepository()));
  435. * </pre>
  436. *
  437. * @return the result status of the delete.
  438. * @throws IOException
  439. */
  440. public Result delete() throws IOException {
  441. RevWalk rw = new RevWalk(getRepository());
  442. try {
  443. return delete(rw);
  444. } finally {
  445. rw.release();
  446. }
  447. }
  448. /**
  449. * Delete the ref.
  450. *
  451. * @param walk
  452. * a RevWalk instance this delete command can borrow to perform
  453. * the merge test. The walk will be reset to perform the test.
  454. * @return the result status of the delete.
  455. * @throws IOException
  456. */
  457. public Result delete(final RevWalk walk) throws IOException {
  458. final String myName = getRef().getLeaf().getName();
  459. if (myName.startsWith(Constants.R_HEADS)) {
  460. Ref head = getRefDatabase().getRef(Constants.HEAD);
  461. while (head.isSymbolic()) {
  462. head = head.getTarget();
  463. if (myName.equals(head.getName()))
  464. return result = Result.REJECTED_CURRENT_BRANCH;
  465. }
  466. }
  467. try {
  468. return result = updateImpl(walk, new Store() {
  469. @Override
  470. Result execute(Result status) throws IOException {
  471. return doDelete(status);
  472. }
  473. });
  474. } catch (IOException x) {
  475. result = Result.IO_FAILURE;
  476. throw x;
  477. }
  478. }
  479. /**
  480. * Replace this reference with a symbolic reference to another reference.
  481. * <p>
  482. * This exact reference (not its traversed leaf) is replaced with a symbolic
  483. * reference to the requested name.
  484. *
  485. * @param target
  486. * name of the new target for this reference. The new target name
  487. * must be absolute, so it must begin with {@code refs/}.
  488. * @return {@link Result#NEW} or {@link Result#FORCED} on success.
  489. * @throws IOException
  490. */
  491. public Result link(String target) throws IOException {
  492. if (!target.startsWith(Constants.R_REFS))
  493. throw new IllegalArgumentException(MessageFormat.format(JGitText.get().illegalArgumentNotA, Constants.R_REFS));
  494. if (getRefDatabase().isNameConflicting(getName()))
  495. return Result.LOCK_FAILURE;
  496. try {
  497. if (!tryLock(false))
  498. return Result.LOCK_FAILURE;
  499. final Ref old = getRefDatabase().getRef(getName());
  500. if (old != null && old.isSymbolic()) {
  501. final Ref dst = old.getTarget();
  502. if (target.equals(dst.getName()))
  503. return result = Result.NO_CHANGE;
  504. }
  505. if (old != null && old.getObjectId() != null)
  506. setOldObjectId(old.getObjectId());
  507. final Ref dst = getRefDatabase().getRef(target);
  508. if (dst != null && dst.getObjectId() != null)
  509. setNewObjectId(dst.getObjectId());
  510. return result = doLink(target);
  511. } catch (IOException x) {
  512. result = Result.IO_FAILURE;
  513. throw x;
  514. } finally {
  515. unlock();
  516. }
  517. }
  518. private Result updateImpl(final RevWalk walk, final Store store)
  519. throws IOException {
  520. RevObject newObj;
  521. RevObject oldObj;
  522. if (getRefDatabase().isNameConflicting(getName()))
  523. return Result.LOCK_FAILURE;
  524. try {
  525. if (!tryLock(true))
  526. return Result.LOCK_FAILURE;
  527. if (expValue != null) {
  528. final ObjectId o;
  529. o = oldValue != null ? oldValue : ObjectId.zeroId();
  530. if (!AnyObjectId.equals(expValue, o))
  531. return Result.LOCK_FAILURE;
  532. }
  533. if (oldValue == null)
  534. return store.execute(Result.NEW);
  535. newObj = safeParse(walk, newValue);
  536. oldObj = safeParse(walk, oldValue);
  537. if (newObj == oldObj)
  538. return store.execute(Result.NO_CHANGE);
  539. if (newObj instanceof RevCommit && oldObj instanceof RevCommit) {
  540. if (walk.isMergedInto((RevCommit) oldObj, (RevCommit) newObj))
  541. return store.execute(Result.FAST_FORWARD);
  542. }
  543. if (isForceUpdate())
  544. return store.execute(Result.FORCED);
  545. return Result.REJECTED;
  546. } finally {
  547. unlock();
  548. }
  549. }
  550. private static RevObject safeParse(final RevWalk rw, final AnyObjectId id)
  551. throws IOException {
  552. try {
  553. return id != null ? rw.parseAny(id) : null;
  554. } catch (MissingObjectException e) {
  555. // We can expect some objects to be missing, like if we are
  556. // trying to force a deletion of a branch and the object it
  557. // points to has been pruned from the database due to freak
  558. // corruption accidents (it happens with 'git new-work-dir').
  559. //
  560. return null;
  561. }
  562. }
  563. /**
  564. * Handle the abstraction of storing a ref update. This is because both
  565. * updating and deleting of a ref have merge testing in common.
  566. */
  567. private abstract class Store {
  568. abstract Result execute(Result status) throws IOException;
  569. }
  570. }