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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  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. import org.eclipse.jgit.transport.PushCertificate;
  53. import org.eclipse.jgit.util.References;
  54. /**
  55. * Creates, updates or deletes any reference.
  56. */
  57. public abstract class RefUpdate {
  58. /**
  59. * Status of an update request.
  60. * <p>
  61. * New values may be added to this enum in the future. Callers may assume that
  62. * unknown values are failures, and may generally treat them the same as
  63. * {@link #REJECTED_OTHER_REASON}.
  64. */
  65. public static enum Result {
  66. /** The ref update/delete has not been attempted by the caller. */
  67. NOT_ATTEMPTED,
  68. /**
  69. * The ref could not be locked for update/delete.
  70. * <p>
  71. * This is generally a transient failure and is usually caused by
  72. * another process trying to access the ref at the same time as this
  73. * process was trying to update it. It is possible a future operation
  74. * will be successful.
  75. */
  76. LOCK_FAILURE,
  77. /**
  78. * Same value already stored.
  79. * <p>
  80. * Both the old value and the new value are identical. No change was
  81. * necessary for an update. For delete the branch is removed.
  82. */
  83. NO_CHANGE,
  84. /**
  85. * The ref was created locally for an update, but ignored for delete.
  86. * <p>
  87. * The ref did not exist when the update started, but it was created
  88. * successfully with the new value.
  89. */
  90. NEW,
  91. /**
  92. * The ref had to be forcefully updated/deleted.
  93. * <p>
  94. * The ref already existed but its old value was not fully merged into
  95. * the new value. The configuration permitted a forced update to take
  96. * place, so ref now contains the new value. History associated with the
  97. * objects not merged may no longer be reachable.
  98. */
  99. FORCED,
  100. /**
  101. * The ref was updated/deleted in a fast-forward way.
  102. * <p>
  103. * The tracking ref already existed and its old value was fully merged
  104. * into the new value. No history was made unreachable.
  105. */
  106. FAST_FORWARD,
  107. /**
  108. * Not a fast-forward and not stored.
  109. * <p>
  110. * The tracking ref already existed but its old value was not fully
  111. * merged into the new value. The configuration did not allow a forced
  112. * update/delete to take place, so ref still contains the old value. No
  113. * previous history was lost.
  114. * <p>
  115. * <em>Note:</em> Despite the general name, this result only refers to the
  116. * non-fast-forward case. For more general errors, see {@link
  117. * #REJECTED_OTHER_REASON}.
  118. */
  119. REJECTED,
  120. /**
  121. * Rejected because trying to delete the current branch.
  122. * <p>
  123. * Has no meaning for update.
  124. */
  125. REJECTED_CURRENT_BRANCH,
  126. /**
  127. * The ref was probably not updated/deleted because of I/O error.
  128. * <p>
  129. * Unexpected I/O error occurred when writing new ref. Such error may
  130. * result in uncertain state, but most probably ref was not updated.
  131. * <p>
  132. * This kind of error doesn't include {@link #LOCK_FAILURE}, which is a
  133. * different case.
  134. */
  135. IO_FAILURE,
  136. /**
  137. * The ref was renamed from another name
  138. * <p>
  139. */
  140. RENAMED,
  141. /**
  142. * One or more objects aren't in the repository.
  143. * <p>
  144. * This is severe indication of either repository corruption on the
  145. * server side, or a bug in the client wherein the client did not supply
  146. * all required objects during the pack transfer.
  147. *
  148. * @since 4.9
  149. */
  150. REJECTED_MISSING_OBJECT,
  151. /**
  152. * Rejected for some other reason not covered by another enum value.
  153. *
  154. * @since 4.9
  155. */
  156. REJECTED_OTHER_REASON;
  157. }
  158. /** New value the caller wants this ref to have. */
  159. private ObjectId newValue;
  160. /** Does this specification ask for forced updated (rewind/reset)? */
  161. private boolean force;
  162. /** Identity to record action as within the reflog. */
  163. private PersonIdent refLogIdent;
  164. /** Message the caller wants included in the reflog. */
  165. private String refLogMessage;
  166. /** Should the Result value be appended to {@link #refLogMessage}. */
  167. private boolean refLogIncludeResult;
  168. /**
  169. * Should reflogs be written even if the configured default for this ref is
  170. * not to write it.
  171. */
  172. private boolean forceRefLog;
  173. /** Old value of the ref, obtained after we lock it. */
  174. private ObjectId oldValue;
  175. /** If non-null, the value {@link #oldValue} must have to continue. */
  176. private ObjectId expValue;
  177. /** Result of the update operation. */
  178. private Result result = Result.NOT_ATTEMPTED;
  179. /** Push certificate associated with this update. */
  180. private PushCertificate pushCert;
  181. private final Ref ref;
  182. /**
  183. * Is this RefUpdate detaching a symbolic ref?
  184. *
  185. * We need this info since this.ref will normally be peeled of in case of
  186. * detaching a symbolic ref (HEAD for example).
  187. *
  188. * Without this flag we cannot decide whether the ref has to be updated or
  189. * not in case when it was a symbolic ref and the newValue == oldValue.
  190. */
  191. private boolean detachingSymbolicRef;
  192. private boolean checkConflicting = true;
  193. /**
  194. * Construct a new update operation for the reference.
  195. * <p>
  196. * {@code ref.getObjectId()} will be used to seed {@link #getOldObjectId()},
  197. * which callers can use as part of their own update logic.
  198. *
  199. * @param ref
  200. * the reference that will be updated by this operation.
  201. */
  202. protected RefUpdate(Ref ref) {
  203. this.ref = ref;
  204. oldValue = ref.getObjectId();
  205. refLogMessage = ""; //$NON-NLS-1$
  206. }
  207. /**
  208. * Get the reference database this update modifies.
  209. *
  210. * @return the reference database this update modifies.
  211. */
  212. protected abstract RefDatabase getRefDatabase();
  213. /**
  214. * Get the repository storing the database's objects.
  215. *
  216. * @return the repository storing the database's objects.
  217. */
  218. protected abstract Repository getRepository();
  219. /**
  220. * Try to acquire the lock on the reference.
  221. * <p>
  222. * If the locking was successful the implementor must set the current
  223. * identity value by calling {@link #setOldObjectId(ObjectId)}.
  224. *
  225. * @param deref
  226. * true if the lock should be taken against the leaf level
  227. * reference; false if it should be taken exactly against the
  228. * current reference.
  229. * @return true if the lock was acquired and the reference is likely
  230. * protected from concurrent modification; false if it failed.
  231. * @throws java.io.IOException
  232. * the lock couldn't be taken due to an unexpected storage
  233. * failure, and not because of a concurrent update.
  234. */
  235. protected abstract boolean tryLock(boolean deref) throws IOException;
  236. /**
  237. * Releases the lock taken by {@link #tryLock} if it succeeded.
  238. */
  239. protected abstract void unlock();
  240. /**
  241. * Do update
  242. *
  243. * @param desiredResult
  244. * a {@link org.eclipse.jgit.lib.RefUpdate.Result} object.
  245. * @return {@code result}
  246. * @throws java.io.IOException
  247. */
  248. protected abstract Result doUpdate(Result desiredResult) throws IOException;
  249. /**
  250. * Do delete
  251. *
  252. * @param desiredResult
  253. * a {@link org.eclipse.jgit.lib.RefUpdate.Result} object.
  254. * @return {@code result}
  255. * @throws java.io.IOException
  256. */
  257. protected abstract Result doDelete(Result desiredResult) throws IOException;
  258. /**
  259. * Do link
  260. *
  261. * @param target
  262. * a {@link java.lang.String} object.
  263. * @return {@link org.eclipse.jgit.lib.RefUpdate.Result#NEW} on success.
  264. * @throws java.io.IOException
  265. */
  266. protected abstract Result doLink(String target) throws IOException;
  267. /**
  268. * Get the name of the ref this update will operate on.
  269. *
  270. * @return name of underlying ref.
  271. */
  272. public String getName() {
  273. return getRef().getName();
  274. }
  275. /**
  276. * Get the reference this update will create or modify.
  277. *
  278. * @return the reference this update will create or modify.
  279. */
  280. public Ref getRef() {
  281. return ref;
  282. }
  283. /**
  284. * Get the new value the ref will be (or was) updated to.
  285. *
  286. * @return new value. Null if the caller has not configured it.
  287. */
  288. public ObjectId getNewObjectId() {
  289. return newValue;
  290. }
  291. /**
  292. * Tells this RefUpdate that it is actually detaching a symbolic ref.
  293. */
  294. public void setDetachingSymbolicRef() {
  295. detachingSymbolicRef = true;
  296. }
  297. /**
  298. * Return whether this update is actually detaching a symbolic ref.
  299. *
  300. * @return true if detaching a symref.
  301. * @since 4.9
  302. */
  303. public boolean isDetachingSymbolicRef() {
  304. return detachingSymbolicRef;
  305. }
  306. /**
  307. * Set the new value the ref will update to.
  308. *
  309. * @param id
  310. * the new value.
  311. */
  312. public void setNewObjectId(AnyObjectId id) {
  313. newValue = id.copy();
  314. }
  315. /**
  316. * Get the expected value of the ref after the lock is taken, but before
  317. * update occurs.
  318. *
  319. * @return the expected value of the ref after the lock is taken, but before
  320. * update occurs. Null to avoid the compare and swap test. Use
  321. * {@link org.eclipse.jgit.lib.ObjectId#zeroId()} to indicate
  322. * expectation of a non-existant ref.
  323. */
  324. public ObjectId getExpectedOldObjectId() {
  325. return expValue;
  326. }
  327. /**
  328. * Set the expected value of the ref after the lock is taken, but before
  329. * update occurs.
  330. *
  331. * @param id
  332. * the expected value of the ref after the lock is taken, but
  333. * before update occurs. Null to avoid the compare and swap test.
  334. * Use {@link org.eclipse.jgit.lib.ObjectId#zeroId()} to indicate
  335. * expectation of a non-existant ref.
  336. */
  337. public void setExpectedOldObjectId(AnyObjectId id) {
  338. expValue = id != null ? id.toObjectId() : null;
  339. }
  340. /**
  341. * Check if this update wants to forcefully change the ref.
  342. *
  343. * @return true if this update should ignore merge tests.
  344. */
  345. public boolean isForceUpdate() {
  346. return force;
  347. }
  348. /**
  349. * Set if this update wants to forcefully change the ref.
  350. *
  351. * @param b
  352. * true if this update should ignore merge tests.
  353. */
  354. public void setForceUpdate(boolean b) {
  355. force = b;
  356. }
  357. /**
  358. * Get identity of the user making the change in the reflog.
  359. *
  360. * @return identity of the user making the change in the reflog.
  361. */
  362. public PersonIdent getRefLogIdent() {
  363. return refLogIdent;
  364. }
  365. /**
  366. * Set the identity of the user appearing in the reflog.
  367. * <p>
  368. * The timestamp portion of the identity is ignored. A new identity with the
  369. * current timestamp will be created automatically when the update occurs
  370. * and the log record is written.
  371. *
  372. * @param pi
  373. * identity of the user. If null the identity will be
  374. * automatically determined based on the repository
  375. * configuration.
  376. */
  377. public void setRefLogIdent(PersonIdent pi) {
  378. refLogIdent = pi;
  379. }
  380. /**
  381. * Get the message to include in the reflog.
  382. *
  383. * @return message the caller wants to include in the reflog; null if the
  384. * update should not be logged.
  385. */
  386. public String getRefLogMessage() {
  387. return refLogMessage;
  388. }
  389. /**
  390. * Whether the ref log message should show the result.
  391. *
  392. * @return {@code true} if the ref log message should show the result.
  393. */
  394. protected boolean isRefLogIncludingResult() {
  395. return refLogIncludeResult;
  396. }
  397. /**
  398. * Set the message to include in the reflog.
  399. * <p>
  400. * Repository implementations may limit which reflogs are written by default,
  401. * based on the project configuration. If a repo is not configured to write
  402. * logs for this ref by default, setting the message alone may have no effect.
  403. * To indicate that the repo should write logs for this update in spite of
  404. * configured defaults, use {@link #setForceRefLog(boolean)}.
  405. *
  406. * @param msg
  407. * the message to describe this change. It may be null if
  408. * appendStatus is null in order not to append to the reflog
  409. * @param appendStatus
  410. * true if the status of the ref change (fast-forward or
  411. * forced-update) should be appended to the user supplied
  412. * message.
  413. */
  414. public void setRefLogMessage(String msg, boolean appendStatus) {
  415. if (msg == null && !appendStatus)
  416. disableRefLog();
  417. else if (msg == null && appendStatus) {
  418. refLogMessage = ""; //$NON-NLS-1$
  419. refLogIncludeResult = true;
  420. } else {
  421. refLogMessage = msg;
  422. refLogIncludeResult = appendStatus;
  423. }
  424. }
  425. /**
  426. * Don't record this update in the ref's associated reflog.
  427. */
  428. public void disableRefLog() {
  429. refLogMessage = null;
  430. refLogIncludeResult = false;
  431. }
  432. /**
  433. * Force writing a reflog for the updated ref.
  434. *
  435. * @param force whether to force.
  436. * @since 4.9
  437. */
  438. public void setForceRefLog(boolean force) {
  439. forceRefLog = force;
  440. }
  441. /**
  442. * Check whether the reflog should be written regardless of repo defaults.
  443. *
  444. * @return whether force writing is enabled.
  445. * @since 4.9
  446. */
  447. protected boolean isForceRefLog() {
  448. return forceRefLog;
  449. }
  450. /**
  451. * The old value of the ref, prior to the update being attempted.
  452. * <p>
  453. * This value may differ before and after the update method. Initially it is
  454. * populated with the value of the ref before the lock is taken, but the old
  455. * value may change if someone else modified the ref between the time we
  456. * last read it and when the ref was locked for update.
  457. *
  458. * @return the value of the ref prior to the update being attempted; null if
  459. * the updated has not been attempted yet.
  460. */
  461. public ObjectId getOldObjectId() {
  462. return oldValue;
  463. }
  464. /**
  465. * Set the old value of the ref.
  466. *
  467. * @param old
  468. * the old value.
  469. */
  470. protected void setOldObjectId(ObjectId old) {
  471. oldValue = old;
  472. }
  473. /**
  474. * Set a push certificate associated with this update.
  475. * <p>
  476. * This usually includes a command to update this ref, but is not required to.
  477. *
  478. * @param cert
  479. * push certificate, may be null.
  480. * @since 4.1
  481. */
  482. public void setPushCertificate(PushCertificate cert) {
  483. pushCert = cert;
  484. }
  485. /**
  486. * Set the push certificate associated with this update.
  487. * <p>
  488. * This usually includes a command to update this ref, but is not required to.
  489. *
  490. * @return push certificate, may be null.
  491. * @since 4.1
  492. */
  493. protected PushCertificate getPushCertificate() {
  494. return pushCert;
  495. }
  496. /**
  497. * Get the status of this update.
  498. * <p>
  499. * The same value that was previously returned from an update method.
  500. *
  501. * @return the status of the update.
  502. */
  503. public Result getResult() {
  504. return result;
  505. }
  506. private void requireCanDoUpdate() {
  507. if (newValue == null)
  508. throw new IllegalStateException(JGitText.get().aNewObjectIdIsRequired);
  509. }
  510. /**
  511. * Force the ref to take the new value.
  512. * <p>
  513. * This is just a convenient helper for setting the force flag, and as such
  514. * the merge test is performed.
  515. *
  516. * @return the result status of the update.
  517. * @throws java.io.IOException
  518. * an unexpected IO error occurred while writing changes.
  519. */
  520. public Result forceUpdate() throws IOException {
  521. force = true;
  522. return update();
  523. }
  524. /**
  525. * Gracefully update the ref to the new value.
  526. * <p>
  527. * Merge test will be performed according to {@link #isForceUpdate()}.
  528. * <p>
  529. * This is the same as:
  530. *
  531. * <pre>
  532. * return update(new RevWalk(getRepository()));
  533. * </pre>
  534. *
  535. * @return the result status of the update.
  536. * @throws java.io.IOException
  537. * an unexpected IO error occurred while writing changes.
  538. */
  539. public Result update() throws IOException {
  540. try (RevWalk rw = new RevWalk(getRepository())) {
  541. rw.setRetainBody(false);
  542. return update(rw);
  543. }
  544. }
  545. /**
  546. * Gracefully update the ref to the new value.
  547. * <p>
  548. * Merge test will be performed according to {@link #isForceUpdate()}.
  549. *
  550. * @param walk
  551. * a RevWalk instance this update command can borrow to perform
  552. * the merge test. The walk will be reset to perform the test.
  553. * @return the result status of the update.
  554. * @throws java.io.IOException
  555. * an unexpected IO error occurred while writing changes.
  556. */
  557. public Result update(RevWalk walk) throws IOException {
  558. requireCanDoUpdate();
  559. try {
  560. return result = updateImpl(walk, new Store() {
  561. @Override
  562. Result execute(Result status) throws IOException {
  563. if (status == Result.NO_CHANGE)
  564. return status;
  565. return doUpdate(status);
  566. }
  567. });
  568. } catch (IOException x) {
  569. result = Result.IO_FAILURE;
  570. throw x;
  571. }
  572. }
  573. /**
  574. * Delete the ref.
  575. * <p>
  576. * This is the same as:
  577. *
  578. * <pre>
  579. * return delete(new RevWalk(getRepository()));
  580. * </pre>
  581. *
  582. * @return the result status of the delete.
  583. * @throws java.io.IOException
  584. */
  585. public Result delete() throws IOException {
  586. try (RevWalk rw = new RevWalk(getRepository())) {
  587. rw.setRetainBody(false);
  588. return delete(rw);
  589. }
  590. }
  591. /**
  592. * Delete the ref.
  593. *
  594. * @param walk
  595. * a RevWalk instance this delete command can borrow to perform
  596. * the merge test. The walk will be reset to perform the test.
  597. * @return the result status of the delete.
  598. * @throws java.io.IOException
  599. */
  600. public Result delete(RevWalk walk) throws IOException {
  601. final String myName = detachingSymbolicRef
  602. ? getRef().getName()
  603. : getRef().getLeaf().getName();
  604. if (myName.startsWith(Constants.R_HEADS) && !getRepository().isBare()) {
  605. // Don't allow the currently checked out branch to be deleted.
  606. Ref head = getRefDatabase().exactRef(Constants.HEAD);
  607. while (head != null && head.isSymbolic()) {
  608. head = head.getTarget();
  609. if (myName.equals(head.getName()))
  610. return result = Result.REJECTED_CURRENT_BRANCH;
  611. }
  612. }
  613. try {
  614. return result = updateImpl(walk, new Store() {
  615. @Override
  616. Result execute(Result status) throws IOException {
  617. return doDelete(status);
  618. }
  619. });
  620. } catch (IOException x) {
  621. result = Result.IO_FAILURE;
  622. throw x;
  623. }
  624. }
  625. /**
  626. * Replace this reference with a symbolic reference to another reference.
  627. * <p>
  628. * This exact reference (not its traversed leaf) is replaced with a symbolic
  629. * reference to the requested name.
  630. *
  631. * @param target
  632. * name of the new target for this reference. The new target name
  633. * must be absolute, so it must begin with {@code refs/}.
  634. * @return {@link org.eclipse.jgit.lib.RefUpdate.Result#NEW} or
  635. * {@link org.eclipse.jgit.lib.RefUpdate.Result#FORCED} on success.
  636. * @throws java.io.IOException
  637. */
  638. public Result link(String target) throws IOException {
  639. if (!target.startsWith(Constants.R_REFS))
  640. throw new IllegalArgumentException(MessageFormat.format(JGitText.get().illegalArgumentNotA, Constants.R_REFS));
  641. if (checkConflicting && getRefDatabase().isNameConflicting(getName()))
  642. return Result.LOCK_FAILURE;
  643. try {
  644. if (!tryLock(false))
  645. return Result.LOCK_FAILURE;
  646. final Ref old = getRefDatabase().exactRef(getName());
  647. if (old != null && old.isSymbolic()) {
  648. final Ref dst = old.getTarget();
  649. if (target.equals(dst.getName()))
  650. return result = Result.NO_CHANGE;
  651. }
  652. if (old != null && old.getObjectId() != null)
  653. setOldObjectId(old.getObjectId());
  654. final Ref dst = getRefDatabase().exactRef(target);
  655. if (dst != null && dst.getObjectId() != null)
  656. setNewObjectId(dst.getObjectId());
  657. return result = doLink(target);
  658. } catch (IOException x) {
  659. result = Result.IO_FAILURE;
  660. throw x;
  661. } finally {
  662. unlock();
  663. }
  664. }
  665. private Result updateImpl(RevWalk walk, Store store)
  666. throws IOException {
  667. RevObject newObj;
  668. RevObject oldObj;
  669. // don't make expensive conflict check if this is an existing Ref
  670. if (oldValue == null && checkConflicting
  671. && getRefDatabase().isNameConflicting(getName())) {
  672. return Result.LOCK_FAILURE;
  673. }
  674. try {
  675. // If we're detaching a symbolic reference, we should update the reference
  676. // itself. Otherwise, we will update the leaf reference, which should be
  677. // an ObjectIdRef.
  678. if (!tryLock(!detachingSymbolicRef)) {
  679. return Result.LOCK_FAILURE;
  680. }
  681. if (expValue != null) {
  682. final ObjectId o;
  683. o = oldValue != null ? oldValue : ObjectId.zeroId();
  684. if (!AnyObjectId.isEqual(expValue, o)) {
  685. return Result.LOCK_FAILURE;
  686. }
  687. }
  688. try {
  689. newObj = safeParseNew(walk, newValue);
  690. } catch (MissingObjectException e) {
  691. return Result.REJECTED_MISSING_OBJECT;
  692. }
  693. if (oldValue == null) {
  694. return store.execute(Result.NEW);
  695. }
  696. oldObj = safeParseOld(walk, oldValue);
  697. if (References.isSameObject(newObj, oldObj)
  698. && !detachingSymbolicRef) {
  699. return store.execute(Result.NO_CHANGE);
  700. }
  701. if (isForceUpdate()) {
  702. return store.execute(Result.FORCED);
  703. }
  704. if (newObj instanceof RevCommit && oldObj instanceof RevCommit) {
  705. if (walk.isMergedInto((RevCommit) oldObj, (RevCommit) newObj)) {
  706. return store.execute(Result.FAST_FORWARD);
  707. }
  708. }
  709. return Result.REJECTED;
  710. } finally {
  711. unlock();
  712. }
  713. }
  714. /**
  715. * Enable/disable the check for conflicting ref names. By default conflicts
  716. * are checked explicitly.
  717. *
  718. * @param check
  719. * whether to enable the check for conflicting ref names.
  720. * @since 3.0
  721. */
  722. public void setCheckConflicting(boolean check) {
  723. checkConflicting = check;
  724. }
  725. private static RevObject safeParseNew(RevWalk rw, AnyObjectId newId)
  726. throws IOException {
  727. if (newId == null || ObjectId.zeroId().equals(newId)) {
  728. return null;
  729. }
  730. return rw.parseAny(newId);
  731. }
  732. private static RevObject safeParseOld(RevWalk rw, AnyObjectId oldId)
  733. throws IOException {
  734. try {
  735. return oldId != null ? rw.parseAny(oldId) : null;
  736. } catch (MissingObjectException e) {
  737. // We can expect some old objects to be missing, like if we are trying to
  738. // force a deletion of a branch and the object it points to has been
  739. // pruned from the database due to freak corruption accidents (it happens
  740. // with 'git new-work-dir').
  741. return null;
  742. }
  743. }
  744. /**
  745. * Handle the abstraction of storing a ref update. This is because both
  746. * updating and deleting of a ref have merge testing in common.
  747. */
  748. private static abstract class Store {
  749. abstract Result execute(Result status) throws IOException;
  750. }
  751. }