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

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