Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

DirCacheCheckout.java 44KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  1. /*
  2. * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com>
  3. * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  4. * Copyright (C) 2008, Roger C. Soares <rogersoares@intelinet.com.br>
  5. * Copyright (C) 2006, Shawn O. Pearce <spearce@spearce.org>
  6. * Copyright (C) 2010, Chrisian Halstrick <christian.halstrick@sap.com> and
  7. * other copyright owners as documented in the project's IP log.
  8. *
  9. * This program and the accompanying materials are made available under the
  10. * terms of the Eclipse Distribution License v1.0 which accompanies this
  11. * distribution, is reproduced below, and is available at
  12. * http://www.eclipse.org/org/documents/edl-v10.php
  13. *
  14. * All rights reserved.
  15. *
  16. * Redistribution and use in source and binary forms, with or without
  17. * modification, are permitted provided that the following conditions are met:
  18. *
  19. * - Redistributions of source code must retain the above copyright notice, this
  20. * list of conditions and the following disclaimer.
  21. *
  22. * - Redistributions in binary form must reproduce the above copyright notice,
  23. * this list of conditions and the following disclaimer in the documentation
  24. * and/or other materials provided with the distribution.
  25. *
  26. * - Neither the name of the Eclipse Foundation, Inc. nor the names of its
  27. * contributors may be used to endorse or promote products derived from this
  28. * software without specific prior written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  31. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  32. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  34. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  35. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  36. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  37. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  38. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  39. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  40. * POSSIBILITY OF SUCH DAMAGE.
  41. */
  42. package org.eclipse.jgit.dircache;
  43. import java.io.File;
  44. import java.io.FileOutputStream;
  45. import java.io.IOException;
  46. import java.io.OutputStream;
  47. import java.text.MessageFormat;
  48. import java.util.ArrayList;
  49. import java.util.HashMap;
  50. import java.util.List;
  51. import java.util.Map;
  52. import org.eclipse.jgit.errors.CheckoutConflictException;
  53. import org.eclipse.jgit.errors.CorruptObjectException;
  54. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  55. import org.eclipse.jgit.errors.IndexWriteException;
  56. import org.eclipse.jgit.errors.MissingObjectException;
  57. import org.eclipse.jgit.internal.JGitText;
  58. import org.eclipse.jgit.lib.CoreConfig.AutoCRLF;
  59. import org.eclipse.jgit.lib.CoreConfig.SymLinks;
  60. import org.eclipse.jgit.lib.FileMode;
  61. import org.eclipse.jgit.lib.ObjectChecker;
  62. import org.eclipse.jgit.lib.ObjectId;
  63. import org.eclipse.jgit.lib.ObjectLoader;
  64. import org.eclipse.jgit.lib.ObjectReader;
  65. import org.eclipse.jgit.lib.Repository;
  66. import org.eclipse.jgit.treewalk.AbstractTreeIterator;
  67. import org.eclipse.jgit.treewalk.CanonicalTreeParser;
  68. import org.eclipse.jgit.treewalk.EmptyTreeIterator;
  69. import org.eclipse.jgit.treewalk.FileTreeIterator;
  70. import org.eclipse.jgit.treewalk.NameConflictTreeWalk;
  71. import org.eclipse.jgit.treewalk.TreeWalk;
  72. import org.eclipse.jgit.treewalk.WorkingTreeIterator;
  73. import org.eclipse.jgit.treewalk.WorkingTreeOptions;
  74. import org.eclipse.jgit.treewalk.filter.PathFilter;
  75. import org.eclipse.jgit.util.FS;
  76. import org.eclipse.jgit.util.FileUtils;
  77. import org.eclipse.jgit.util.RawParseUtils;
  78. import org.eclipse.jgit.util.SystemReader;
  79. import org.eclipse.jgit.util.io.AutoCRLFOutputStream;
  80. /**
  81. * This class handles checking out one or two trees merging with the index.
  82. */
  83. public class DirCacheCheckout {
  84. private Repository repo;
  85. private HashMap<String, ObjectId> updated = new HashMap<String, ObjectId>();
  86. private ArrayList<String> conflicts = new ArrayList<String>();
  87. private ArrayList<String> removed = new ArrayList<String>();
  88. private ObjectId mergeCommitTree;
  89. private DirCache dc;
  90. private DirCacheBuilder builder;
  91. private NameConflictTreeWalk walk;
  92. private ObjectId headCommitTree;
  93. private WorkingTreeIterator workingTree;
  94. private boolean failOnConflict = true;
  95. private ArrayList<String> toBeDeleted = new ArrayList<String>();
  96. private boolean emptyDirCache;
  97. /**
  98. * @return a list of updated paths and objectIds
  99. */
  100. public Map<String, ObjectId> getUpdated() {
  101. return updated;
  102. }
  103. /**
  104. * @return a list of conflicts created by this checkout
  105. */
  106. public List<String> getConflicts() {
  107. return conflicts;
  108. }
  109. /**
  110. * @return a list of paths (relative to the start of the working tree) of
  111. * files which couldn't be deleted during last call to
  112. * {@link #checkout()} . {@link #checkout()} detected that these
  113. * files should be deleted but the deletion in the filesystem failed
  114. * (e.g. because a file was locked). To have a consistent state of
  115. * the working tree these files have to be deleted by the callers of
  116. * {@link DirCacheCheckout}.
  117. */
  118. public List<String> getToBeDeleted() {
  119. return toBeDeleted;
  120. }
  121. /**
  122. * @return a list of all files removed by this checkout
  123. */
  124. public List<String> getRemoved() {
  125. return removed;
  126. }
  127. /**
  128. * Constructs a DirCacheCeckout for merging and checking out two trees (HEAD
  129. * and mergeCommitTree) and the index.
  130. *
  131. * @param repo
  132. * the repository in which we do the checkout
  133. * @param headCommitTree
  134. * the id of the tree of the head commit
  135. * @param dc
  136. * the (already locked) Dircache for this repo
  137. * @param mergeCommitTree
  138. * the id of the tree we want to fast-forward to
  139. * @param workingTree
  140. * an iterator over the repositories Working Tree
  141. * @throws IOException
  142. */
  143. public DirCacheCheckout(Repository repo, ObjectId headCommitTree, DirCache dc,
  144. ObjectId mergeCommitTree, WorkingTreeIterator workingTree)
  145. throws IOException {
  146. this.repo = repo;
  147. this.dc = dc;
  148. this.headCommitTree = headCommitTree;
  149. this.mergeCommitTree = mergeCommitTree;
  150. this.workingTree = workingTree;
  151. this.emptyDirCache = (dc == null) || (dc.getEntryCount() == 0);
  152. }
  153. /**
  154. * Constructs a DirCacheCeckout for merging and checking out two trees (HEAD
  155. * and mergeCommitTree) and the index. As iterator over the working tree
  156. * this constructor creates a standard {@link FileTreeIterator}
  157. *
  158. * @param repo
  159. * the repository in which we do the checkout
  160. * @param headCommitTree
  161. * the id of the tree of the head commit
  162. * @param dc
  163. * the (already locked) Dircache for this repo
  164. * @param mergeCommitTree
  165. * the id of the tree we want to fast-forward to
  166. * @throws IOException
  167. */
  168. public DirCacheCheckout(Repository repo, ObjectId headCommitTree,
  169. DirCache dc, ObjectId mergeCommitTree) throws IOException {
  170. this(repo, headCommitTree, dc, mergeCommitTree, new FileTreeIterator(repo));
  171. }
  172. /**
  173. * Constructs a DirCacheCeckout for checking out one tree, merging with the
  174. * index.
  175. *
  176. * @param repo
  177. * the repository in which we do the checkout
  178. * @param dc
  179. * the (already locked) Dircache for this repo
  180. * @param mergeCommitTree
  181. * the id of the tree we want to fast-forward to
  182. * @param workingTree
  183. * an iterator over the repositories Working Tree
  184. * @throws IOException
  185. */
  186. public DirCacheCheckout(Repository repo, DirCache dc,
  187. ObjectId mergeCommitTree, WorkingTreeIterator workingTree)
  188. throws IOException {
  189. this(repo, null, dc, mergeCommitTree, workingTree);
  190. }
  191. /**
  192. * Constructs a DirCacheCeckout for checking out one tree, merging with the
  193. * index. As iterator over the working tree this constructor creates a
  194. * standard {@link FileTreeIterator}
  195. *
  196. * @param repo
  197. * the repository in which we do the checkout
  198. * @param dc
  199. * the (already locked) Dircache for this repo
  200. * @param mergeCommitTree
  201. * the id of the tree of the
  202. * @throws IOException
  203. */
  204. public DirCacheCheckout(Repository repo, DirCache dc,
  205. ObjectId mergeCommitTree) throws IOException {
  206. this(repo, null, dc, mergeCommitTree, new FileTreeIterator(repo));
  207. }
  208. /**
  209. * Scan head, index and merge tree. Used during normal checkout or merge
  210. * operations.
  211. *
  212. * @throws CorruptObjectException
  213. * @throws IOException
  214. */
  215. public void preScanTwoTrees() throws CorruptObjectException, IOException {
  216. removed.clear();
  217. updated.clear();
  218. conflicts.clear();
  219. walk = new NameConflictTreeWalk(repo);
  220. builder = dc.builder();
  221. addTree(walk, headCommitTree);
  222. addTree(walk, mergeCommitTree);
  223. walk.addTree(new DirCacheBuildIterator(builder));
  224. walk.addTree(workingTree);
  225. while (walk.next()) {
  226. processEntry(walk.getTree(0, CanonicalTreeParser.class),
  227. walk.getTree(1, CanonicalTreeParser.class),
  228. walk.getTree(2, DirCacheBuildIterator.class),
  229. walk.getTree(3, WorkingTreeIterator.class));
  230. if (walk.isSubtree())
  231. walk.enterSubtree();
  232. }
  233. }
  234. private void addTree(TreeWalk tw, ObjectId id) throws MissingObjectException, IncorrectObjectTypeException, IOException {
  235. if (id == null)
  236. tw.addTree(new EmptyTreeIterator());
  237. else
  238. tw.addTree(id);
  239. }
  240. /**
  241. * Scan index and merge tree (no HEAD). Used e.g. for initial checkout when
  242. * there is no head yet.
  243. *
  244. * @throws MissingObjectException
  245. * @throws IncorrectObjectTypeException
  246. * @throws CorruptObjectException
  247. * @throws IOException
  248. */
  249. public void prescanOneTree()
  250. throws MissingObjectException, IncorrectObjectTypeException,
  251. CorruptObjectException, IOException {
  252. removed.clear();
  253. updated.clear();
  254. conflicts.clear();
  255. builder = dc.builder();
  256. walk = new NameConflictTreeWalk(repo);
  257. addTree(walk, mergeCommitTree);
  258. walk.addTree(new DirCacheBuildIterator(builder));
  259. walk.addTree(workingTree);
  260. while (walk.next()) {
  261. processEntry(walk.getTree(0, CanonicalTreeParser.class),
  262. walk.getTree(1, DirCacheBuildIterator.class),
  263. walk.getTree(2, WorkingTreeIterator.class));
  264. if (walk.isSubtree())
  265. walk.enterSubtree();
  266. }
  267. conflicts.removeAll(removed);
  268. }
  269. /**
  270. * Processing an entry in the context of {@link #prescanOneTree()} when only
  271. * one tree is given
  272. *
  273. * @param m the tree to merge
  274. * @param i the index
  275. * @param f the working tree
  276. * @throws IOException
  277. */
  278. void processEntry(CanonicalTreeParser m, DirCacheBuildIterator i,
  279. WorkingTreeIterator f) throws IOException {
  280. if (m != null) {
  281. checkValidPath(m);
  282. // There is an entry in the merge commit. Means: we want to update
  283. // what's currently in the index and working-tree to that one
  284. if (i == null) {
  285. // The index entry is missing
  286. if (f != null && !FileMode.TREE.equals(f.getEntryFileMode())
  287. && !f.isEntryIgnored()) {
  288. // don't overwrite an untracked and not ignored file
  289. conflicts.add(walk.getPathString());
  290. } else
  291. update(m.getEntryPathString(), m.getEntryObjectId(),
  292. m.getEntryFileMode());
  293. } else if (f == null || !m.idEqual(i)) {
  294. // The working tree file is missing or the merge content differs
  295. // from index content
  296. update(m.getEntryPathString(), m.getEntryObjectId(),
  297. m.getEntryFileMode());
  298. } else if (i.getDirCacheEntry() != null) {
  299. // The index contains a file (and not a folder)
  300. if (f.isModified(i.getDirCacheEntry(), true,
  301. this.walk.getObjectReader())
  302. || i.getDirCacheEntry().getStage() != 0)
  303. // The working tree file is dirty or the index contains a
  304. // conflict
  305. update(m.getEntryPathString(), m.getEntryObjectId(),
  306. m.getEntryFileMode());
  307. else {
  308. // update the timestamp of the index with the one from the
  309. // file if not set, as we are sure to be in sync here.
  310. DirCacheEntry entry = i.getDirCacheEntry();
  311. if (entry.getLastModified() == 0)
  312. entry.setLastModified(f.getEntryLastModified());
  313. keep(entry);
  314. }
  315. } else
  316. // The index contains a folder
  317. keep(i.getDirCacheEntry());
  318. } else {
  319. // There is no entry in the merge commit. Means: we want to delete
  320. // what's currently in the index and working tree
  321. if (f != null) {
  322. // There is a file/folder for that path in the working tree
  323. if (walk.isDirectoryFileConflict()) {
  324. conflicts.add(walk.getPathString());
  325. } else {
  326. // No file/folder conflict exists. All entries are files or
  327. // all entries are folders
  328. if (i != null) {
  329. // ... and the working tree contained a file or folder
  330. // -> add it to the removed set and remove it from
  331. // conflicts set
  332. remove(i.getEntryPathString());
  333. conflicts.remove(i.getEntryPathString());
  334. } else {
  335. // untracked file, neither contained in tree to merge
  336. // nor in index
  337. }
  338. }
  339. } else {
  340. // There is no file/folder for that path in the working tree,
  341. // nor in the merge head.
  342. // The only entry we have is the index entry. Like the case
  343. // where there is a file with the same name, remove it,
  344. }
  345. }
  346. }
  347. /**
  348. * Execute this checkout
  349. *
  350. * @return <code>false</code> if this method could not delete all the files
  351. * which should be deleted (e.g. because of of the files was
  352. * locked). In this case {@link #getToBeDeleted()} lists the files
  353. * which should be tried to be deleted outside of this method.
  354. * Although <code>false</code> is returned the checkout was
  355. * successful and the working tree was updated for all other files.
  356. * <code>true</code> is returned when no such problem occurred
  357. *
  358. * @throws IOException
  359. */
  360. public boolean checkout() throws IOException {
  361. try {
  362. return doCheckout();
  363. } finally {
  364. dc.unlock();
  365. }
  366. }
  367. private boolean doCheckout() throws CorruptObjectException, IOException,
  368. MissingObjectException, IncorrectObjectTypeException,
  369. CheckoutConflictException, IndexWriteException {
  370. toBeDeleted.clear();
  371. ObjectReader objectReader = repo.getObjectDatabase().newReader();
  372. try {
  373. if (headCommitTree != null)
  374. preScanTwoTrees();
  375. else
  376. prescanOneTree();
  377. if (!conflicts.isEmpty()) {
  378. if (failOnConflict)
  379. throw new CheckoutConflictException(conflicts.toArray(new String[conflicts.size()]));
  380. else
  381. cleanUpConflicts();
  382. }
  383. // update our index
  384. builder.finish();
  385. File file = null;
  386. String last = null;
  387. // when deleting files process them in the opposite order as they have
  388. // been reported. This ensures the files are deleted before we delete
  389. // their parent folders
  390. for (int i = removed.size() - 1; i >= 0; i--) {
  391. String r = removed.get(i);
  392. file = new File(repo.getWorkTree(), r);
  393. if (!file.delete() && repo.getFS().exists(file)) {
  394. // The list of stuff to delete comes from the index
  395. // which will only contain a directory if it is
  396. // a submodule, in which case we shall not attempt
  397. // to delete it. A submodule is not empty, so it
  398. // is safe to check this after a failed delete.
  399. if (!repo.getFS().isDirectory(file))
  400. toBeDeleted.add(r);
  401. } else {
  402. if (last != null && !isSamePrefix(r, last))
  403. removeEmptyParents(new File(repo.getWorkTree(), last));
  404. last = r;
  405. }
  406. }
  407. if (file != null)
  408. removeEmptyParents(file);
  409. for (String path : updated.keySet()) {
  410. DirCacheEntry entry = dc.getEntry(path);
  411. if (!FileMode.GITLINK.equals(entry.getRawMode()))
  412. checkoutEntry(repo, entry, objectReader);
  413. }
  414. // commit the index builder - a new index is persisted
  415. if (!builder.commit())
  416. throw new IndexWriteException();
  417. } finally {
  418. objectReader.release();
  419. }
  420. return toBeDeleted.size() == 0;
  421. }
  422. private static boolean isSamePrefix(String a, String b) {
  423. int as = a.lastIndexOf('/');
  424. int bs = b.lastIndexOf('/');
  425. return a.substring(0, as + 1).equals(b.substring(0, bs + 1));
  426. }
  427. private void removeEmptyParents(File f) {
  428. File parentFile = f.getParentFile();
  429. while (parentFile != null && !parentFile.equals(repo.getWorkTree())) {
  430. if (!parentFile.delete())
  431. break;
  432. parentFile = parentFile.getParentFile();
  433. }
  434. }
  435. /**
  436. * Compares whether two pairs of ObjectId and FileMode are equal.
  437. *
  438. * @param id1
  439. * @param mode1
  440. * @param id2
  441. * @param mode2
  442. * @return <code>true</code> if FileModes and ObjectIds are equal.
  443. * <code>false</code> otherwise
  444. */
  445. private boolean equalIdAndMode(ObjectId id1, FileMode mode1, ObjectId id2,
  446. FileMode mode2) {
  447. if (!mode1.equals(mode2))
  448. return false;
  449. return id1 != null ? id1.equals(id2) : id2 == null;
  450. }
  451. /**
  452. * Here the main work is done. This method is called for each existing path
  453. * in head, index and merge. This method decides what to do with the
  454. * corresponding index entry: keep it, update it, remove it or mark a
  455. * conflict.
  456. *
  457. * @param h
  458. * the entry for the head
  459. * @param m
  460. * the entry for the merge
  461. * @param i
  462. * the entry for the index
  463. * @param f
  464. * the file in the working tree
  465. * @throws IOException
  466. */
  467. void processEntry(CanonicalTreeParser h, CanonicalTreeParser m,
  468. DirCacheBuildIterator i, WorkingTreeIterator f) throws IOException {
  469. DirCacheEntry dce = i != null ? i.getDirCacheEntry() : null;
  470. String name = walk.getPathString();
  471. if (m != null)
  472. checkValidPath(m);
  473. if (i == null && m == null && h == null) {
  474. // File/Directory conflict case #20
  475. if (walk.isDirectoryFileConflict())
  476. // TODO: check whether it is always correct to report a conflict here
  477. conflict(name, null, null, null);
  478. // file only exists in working tree -> ignore it
  479. return;
  480. }
  481. ObjectId iId = (i == null ? null : i.getEntryObjectId());
  482. ObjectId mId = (m == null ? null : m.getEntryObjectId());
  483. ObjectId hId = (h == null ? null : h.getEntryObjectId());
  484. FileMode iMode = (i == null ? null : i.getEntryFileMode());
  485. FileMode mMode = (m == null ? null : m.getEntryFileMode());
  486. FileMode hMode = (h == null ? null : h.getEntryFileMode());
  487. /**
  488. * <pre>
  489. * File/Directory conflicts:
  490. * the following table from ReadTreeTest tells what to do in case of directory/file
  491. * conflicts. I give comments here
  492. *
  493. * H I M Clean H==M H==I I==M Result
  494. * ------------------------------------------------------------------
  495. * 1 D D F Y N Y N Update
  496. * 2 D D F N N Y N Conflict
  497. * 3 D F D Y N N Keep
  498. * 4 D F D N N N Conflict
  499. * 5 D F F Y N N Y Keep
  500. * 5b D F F Y N N N Conflict
  501. * 6 D F F N N N Y Keep
  502. * 6b D F F N N N N Conflict
  503. * 7 F D F Y Y N N Update
  504. * 8 F D F N Y N N Conflict
  505. * 9 F D F N N N Conflict
  506. * 10 F D D N N Y Keep
  507. * 11 F D D N N N Conflict
  508. * 12 F F D Y N Y N Update
  509. * 13 F F D N N Y N Conflict
  510. * 14 F F D N N N Conflict
  511. * 15 0 F D N N N Conflict
  512. * 16 0 D F Y N N N Update
  513. * 17 0 D F N N N Conflict
  514. * 18 F 0 D Update
  515. * 19 D 0 F Update
  516. * 20 0 0 F N (worktree=dir) Conflict
  517. * </pre>
  518. */
  519. // The information whether head,index,merge iterators are currently
  520. // pointing to file/folder/non-existing is encoded into this variable.
  521. //
  522. // To decode write down ffMask in hexadecimal form. The last digit
  523. // represents the state for the merge iterator, the second last the
  524. // state for the index iterator and the third last represents the state
  525. // for the head iterator. The hexadecimal constant "F" stands for
  526. // "file", a "D" stands for "directory" (tree), and a "0" stands for
  527. // non-existing. Symbolic links and git links are treated as File here.
  528. //
  529. // Examples:
  530. // ffMask == 0xFFD -> Head=File, Index=File, Merge=Tree
  531. // ffMask == 0xDD0 -> Head=Tree, Index=Tree, Merge=Non-Existing
  532. int ffMask = 0;
  533. if (h != null)
  534. ffMask = FileMode.TREE.equals(hMode) ? 0xD00 : 0xF00;
  535. if (i != null)
  536. ffMask |= FileMode.TREE.equals(iMode) ? 0x0D0 : 0x0F0;
  537. if (m != null)
  538. ffMask |= FileMode.TREE.equals(mMode) ? 0x00D : 0x00F;
  539. // Check whether we have a possible file/folder conflict. Therefore we
  540. // need a least one file and one folder.
  541. if (((ffMask & 0x222) != 0x000)
  542. && (((ffMask & 0x00F) == 0x00D) || ((ffMask & 0x0F0) == 0x0D0) || ((ffMask & 0xF00) == 0xD00))) {
  543. // There are 3*3*3=27 possible combinations of file/folder
  544. // conflicts. Some of them are not-relevant because
  545. // they represent no conflict, e.g. 0xFFF, 0xDDD, ... The following
  546. // switch processes all relevant cases.
  547. switch (ffMask) {
  548. case 0xDDF: // 1 2
  549. if (f != null && isModifiedSubtree_IndexWorkingtree(name)) {
  550. conflict(name, dce, h, m); // 1
  551. } else {
  552. update(name, mId, mMode); // 2
  553. }
  554. break;
  555. case 0xDFD: // 3 4
  556. keep(dce);
  557. break;
  558. case 0xF0D: // 18
  559. remove(name);
  560. break;
  561. case 0xDFF: // 5 5b 6 6b
  562. if (equalIdAndMode(iId, iMode, mId, mMode))
  563. keep(dce); // 5 6
  564. else
  565. conflict(name, dce, h, m); // 5b 6b
  566. break;
  567. case 0xFDD: // 10 11
  568. // TODO: make use of tree extension as soon as available in jgit
  569. // we would like to do something like
  570. // if (!equalIdAndMode(iId, iMode, mId, mMode)
  571. // conflict(name, i.getDirCacheEntry(), h, m);
  572. // But since we don't know the id of a tree in the index we do
  573. // nothing here and wait that conflicts between index and merge
  574. // are found later
  575. break;
  576. case 0xD0F: // 19
  577. update(name, mId, mMode);
  578. break;
  579. case 0xDF0: // conflict without a rule
  580. case 0x0FD: // 15
  581. conflict(name, dce, h, m);
  582. break;
  583. case 0xFDF: // 7 8 9
  584. if (equalIdAndMode(hId, hMode, mId, mMode)) {
  585. if (isModifiedSubtree_IndexWorkingtree(name))
  586. conflict(name, dce, h, m); // 8
  587. else
  588. update(name, mId, mMode); // 7
  589. } else
  590. conflict(name, dce, h, m); // 9
  591. break;
  592. case 0xFD0: // keep without a rule
  593. keep(dce);
  594. break;
  595. case 0xFFD: // 12 13 14
  596. if (equalIdAndMode(hId, hMode, iId, iMode))
  597. if (f != null
  598. && f.isModified(dce, true,
  599. this.walk.getObjectReader()))
  600. conflict(name, dce, h, m); // 13
  601. else
  602. remove(name); // 12
  603. else
  604. conflict(name, dce, h, m); // 14
  605. break;
  606. case 0x0DF: // 16 17
  607. if (!isModifiedSubtree_IndexWorkingtree(name))
  608. update(name, mId, mMode);
  609. else
  610. conflict(name, dce, h, m);
  611. break;
  612. default:
  613. keep(dce);
  614. }
  615. return;
  616. }
  617. // if we have no file at all then there is nothing to do
  618. if ((ffMask & 0x222) == 0
  619. && (f == null || FileMode.TREE.equals(f.getEntryFileMode())))
  620. return;
  621. if ((ffMask == 0x00F) && f != null && FileMode.TREE.equals(f.getEntryFileMode())) {
  622. // File/Directory conflict case #20
  623. conflict(name, null, h, m);
  624. return;
  625. }
  626. if (i == null) {
  627. // Nothing in Index
  628. // At least one of Head, Index, Merge is not empty
  629. // make sure not to overwrite untracked files
  630. if (f != null && !f.isEntryIgnored()) {
  631. // A submodule is not a file. We should ignore it
  632. if (!FileMode.GITLINK.equals(mMode)) {
  633. // a dirty worktree: the index is empty but we have a
  634. // workingtree-file
  635. if (mId == null
  636. || !equalIdAndMode(mId, mMode,
  637. f.getEntryObjectId(), f.getEntryFileMode())) {
  638. conflict(name, null, h, m);
  639. return;
  640. }
  641. }
  642. }
  643. /**
  644. * <pre>
  645. * I (index) H M H==M Result
  646. * -------------------------------------------
  647. * 0 nothing nothing nothing (does not happen)
  648. * 1 nothing nothing exists use M
  649. * 2 nothing exists nothing remove path from index
  650. * 3 nothing exists exists yes keep index if not in initial checkout
  651. * , otherwise use M
  652. * nothing exists exists no fail
  653. * </pre>
  654. */
  655. if (h == null)
  656. // Nothing in Head
  657. // Nothing in Index
  658. // At least one of Head, Index, Merge is not empty
  659. // -> only Merge contains something for this path. Use it!
  660. // Potentially update the file
  661. update(name, mId, mMode); // 1
  662. else if (m == null)
  663. // Nothing in Merge
  664. // Something in Head
  665. // Nothing in Index
  666. // -> only Head contains something for this path and it should
  667. // be deleted. Potentially removes the file!
  668. remove(name); // 2
  669. else { // 3
  670. // Something in Merge
  671. // Something in Head
  672. // Nothing in Index
  673. // -> Head and Merge contain something (maybe not the same) and
  674. // in the index there is nothing (e.g. 'git rm ...' was
  675. // called before). Ignore the cached deletion and use what we
  676. // find in Merge. Potentially updates the file.
  677. if (equalIdAndMode(hId, hMode, mId, mMode)) {
  678. if (emptyDirCache)
  679. update(name, mId, mMode);
  680. else
  681. keep(dce);
  682. } else
  683. conflict(name, dce, h, m);
  684. }
  685. } else {
  686. // Something in Index
  687. if (h == null) {
  688. // Nothing in Head
  689. // Something in Index
  690. /**
  691. * <pre>
  692. * clean I==H I==M H M Result
  693. * -----------------------------------------------------
  694. * 4 yes N/A N/A nothing nothing keep index
  695. * 5 no N/A N/A nothing nothing keep index
  696. *
  697. * 6 yes N/A yes nothing exists keep index
  698. * 7 no N/A yes nothing exists keep index
  699. * 8 yes N/A no nothing exists fail
  700. * 9 no N/A no nothing exists fail
  701. * </pre>
  702. */
  703. if (m == null
  704. || !isModified_IndexTree(name, iId, iMode, mId, mMode,
  705. mergeCommitTree)) {
  706. // Merge contains nothing or the same as Index
  707. // Nothing in Head
  708. // Something in Index
  709. if (m==null && walk.isDirectoryFileConflict()) {
  710. // Nothing in Merge and current path is part of
  711. // File/Folder conflict
  712. // Nothing in Head
  713. // Something in Index
  714. if (dce != null
  715. && (f == null || f.isModified(dce, true,
  716. this.walk.getObjectReader())))
  717. // No file or file is dirty
  718. // Nothing in Merge and current path is part of
  719. // File/Folder conflict
  720. // Nothing in Head
  721. // Something in Index
  722. // -> File folder conflict and Merge wants this
  723. // path to be removed. Since the file is dirty
  724. // report a conflict
  725. conflict(name, dce, h, m);
  726. else
  727. // A file is present and file is not dirty
  728. // Nothing in Merge and current path is part of
  729. // File/Folder conflict
  730. // Nothing in Head
  731. // Something in Index
  732. // -> File folder conflict and Merge wants this path
  733. // to be removed. Since the file is not dirty remove
  734. // file and index entry
  735. remove(name);
  736. } else
  737. // Something in Merge or current path is not part of
  738. // File/Folder conflict
  739. // Merge contains nothing or the same as Index
  740. // Nothing in Head
  741. // Something in Index
  742. // -> Merge contains nothing new. Keep the index.
  743. keep(dce);
  744. } else
  745. // Merge contains something and it is not the same as Index
  746. // Nothing in Head
  747. // Something in Index
  748. // -> Index contains something new (different from Head)
  749. // and Merge is different from Index. Report a conflict
  750. conflict(name, dce, h, m);
  751. } else if (m == null) {
  752. // Nothing in Merge
  753. // Something in Head
  754. // Something in Index
  755. /**
  756. * <pre>
  757. * clean I==H I==M H M Result
  758. * -----------------------------------------------------
  759. * 10 yes yes N/A exists nothing remove path from index
  760. * 11 no yes N/A exists nothing keep file
  761. * 12 yes no N/A exists nothing fail
  762. * 13 no no N/A exists nothing fail
  763. * </pre>
  764. */
  765. if (iMode == FileMode.GITLINK) {
  766. // A submodule in Index
  767. // Nothing in Merge
  768. // Something in Head
  769. // Submodules that disappear from the checkout must
  770. // be removed from the index, but not deleted from disk.
  771. remove(name);
  772. } else {
  773. // Something different from a submodule in Index
  774. // Nothing in Merge
  775. // Something in Head
  776. if (!isModified_IndexTree(name, iId, iMode, hId, hMode,
  777. headCommitTree)) {
  778. // Index contains the same as Head
  779. // Something different from a submodule in Index
  780. // Nothing in Merge
  781. // Something in Head
  782. if (f != null
  783. && f.isModified(dce, true,
  784. this.walk.getObjectReader())) {
  785. // file is dirty
  786. // Index contains the same as Head
  787. // Something different from a submodule in Index
  788. // Nothing in Merge
  789. // Something in Head
  790. if (!FileMode.TREE.equals(f.getEntryFileMode())
  791. && FileMode.TREE.equals(iMode))
  792. // The workingtree contains a file and the index semantically contains a folder.
  793. // Git considers the workingtree file as untracked. Just keep the untracked file.
  794. return;
  795. else
  796. // -> file is dirty and tracked but is should be
  797. // removed. That's a conflict
  798. conflict(name, dce, h, m);
  799. } else
  800. // file doesn't exist or is clean
  801. // Index contains the same as Head
  802. // Something different from a submodule in Index
  803. // Nothing in Merge
  804. // Something in Head
  805. // -> Remove from index and delete the file
  806. remove(name);
  807. } else
  808. // Index contains something different from Head
  809. // Something different from a submodule in Index
  810. // Nothing in Merge
  811. // Something in Head
  812. // -> Something new is in index (and maybe even on the
  813. // filesystem). But Merge wants the path to be removed.
  814. // Report a conflict
  815. conflict(name, dce, h, m);
  816. }
  817. } else {
  818. // Something in Merge
  819. // Something in Head
  820. // Something in Index
  821. if (!equalIdAndMode(hId, hMode, mId, mMode)
  822. && isModified_IndexTree(name, iId, iMode, hId, hMode,
  823. headCommitTree)
  824. && isModified_IndexTree(name, iId, iMode, mId, mMode,
  825. mergeCommitTree))
  826. // All three contents in Head, Merge, Index differ from each
  827. // other
  828. // -> All contents differ. Report a conflict.
  829. conflict(name, dce, h, m);
  830. else
  831. // At least two of the contents of Head, Index, Merge
  832. // are the same
  833. // Something in Merge
  834. // Something in Head
  835. // Something in Index
  836. if (!isModified_IndexTree(name, iId, iMode, hId, hMode,
  837. headCommitTree)
  838. && isModified_IndexTree(name, iId, iMode, mId, mMode,
  839. mergeCommitTree)) {
  840. // Head contains the same as Index. Merge differs
  841. // Something in Merge
  842. // For submodules just update the index with the new SHA-1
  843. if (dce != null
  844. && FileMode.GITLINK.equals(dce.getFileMode())) {
  845. // Index and Head contain the same submodule. Merge
  846. // differs
  847. // Something in Merge
  848. // -> Nothing new in index. Move to merge.
  849. // Potentially updates the file
  850. // TODO check that we don't overwrite some unsaved
  851. // file content
  852. update(name, mId, mMode);
  853. } else if (dce != null
  854. && (f != null && f.isModified(dce, true,
  855. this.walk.getObjectReader()))) {
  856. // File exists and is dirty
  857. // Head and Index don't contain a submodule
  858. // Head contains the same as Index. Merge differs
  859. // Something in Merge
  860. // -> Merge wants the index and file to be updated
  861. // but the file is dirty. Report a conflict
  862. conflict(name, dce, h, m);
  863. } else {
  864. // File doesn't exist or is clean
  865. // Head and Index don't contain a submodule
  866. // Head contains the same as Index. Merge differs
  867. // Something in Merge
  868. // -> Standard case when switching between branches:
  869. // Nothing new in index but something different in
  870. // Merge. Update index and file
  871. update(name, mId, mMode);
  872. }
  873. } else {
  874. // Head differs from index or merge is same as index
  875. // At least two of the contents of Head, Index, Merge
  876. // are the same
  877. // Something in Merge
  878. // Something in Head
  879. // Something in Index
  880. // Can be formulated as: Either all three states are
  881. // equal or Merge is equal to Head or Index and differs
  882. // to the other one.
  883. // -> In all three cases we don't touch index and file.
  884. keep(dce);
  885. }
  886. }
  887. }
  888. }
  889. /**
  890. * A conflict is detected - add the three different stages to the index
  891. * @param path the path of the conflicting entry
  892. * @param e the previous index entry
  893. * @param h the first tree you want to merge (the HEAD)
  894. * @param m the second tree you want to merge
  895. */
  896. private void conflict(String path, DirCacheEntry e, AbstractTreeIterator h, AbstractTreeIterator m) {
  897. conflicts.add(path);
  898. DirCacheEntry entry;
  899. if (e != null) {
  900. entry = new DirCacheEntry(e.getPathString(), DirCacheEntry.STAGE_1);
  901. entry.copyMetaData(e, true);
  902. builder.add(entry);
  903. }
  904. if (h != null && !FileMode.TREE.equals(h.getEntryFileMode())) {
  905. entry = new DirCacheEntry(h.getEntryPathString(), DirCacheEntry.STAGE_2);
  906. entry.setFileMode(h.getEntryFileMode());
  907. entry.setObjectId(h.getEntryObjectId());
  908. builder.add(entry);
  909. }
  910. if (m != null && !FileMode.TREE.equals(m.getEntryFileMode())) {
  911. entry = new DirCacheEntry(m.getEntryPathString(), DirCacheEntry.STAGE_3);
  912. entry.setFileMode(m.getEntryFileMode());
  913. entry.setObjectId(m.getEntryObjectId());
  914. builder.add(entry);
  915. }
  916. }
  917. private void keep(DirCacheEntry e) {
  918. if (e != null && !FileMode.TREE.equals(e.getFileMode()))
  919. builder.add(e);
  920. }
  921. private void remove(String path) {
  922. removed.add(path);
  923. }
  924. private void update(String path, ObjectId mId, FileMode mode) {
  925. if (!FileMode.TREE.equals(mode)) {
  926. updated.put(path, mId);
  927. DirCacheEntry entry = new DirCacheEntry(path, DirCacheEntry.STAGE_0);
  928. entry.setObjectId(mId);
  929. entry.setFileMode(mode);
  930. builder.add(entry);
  931. }
  932. }
  933. /**
  934. * If <code>true</code>, will scan first to see if it's possible to check
  935. * out, otherwise throw {@link CheckoutConflictException}. If
  936. * <code>false</code>, it will silently deal with the problem.
  937. *
  938. * @param failOnConflict
  939. */
  940. public void setFailOnConflict(boolean failOnConflict) {
  941. this.failOnConflict = failOnConflict;
  942. }
  943. /**
  944. * This method implements how to handle conflicts when
  945. * {@link #failOnConflict} is false
  946. *
  947. * @throws CheckoutConflictException
  948. */
  949. private void cleanUpConflicts() throws CheckoutConflictException {
  950. // TODO: couldn't we delete unsaved worktree content here?
  951. for (String c : conflicts) {
  952. File conflict = new File(repo.getWorkTree(), c);
  953. if (!conflict.delete())
  954. throw new CheckoutConflictException(MessageFormat.format(
  955. JGitText.get().cannotDeleteFile, c));
  956. removeEmptyParents(conflict);
  957. }
  958. for (String r : removed) {
  959. File file = new File(repo.getWorkTree(), r);
  960. if (!file.delete())
  961. throw new CheckoutConflictException(
  962. MessageFormat.format(JGitText.get().cannotDeleteFile,
  963. file.getAbsolutePath()));
  964. removeEmptyParents(file);
  965. }
  966. }
  967. /**
  968. * Checks whether the subtree starting at a given path differs between Index and
  969. * workingtree.
  970. *
  971. * @param path
  972. * @return true if the subtrees differ
  973. * @throws CorruptObjectException
  974. * @throws IOException
  975. */
  976. private boolean isModifiedSubtree_IndexWorkingtree(String path)
  977. throws CorruptObjectException, IOException {
  978. NameConflictTreeWalk tw = new NameConflictTreeWalk(repo);
  979. try {
  980. tw.addTree(new DirCacheIterator(dc));
  981. tw.addTree(new FileTreeIterator(repo));
  982. tw.setRecursive(true);
  983. tw.setFilter(PathFilter.create(path));
  984. DirCacheIterator dcIt;
  985. WorkingTreeIterator wtIt;
  986. while (tw.next()) {
  987. dcIt = tw.getTree(0, DirCacheIterator.class);
  988. wtIt = tw.getTree(1, WorkingTreeIterator.class);
  989. if (dcIt == null || wtIt == null)
  990. return true;
  991. if (wtIt.isModified(dcIt.getDirCacheEntry(), true,
  992. this.walk.getObjectReader())) {
  993. return true;
  994. }
  995. }
  996. return false;
  997. } finally {
  998. tw.release();
  999. }
  1000. }
  1001. private boolean isModified_IndexTree(String path, ObjectId iId,
  1002. FileMode iMode, ObjectId tId, FileMode tMode, ObjectId rootTree)
  1003. throws CorruptObjectException, IOException {
  1004. if (iMode != tMode)
  1005. return true;
  1006. if (FileMode.TREE.equals(iMode)
  1007. && (iId == null || ObjectId.zeroId().equals(iId)))
  1008. return isModifiedSubtree_IndexTree(path, rootTree);
  1009. else
  1010. return !equalIdAndMode(iId, iMode, tId, tMode);
  1011. }
  1012. /**
  1013. * Checks whether the subtree starting at a given path differs between Index and
  1014. * some tree.
  1015. *
  1016. * @param path
  1017. * @param tree
  1018. * the tree to compare
  1019. * @return true if the subtrees differ
  1020. * @throws CorruptObjectException
  1021. * @throws IOException
  1022. */
  1023. private boolean isModifiedSubtree_IndexTree(String path, ObjectId tree)
  1024. throws CorruptObjectException, IOException {
  1025. NameConflictTreeWalk tw = new NameConflictTreeWalk(repo);
  1026. try {
  1027. tw.addTree(new DirCacheIterator(dc));
  1028. tw.addTree(tree);
  1029. tw.setRecursive(true);
  1030. tw.setFilter(PathFilter.create(path));
  1031. while (tw.next()) {
  1032. AbstractTreeIterator dcIt = tw.getTree(0,
  1033. DirCacheIterator.class);
  1034. AbstractTreeIterator treeIt = tw.getTree(1,
  1035. AbstractTreeIterator.class);
  1036. if (dcIt == null || treeIt == null)
  1037. return true;
  1038. if (dcIt.getEntryRawMode() != treeIt.getEntryRawMode())
  1039. return true;
  1040. if (!dcIt.getEntryObjectId().equals(treeIt.getEntryObjectId()))
  1041. return true;
  1042. }
  1043. return false;
  1044. } finally {
  1045. tw.release();
  1046. }
  1047. }
  1048. /**
  1049. * Updates the file in the working tree with content and mode from an entry
  1050. * in the index. The new content is first written to a new temporary file in
  1051. * the same directory as the real file. Then that new file is renamed to the
  1052. * final filename. Use this method only for checkout of a single entry.
  1053. * Otherwise use
  1054. * {@code checkoutEntry(Repository, File f, DirCacheEntry, ObjectReader)}
  1055. * instead which allows to reuse one {@code ObjectReader} for multiple
  1056. * entries.
  1057. *
  1058. * <p>
  1059. * TODO: this method works directly on File IO, we may need another
  1060. * abstraction (like WorkingTreeIterator). This way we could tell e.g.
  1061. * Eclipse that Files in the workspace got changed
  1062. * </p>
  1063. *
  1064. * @param repository
  1065. * @param f
  1066. * this parameter is ignored.
  1067. * @param entry
  1068. * the entry containing new mode and content
  1069. * @throws IOException
  1070. * @deprecated Use the overloaded form that accepts {@link ObjectReader}.
  1071. */
  1072. @Deprecated
  1073. public static void checkoutEntry(final Repository repository, File f,
  1074. DirCacheEntry entry) throws IOException {
  1075. ObjectReader or = repository.newObjectReader();
  1076. try {
  1077. checkoutEntry(repository, f, entry, or);
  1078. } finally {
  1079. or.release();
  1080. }
  1081. }
  1082. /**
  1083. * Updates the file in the working tree with content and mode from an entry
  1084. * in the index. The new content is first written to a new temporary file in
  1085. * the same directory as the real file. Then that new file is renamed to the
  1086. * final filename.
  1087. *
  1088. * <p>
  1089. * TODO: this method works directly on File IO, we may need another
  1090. * abstraction (like WorkingTreeIterator). This way we could tell e.g.
  1091. * Eclipse that Files in the workspace got changed
  1092. * </p>
  1093. *
  1094. * @param repo
  1095. * @param f
  1096. * this parameter is ignored.
  1097. * @param entry
  1098. * the entry containing new mode and content
  1099. * @param or
  1100. * object reader to use for checkout
  1101. * @throws IOException
  1102. * @deprecated Do not pass File object.
  1103. */
  1104. @Deprecated
  1105. public static void checkoutEntry(final Repository repo, File f,
  1106. DirCacheEntry entry, ObjectReader or) throws IOException {
  1107. if (f == null || repo.getWorkTree() == null)
  1108. throw new IllegalArgumentException();
  1109. if (!f.equals(new File(repo.getWorkTree(), entry.getPathString())))
  1110. throw new IllegalArgumentException();
  1111. checkoutEntry(repo, entry, or);
  1112. }
  1113. /**
  1114. * Updates the file in the working tree with content and mode from an entry
  1115. * in the index. The new content is first written to a new temporary file in
  1116. * the same directory as the real file. Then that new file is renamed to the
  1117. * final filename.
  1118. *
  1119. * <p>
  1120. * TODO: this method works directly on File IO, we may need another
  1121. * abstraction (like WorkingTreeIterator). This way we could tell e.g.
  1122. * Eclipse that Files in the workspace got changed
  1123. * </p>
  1124. *
  1125. * @param repo
  1126. * repository managing the destination work tree.
  1127. * @param entry
  1128. * the entry containing new mode and content
  1129. * @param or
  1130. * object reader to use for checkout
  1131. * @throws IOException
  1132. * @since 3.6
  1133. */
  1134. public static void checkoutEntry(Repository repo, DirCacheEntry entry,
  1135. ObjectReader or) throws IOException {
  1136. ObjectLoader ol = or.open(entry.getObjectId());
  1137. File f = new File(repo.getWorkTree(), entry.getPathString());
  1138. File parentDir = f.getParentFile();
  1139. FileUtils.mkdirs(parentDir, true);
  1140. FS fs = repo.getFS();
  1141. WorkingTreeOptions opt = repo.getConfig().get(WorkingTreeOptions.KEY);
  1142. if (entry.getFileMode() == FileMode.SYMLINK
  1143. && opt.getSymLinks() == SymLinks.TRUE) {
  1144. byte[] bytes = ol.getBytes();
  1145. String target = RawParseUtils.decode(bytes);
  1146. fs.createSymLink(f, target);
  1147. entry.setLength(bytes.length);
  1148. entry.setLastModified(fs.lastModified(f));
  1149. return;
  1150. }
  1151. File tmpFile = File.createTempFile(
  1152. "._" + f.getName(), null, parentDir); //$NON-NLS-1$
  1153. OutputStream channel = new FileOutputStream(tmpFile);
  1154. if (opt.getAutoCRLF() == AutoCRLF.TRUE)
  1155. channel = new AutoCRLFOutputStream(channel);
  1156. try {
  1157. ol.copyTo(channel);
  1158. } finally {
  1159. channel.close();
  1160. }
  1161. entry.setLength(opt.getAutoCRLF() == AutoCRLF.TRUE ? //
  1162. tmpFile.length() // AutoCRLF wants on-disk-size
  1163. : (int) ol.getSize());
  1164. if (opt.isFileMode() && fs.supportsExecute()) {
  1165. if (FileMode.EXECUTABLE_FILE.equals(entry.getRawMode())) {
  1166. if (!fs.canExecute(tmpFile))
  1167. fs.setExecute(tmpFile, true);
  1168. } else {
  1169. if (fs.canExecute(tmpFile))
  1170. fs.setExecute(tmpFile, false);
  1171. }
  1172. }
  1173. try {
  1174. FileUtils.rename(tmpFile, f);
  1175. } catch (IOException e) {
  1176. throw new IOException(MessageFormat.format(
  1177. JGitText.get().renameFileFailed, tmpFile.getPath(),
  1178. f.getPath()));
  1179. }
  1180. entry.setLastModified(f.lastModified());
  1181. }
  1182. private static void checkValidPath(CanonicalTreeParser t)
  1183. throws InvalidPathException {
  1184. ObjectChecker chk = new ObjectChecker()
  1185. .setSafeForWindows(SystemReader.getInstance().isWindows())
  1186. .setSafeForMacOS(SystemReader.getInstance().isMacOS());
  1187. for (CanonicalTreeParser i = t; i != null; i = i.getParent())
  1188. checkValidPathSegment(chk, i);
  1189. }
  1190. /**
  1191. * Check if path is a valid path for a checked out file name or ref name.
  1192. *
  1193. * @param path
  1194. * @throws InvalidPathException
  1195. * if the path is invalid
  1196. * @since 3.3
  1197. * @deprecated Use {@link SystemReader#checkPath(String)}.
  1198. */
  1199. @Deprecated
  1200. public static void checkValidPath(String path) throws InvalidPathException {
  1201. try {
  1202. SystemReader.getInstance().checkPath(path);
  1203. } catch (CorruptObjectException e) {
  1204. InvalidPathException p = new InvalidPathException(path);
  1205. p.initCause(e);
  1206. throw p;
  1207. }
  1208. }
  1209. private static void checkValidPathSegment(ObjectChecker chk,
  1210. CanonicalTreeParser t) throws InvalidPathException {
  1211. try {
  1212. int ptr = t.getNameOffset();
  1213. int end = ptr + t.getNameLength();
  1214. chk.checkPathSegment(t.getEntryPathBuffer(), ptr, end);
  1215. } catch (CorruptObjectException err) {
  1216. String path = t.getEntryPathString();
  1217. InvalidPathException i = new InvalidPathException(path);
  1218. i.initCause(err);
  1219. throw i;
  1220. }
  1221. }
  1222. }