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

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