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

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