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 42KB

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