Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

DirCacheCheckout.java 44KB

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