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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  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.errors.MissingObjectException;
  48. import org.eclipse.jgit.internal.JGitText;
  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. * Is this RefUpdate detaching a symbolic ref?
  149. *
  150. * We need this info since this.ref will normally be peeled of in case of
  151. * detaching a symbolic ref (HEAD for example).
  152. *
  153. * Without this flag we cannot decide whether the ref has to be updated or
  154. * not in case when it was a symbolic ref and the newValue == oldValue.
  155. */
  156. private boolean detachingSymbolicRef;
  157. private boolean checkConflicting = true;
  158. /**
  159. * Construct a new update operation for the reference.
  160. * <p>
  161. * {@code ref.getObjectId()} will be used to seed {@link #getOldObjectId()},
  162. * which callers can use as part of their own update logic.
  163. *
  164. * @param ref
  165. * the reference that will be updated by this operation.
  166. */
  167. protected RefUpdate(final Ref ref) {
  168. this.ref = ref;
  169. oldValue = ref.getObjectId();
  170. refLogMessage = ""; //$NON-NLS-1$
  171. }
  172. /** @return the reference database this update modifies. */
  173. protected abstract RefDatabase getRefDatabase();
  174. /** @return the repository storing the database's objects. */
  175. protected abstract Repository getRepository();
  176. /**
  177. * Try to acquire the lock on the reference.
  178. * <p>
  179. * If the locking was successful the implementor must set the current
  180. * identity value by calling {@link #setOldObjectId(ObjectId)}.
  181. *
  182. * @param deref
  183. * true if the lock should be taken against the leaf level
  184. * reference; false if it should be taken exactly against the
  185. * current reference.
  186. * @return true if the lock was acquired and the reference is likely
  187. * protected from concurrent modification; false if it failed.
  188. * @throws IOException
  189. * the lock couldn't be taken due to an unexpected storage
  190. * failure, and not because of a concurrent update.
  191. */
  192. protected abstract boolean tryLock(boolean deref) throws IOException;
  193. /** Releases the lock taken by {@link #tryLock} if it succeeded. */
  194. protected abstract void unlock();
  195. /**
  196. * @param desiredResult
  197. * @return {@code result}
  198. * @throws IOException
  199. */
  200. protected abstract Result doUpdate(Result desiredResult) throws IOException;
  201. /**
  202. * @param desiredResult
  203. * @return {@code result}
  204. * @throws IOException
  205. */
  206. protected abstract Result doDelete(Result desiredResult) throws IOException;
  207. /**
  208. * @param target
  209. * @return {@link Result#NEW} on success.
  210. * @throws IOException
  211. */
  212. protected abstract Result doLink(String target) throws IOException;
  213. /**
  214. * Get the name of the ref this update will operate on.
  215. *
  216. * @return name of underlying ref.
  217. */
  218. public String getName() {
  219. return getRef().getName();
  220. }
  221. /** @return the reference this update will create or modify. */
  222. public Ref getRef() {
  223. return ref;
  224. }
  225. /**
  226. * Get the new value the ref will be (or was) updated to.
  227. *
  228. * @return new value. Null if the caller has not configured it.
  229. */
  230. public ObjectId getNewObjectId() {
  231. return newValue;
  232. }
  233. /**
  234. * Tells this RefUpdate that it is actually detaching a symbolic ref.
  235. */
  236. public void setDetachingSymbolicRef() {
  237. detachingSymbolicRef = true;
  238. }
  239. /**
  240. * Set the new value the ref will update to.
  241. *
  242. * @param id
  243. * the new value.
  244. */
  245. public void setNewObjectId(final AnyObjectId id) {
  246. newValue = id.copy();
  247. }
  248. /**
  249. * @return the expected value of the ref after the lock is taken, but before
  250. * update occurs. Null to avoid the compare and swap test. Use
  251. * {@link ObjectId#zeroId()} to indicate expectation of a
  252. * non-existant ref.
  253. */
  254. public ObjectId getExpectedOldObjectId() {
  255. return expValue;
  256. }
  257. /**
  258. * @param id
  259. * the expected value of the ref after the lock is taken, but
  260. * before update occurs. Null to avoid the compare and swap test.
  261. * Use {@link ObjectId#zeroId()} to indicate expectation of a
  262. * non-existant ref.
  263. */
  264. public void setExpectedOldObjectId(final AnyObjectId id) {
  265. expValue = id != null ? id.toObjectId() : null;
  266. }
  267. /**
  268. * Check if this update wants to forcefully change the ref.
  269. *
  270. * @return true if this update should ignore merge tests.
  271. */
  272. public boolean isForceUpdate() {
  273. return force;
  274. }
  275. /**
  276. * Set if this update wants to forcefully change the ref.
  277. *
  278. * @param b
  279. * true if this update should ignore merge tests.
  280. */
  281. public void setForceUpdate(final boolean b) {
  282. force = b;
  283. }
  284. /** @return identity of the user making the change in the reflog. */
  285. public PersonIdent getRefLogIdent() {
  286. return refLogIdent;
  287. }
  288. /**
  289. * Set the identity of the user appearing in the reflog.
  290. * <p>
  291. * The timestamp portion of the identity is ignored. A new identity with the
  292. * current timestamp will be created automatically when the update occurs
  293. * and the log record is written.
  294. *
  295. * @param pi
  296. * identity of the user. If null the identity will be
  297. * automatically determined based on the repository
  298. * configuration.
  299. */
  300. public void setRefLogIdent(final PersonIdent pi) {
  301. refLogIdent = pi;
  302. }
  303. /**
  304. * Get the message to include in the reflog.
  305. *
  306. * @return message the caller wants to include in the reflog; null if the
  307. * update should not be logged.
  308. */
  309. public String getRefLogMessage() {
  310. return refLogMessage;
  311. }
  312. /** @return {@code true} if the ref log message should show the result. */
  313. protected boolean isRefLogIncludingResult() {
  314. return refLogIncludeResult;
  315. }
  316. /**
  317. * Set the message to include in the reflog.
  318. *
  319. * @param msg
  320. * the message to describe this change. It may be null if
  321. * appendStatus is null in order not to append to the reflog
  322. * @param appendStatus
  323. * true if the status of the ref change (fast-forward or
  324. * forced-update) should be appended to the user supplied
  325. * message.
  326. */
  327. public void setRefLogMessage(final String msg, final boolean appendStatus) {
  328. if (msg == null && !appendStatus)
  329. disableRefLog();
  330. else if (msg == null && appendStatus) {
  331. refLogMessage = ""; //$NON-NLS-1$
  332. refLogIncludeResult = true;
  333. } else {
  334. refLogMessage = msg;
  335. refLogIncludeResult = appendStatus;
  336. }
  337. }
  338. /** Don't record this update in the ref's associated reflog. */
  339. public void disableRefLog() {
  340. refLogMessage = null;
  341. refLogIncludeResult = false;
  342. }
  343. /**
  344. * The old value of the ref, prior to the update being attempted.
  345. * <p>
  346. * This value may differ before and after the update method. Initially it is
  347. * populated with the value of the ref before the lock is taken, but the old
  348. * value may change if someone else modified the ref between the time we
  349. * last read it and when the ref was locked for update.
  350. *
  351. * @return the value of the ref prior to the update being attempted; null if
  352. * the updated has not been attempted yet.
  353. */
  354. public ObjectId getOldObjectId() {
  355. return oldValue;
  356. }
  357. /**
  358. * Set the old value of the ref.
  359. *
  360. * @param old
  361. * the old value.
  362. */
  363. protected void setOldObjectId(ObjectId old) {
  364. oldValue = old;
  365. }
  366. /**
  367. * Get the status of this update.
  368. * <p>
  369. * The same value that was previously returned from an update method.
  370. *
  371. * @return the status of the update.
  372. */
  373. public Result getResult() {
  374. return result;
  375. }
  376. private void requireCanDoUpdate() {
  377. if (newValue == null)
  378. throw new IllegalStateException(JGitText.get().aNewObjectIdIsRequired);
  379. }
  380. /**
  381. * Force the ref to take the new value.
  382. * <p>
  383. * This is just a convenient helper for setting the force flag, and as such
  384. * the merge test is performed.
  385. *
  386. * @return the result status of the update.
  387. * @throws IOException
  388. * an unexpected IO error occurred while writing changes.
  389. */
  390. public Result forceUpdate() throws IOException {
  391. force = true;
  392. return update();
  393. }
  394. /**
  395. * Gracefully update the ref to the new value.
  396. * <p>
  397. * Merge test will be performed according to {@link #isForceUpdate()}.
  398. * <p>
  399. * This is the same as:
  400. *
  401. * <pre>
  402. * return update(new RevWalk(getRepository()));
  403. * </pre>
  404. *
  405. * @return the result status of the update.
  406. * @throws IOException
  407. * an unexpected IO error occurred while writing changes.
  408. */
  409. public Result update() throws IOException {
  410. RevWalk rw = new RevWalk(getRepository());
  411. try {
  412. return update(rw);
  413. } finally {
  414. rw.release();
  415. }
  416. }
  417. /**
  418. * Gracefully update the ref to the new value.
  419. * <p>
  420. * Merge test will be performed according to {@link #isForceUpdate()}.
  421. *
  422. * @param walk
  423. * a RevWalk instance this update command can borrow to perform
  424. * the merge test. The walk will be reset to perform the test.
  425. * @return the result status of the update.
  426. * @throws IOException
  427. * an unexpected IO error occurred while writing changes.
  428. */
  429. public Result update(final RevWalk walk) throws IOException {
  430. requireCanDoUpdate();
  431. try {
  432. return result = updateImpl(walk, new Store() {
  433. @Override
  434. Result execute(Result status) throws IOException {
  435. if (status == Result.NO_CHANGE)
  436. return status;
  437. return doUpdate(status);
  438. }
  439. });
  440. } catch (IOException x) {
  441. result = Result.IO_FAILURE;
  442. throw x;
  443. }
  444. }
  445. /**
  446. * Delete the ref.
  447. * <p>
  448. * This is the same as:
  449. *
  450. * <pre>
  451. * return delete(new RevWalk(getRepository()));
  452. * </pre>
  453. *
  454. * @return the result status of the delete.
  455. * @throws IOException
  456. */
  457. public Result delete() throws IOException {
  458. RevWalk rw = new RevWalk(getRepository());
  459. try {
  460. return delete(rw);
  461. } finally {
  462. rw.release();
  463. }
  464. }
  465. /**
  466. * Delete the ref.
  467. *
  468. * @param walk
  469. * a RevWalk instance this delete command can borrow to perform
  470. * the merge test. The walk will be reset to perform the test.
  471. * @return the result status of the delete.
  472. * @throws IOException
  473. */
  474. public Result delete(final RevWalk walk) throws IOException {
  475. final String myName = getRef().getLeaf().getName();
  476. if (myName.startsWith(Constants.R_HEADS)) {
  477. Ref head = getRefDatabase().getRef(Constants.HEAD);
  478. while (head.isSymbolic()) {
  479. head = head.getTarget();
  480. if (myName.equals(head.getName()))
  481. return result = Result.REJECTED_CURRENT_BRANCH;
  482. }
  483. }
  484. try {
  485. return result = updateImpl(walk, new Store() {
  486. @Override
  487. Result execute(Result status) throws IOException {
  488. return doDelete(status);
  489. }
  490. });
  491. } catch (IOException x) {
  492. result = Result.IO_FAILURE;
  493. throw x;
  494. }
  495. }
  496. /**
  497. * Replace this reference with a symbolic reference to another reference.
  498. * <p>
  499. * This exact reference (not its traversed leaf) is replaced with a symbolic
  500. * reference to the requested name.
  501. *
  502. * @param target
  503. * name of the new target for this reference. The new target name
  504. * must be absolute, so it must begin with {@code refs/}.
  505. * @return {@link Result#NEW} or {@link Result#FORCED} on success.
  506. * @throws IOException
  507. */
  508. public Result link(String target) throws IOException {
  509. if (!target.startsWith(Constants.R_REFS))
  510. throw new IllegalArgumentException(MessageFormat.format(JGitText.get().illegalArgumentNotA, Constants.R_REFS));
  511. if (checkConflicting && getRefDatabase().isNameConflicting(getName()))
  512. return Result.LOCK_FAILURE;
  513. try {
  514. if (!tryLock(false))
  515. return Result.LOCK_FAILURE;
  516. final Ref old = getRefDatabase().getRef(getName());
  517. if (old != null && old.isSymbolic()) {
  518. final Ref dst = old.getTarget();
  519. if (target.equals(dst.getName()))
  520. return result = Result.NO_CHANGE;
  521. }
  522. if (old != null && old.getObjectId() != null)
  523. setOldObjectId(old.getObjectId());
  524. final Ref dst = getRefDatabase().getRef(target);
  525. if (dst != null && dst.getObjectId() != null)
  526. setNewObjectId(dst.getObjectId());
  527. return result = doLink(target);
  528. } catch (IOException x) {
  529. result = Result.IO_FAILURE;
  530. throw x;
  531. } finally {
  532. unlock();
  533. }
  534. }
  535. private Result updateImpl(final RevWalk walk, final Store store)
  536. throws IOException {
  537. RevObject newObj;
  538. RevObject oldObj;
  539. // don't make expensive conflict check if this is an existing Ref
  540. if (oldValue == null && checkConflicting && getRefDatabase().isNameConflicting(getName()))
  541. return Result.LOCK_FAILURE;
  542. try {
  543. if (!tryLock(true))
  544. return Result.LOCK_FAILURE;
  545. if (expValue != null) {
  546. final ObjectId o;
  547. o = oldValue != null ? oldValue : ObjectId.zeroId();
  548. if (!AnyObjectId.equals(expValue, o))
  549. return Result.LOCK_FAILURE;
  550. }
  551. if (oldValue == null)
  552. return store.execute(Result.NEW);
  553. newObj = safeParse(walk, newValue);
  554. oldObj = safeParse(walk, oldValue);
  555. if (newObj == oldObj && !detachingSymbolicRef)
  556. return store.execute(Result.NO_CHANGE);
  557. if (newObj instanceof RevCommit && oldObj instanceof RevCommit) {
  558. if (walk.isMergedInto((RevCommit) oldObj, (RevCommit) newObj))
  559. return store.execute(Result.FAST_FORWARD);
  560. }
  561. if (isForceUpdate())
  562. return store.execute(Result.FORCED);
  563. return Result.REJECTED;
  564. } finally {
  565. unlock();
  566. }
  567. }
  568. /**
  569. * Enable/disable the check for conflicting ref names. By default conflicts
  570. * are checked explicitly.
  571. *
  572. * @param check
  573. */
  574. public void setCheckConflicting(boolean check) {
  575. checkConflicting = check;
  576. }
  577. private static RevObject safeParse(final RevWalk rw, final AnyObjectId id)
  578. throws IOException {
  579. try {
  580. return id != null ? rw.parseAny(id) : null;
  581. } catch (MissingObjectException e) {
  582. // We can expect some objects to be missing, like if we are
  583. // trying to force a deletion of a branch and the object it
  584. // points to has been pruned from the database due to freak
  585. // corruption accidents (it happens with 'git new-work-dir').
  586. //
  587. return null;
  588. }
  589. }
  590. /**
  591. * Handle the abstraction of storing a ref update. This is because both
  592. * updating and deleting of a ref have merge testing in common.
  593. */
  594. private abstract class Store {
  595. abstract Result execute(Result status) throws IOException;
  596. }
  597. }