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

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