You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DirCacheCheckout.java 43KB

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