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

DirectoryScanner.java 68 kB

9 years ago
9 years ago
9 years ago
12 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
12 years ago
9 years ago
11 years ago
9 years ago
9 years ago
11 years ago
9 years ago
11 years ago
9 years ago
11 years ago
9 years ago
11 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
12 years ago
9 years ago
9 years ago
9 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package org.apache.tools.ant;
  19. import java.io.File;
  20. import java.io.IOException;
  21. import java.nio.file.Files;
  22. import java.nio.file.Path;
  23. import java.nio.file.Paths;
  24. import java.util.ArrayList;
  25. import java.util.Arrays;
  26. import java.util.Collections;
  27. import java.util.Deque;
  28. import java.util.HashMap;
  29. import java.util.HashSet;
  30. import java.util.LinkedList;
  31. import java.util.List;
  32. import java.util.Map;
  33. import java.util.Set;
  34. import java.util.Vector;
  35. import java.util.function.Predicate;
  36. import java.util.stream.Stream;
  37. import org.apache.tools.ant.taskdefs.condition.Os;
  38. import org.apache.tools.ant.types.Resource;
  39. import org.apache.tools.ant.types.ResourceFactory;
  40. import org.apache.tools.ant.types.resources.FileResource;
  41. import org.apache.tools.ant.types.selectors.FileSelector;
  42. import org.apache.tools.ant.types.selectors.SelectorScanner;
  43. import org.apache.tools.ant.types.selectors.SelectorUtils;
  44. import org.apache.tools.ant.types.selectors.TokenizedPath;
  45. import org.apache.tools.ant.types.selectors.TokenizedPattern;
  46. import org.apache.tools.ant.util.FileUtils;
  47. import org.apache.tools.ant.util.VectorSet;
  48. /**
  49. * Class for scanning a directory for files/directories which match certain
  50. * criteria.
  51. * <p>
  52. * These criteria consist of selectors and patterns which have been specified.
  53. * With the selectors you can select which files you want to have included.
  54. * Files which are not selected are excluded. With patterns you can include
  55. * or exclude files based on their filename.
  56. * </p>
  57. * <p>
  58. * The idea is simple. A given directory is recursively scanned for all files
  59. * and directories. Each file/directory is matched against a set of selectors,
  60. * including special support for matching against filenames with include and
  61. * and exclude patterns. Only files/directories which match at least one
  62. * pattern of the include pattern list or other file selector, and don't match
  63. * any pattern of the exclude pattern list or fail to match against a required
  64. * selector will be placed in the list of files/directories found.
  65. * </p>
  66. * <p>
  67. * When no list of include patterns is supplied, "**" will be used, which
  68. * means that everything will be matched. When no list of exclude patterns is
  69. * supplied, an empty list is used, such that nothing will be excluded. When
  70. * no selectors are supplied, none are applied.
  71. * </p>
  72. * <p>
  73. * The filename pattern matching is done as follows:
  74. * The name to be matched is split up in path segments. A path segment is the
  75. * name of a directory or file, which is bounded by
  76. * <code>File.separator</code> ('/' under UNIX, '\' under Windows).
  77. * For example, "abc/def/ghi/xyz.java" is split up in the segments "abc",
  78. * "def","ghi" and "xyz.java".
  79. * The same is done for the pattern against which should be matched.
  80. * </p>
  81. * <p>
  82. * The segments of the name and the pattern are then matched against each
  83. * other. When '**' is used for a path segment in the pattern, it matches
  84. * zero or more path segments of the name.
  85. * </p>
  86. * <p>
  87. * There is a special case regarding the use of <code>File.separator</code>s
  88. * at the beginning of the pattern and the string to match:
  89. * </p>
  90. * <ul>
  91. * <li>When a pattern starts with a <code>File.separator</code>, the string
  92. * to match must also start with a <code>File.separator</code>.</li>
  93. * <li>When a pattern does not start with a <code>File.separator</code>, the
  94. * string to match may not start with a <code>File.separator</code>.</li>
  95. * <li>When one of the above rules is not obeyed, the string will not
  96. * match.</li>
  97. * </ul>
  98. * <p>
  99. * When a name path segment is matched against a pattern path segment, the
  100. * following special characters can be used:<br>
  101. * '*' matches zero or more characters<br>
  102. * '?' matches one character.
  103. * </p>
  104. * <p>
  105. * Examples:
  106. * </p>
  107. * <p>
  108. * "**\*.class" matches all .class files/dirs in a directory tree.
  109. * </p>
  110. * <p>
  111. * "test\a??.java" matches all files/dirs which start with an 'a', then two
  112. * more characters and then ".java", in a directory called test.
  113. * </p>
  114. * <p>
  115. * "**" matches everything in a directory tree.
  116. * </p>
  117. * <p>
  118. * "**\test\**\XYZ*" matches all files/dirs which start with "XYZ" and where
  119. * there is a parent directory called test (e.g. "abc\test\def\ghi\XYZ123").
  120. * </p>
  121. * <p>
  122. * Case sensitivity may be turned off if necessary. By default, it is
  123. * turned on.
  124. * </p>
  125. * <p>
  126. * Example of usage:
  127. * </p>
  128. * <pre>
  129. * String[] includes = {"**\\*.class"};
  130. * String[] excludes = {"modules\\*\\**"};
  131. * ds.setIncludes(includes);
  132. * ds.setExcludes(excludes);
  133. * ds.setBasedir(new File("test"));
  134. * ds.setCaseSensitive(true);
  135. * ds.scan();
  136. *
  137. * System.out.println("FILES:");
  138. * String[] files = ds.getIncludedFiles();
  139. * for (int i = 0; i &lt; files.length; i++) {
  140. * System.out.println(files[i]);
  141. * }
  142. * </pre>
  143. * This will scan a directory called test for .class files, but excludes all
  144. * files in all proper subdirectories of a directory called "modules".
  145. *
  146. */
  147. public class DirectoryScanner
  148. implements FileScanner, SelectorScanner, ResourceFactory {
  149. /** Is OpenVMS the operating system we're running on? */
  150. private static final boolean ON_VMS = Os.isFamily("openvms");
  151. /**
  152. * Patterns which should be excluded by default.
  153. *
  154. * <p>Note that you can now add patterns to the list of default
  155. * excludes. Added patterns will not become part of this array
  156. * that has only been kept around for backwards compatibility
  157. * reasons.</p>
  158. *
  159. * @deprecated since 1.6.x.
  160. * Use the {@link #getDefaultExcludes getDefaultExcludes}
  161. * method instead.
  162. */
  163. @Deprecated
  164. protected static final String[] DEFAULTEXCLUDES = { //NOSONAR
  165. // Miscellaneous typical temporary files
  166. SelectorUtils.DEEP_TREE_MATCH + "/*~",
  167. SelectorUtils.DEEP_TREE_MATCH + "/#*#",
  168. SelectorUtils.DEEP_TREE_MATCH + "/.#*",
  169. SelectorUtils.DEEP_TREE_MATCH + "/%*%",
  170. SelectorUtils.DEEP_TREE_MATCH + "/._*",
  171. // CVS
  172. SelectorUtils.DEEP_TREE_MATCH + "/CVS",
  173. SelectorUtils.DEEP_TREE_MATCH + "/CVS/" + SelectorUtils.DEEP_TREE_MATCH,
  174. SelectorUtils.DEEP_TREE_MATCH + "/.cvsignore",
  175. // SCCS
  176. SelectorUtils.DEEP_TREE_MATCH + "/SCCS",
  177. SelectorUtils.DEEP_TREE_MATCH + "/SCCS/" + SelectorUtils.DEEP_TREE_MATCH,
  178. // Visual SourceSafe
  179. SelectorUtils.DEEP_TREE_MATCH + "/vssver.scc",
  180. // Subversion
  181. SelectorUtils.DEEP_TREE_MATCH + "/.svn",
  182. SelectorUtils.DEEP_TREE_MATCH + "/.svn/" + SelectorUtils.DEEP_TREE_MATCH,
  183. // Git
  184. SelectorUtils.DEEP_TREE_MATCH + "/.git",
  185. SelectorUtils.DEEP_TREE_MATCH + "/.git/" + SelectorUtils.DEEP_TREE_MATCH,
  186. SelectorUtils.DEEP_TREE_MATCH + "/.gitattributes",
  187. SelectorUtils.DEEP_TREE_MATCH + "/.gitignore",
  188. SelectorUtils.DEEP_TREE_MATCH + "/.gitmodules",
  189. // Mercurial
  190. SelectorUtils.DEEP_TREE_MATCH + "/.hg",
  191. SelectorUtils.DEEP_TREE_MATCH + "/.hg/" + SelectorUtils.DEEP_TREE_MATCH,
  192. SelectorUtils.DEEP_TREE_MATCH + "/.hgignore",
  193. SelectorUtils.DEEP_TREE_MATCH + "/.hgsub",
  194. SelectorUtils.DEEP_TREE_MATCH + "/.hgsubstate",
  195. SelectorUtils.DEEP_TREE_MATCH + "/.hgtags",
  196. // Bazaar
  197. SelectorUtils.DEEP_TREE_MATCH + "/.bzr",
  198. SelectorUtils.DEEP_TREE_MATCH + "/.bzr/" + SelectorUtils.DEEP_TREE_MATCH,
  199. SelectorUtils.DEEP_TREE_MATCH + "/.bzrignore",
  200. // Mac
  201. SelectorUtils.DEEP_TREE_MATCH + "/.DS_Store"
  202. };
  203. /**
  204. * default value for {@link #maxLevelsOfSymlinks maxLevelsOfSymlinks}
  205. * @since Ant 1.8.0
  206. */
  207. public static final int MAX_LEVELS_OF_SYMLINKS = 5;
  208. /**
  209. * The end of the exception message if something that should be
  210. * there doesn't exist.
  211. */
  212. public static final String DOES_NOT_EXIST_POSTFIX = " does not exist.";
  213. /** Helper. */
  214. private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
  215. /**
  216. * Patterns which should be excluded by default.
  217. *
  218. * @see #addDefaultExcludes()
  219. */
  220. private static final Set<String> defaultExcludes = new HashSet<>();
  221. static {
  222. resetDefaultExcludes();
  223. }
  224. // CheckStyle:VisibilityModifier OFF - bc
  225. /** The base directory to be scanned. */
  226. protected File basedir;
  227. /** The patterns for the files to be included. */
  228. protected String[] includes;
  229. /** The patterns for the files to be excluded. */
  230. protected String[] excludes;
  231. /** Selectors that will filter which files are in our candidate list. */
  232. protected FileSelector[] selectors = null;
  233. /**
  234. * The files which matched at least one include and no excludes
  235. * and were selected.
  236. */
  237. protected Vector<String> filesIncluded;
  238. /** The files which did not match any includes or selectors. */
  239. protected Vector<String> filesNotIncluded;
  240. /**
  241. * The files which matched at least one include and at least
  242. * one exclude.
  243. */
  244. protected Vector<String> filesExcluded;
  245. /**
  246. * The directories which matched at least one include and no excludes
  247. * and were selected.
  248. */
  249. protected Vector<String> dirsIncluded;
  250. /** The directories which were found and did not match any includes. */
  251. protected Vector<String> dirsNotIncluded;
  252. /**
  253. * The directories which matched at least one include and at least one
  254. * exclude.
  255. */
  256. protected Vector<String> dirsExcluded;
  257. /**
  258. * The files which matched at least one include and no excludes and
  259. * which a selector discarded.
  260. */
  261. protected Vector<String> filesDeselected;
  262. /**
  263. * The directories which matched at least one include and no excludes
  264. * but which a selector discarded.
  265. */
  266. protected Vector<String> dirsDeselected;
  267. /** Whether or not our results were built by a slow scan. */
  268. protected boolean haveSlowResults = false;
  269. /**
  270. * Whether or not the file system should be treated as a case sensitive
  271. * one.
  272. */
  273. protected boolean isCaseSensitive = true;
  274. /**
  275. * Whether a missing base directory is an error.
  276. * @since Ant 1.7.1
  277. */
  278. protected boolean errorOnMissingDir = true;
  279. /**
  280. * Whether or not symbolic links should be followed.
  281. *
  282. * @since Ant 1.5
  283. */
  284. private boolean followSymlinks = true;
  285. /** Whether or not everything tested so far has been included. */
  286. protected boolean everythingIncluded = true;
  287. // CheckStyle:VisibilityModifier ON
  288. /**
  289. * List of all scanned directories.
  290. *
  291. * @since Ant 1.6
  292. */
  293. private final Set<String> scannedDirs = new HashSet<>();
  294. /**
  295. * Map of all include patterns that are full file names and don't
  296. * contain any wildcards.
  297. *
  298. * <p>Maps pattern string to TokenizedPath.</p>
  299. *
  300. * <p>If this instance is not case sensitive, the file names get
  301. * turned to upper case.</p>
  302. *
  303. * <p>Gets lazily initialized on the first invocation of
  304. * isIncluded or isExcluded and cleared at the end of the scan
  305. * method (cleared in clearCaches, actually).</p>
  306. *
  307. * @since Ant 1.8.0
  308. */
  309. private final Map<String, TokenizedPath> includeNonPatterns = new HashMap<>();
  310. /**
  311. * Map of all exclude patterns that are full file names and don't
  312. * contain any wildcards.
  313. *
  314. * <p>Maps pattern string to TokenizedPath.</p>
  315. *
  316. * <p>If this instance is not case sensitive, the file names get
  317. * turned to upper case.</p>
  318. *
  319. * <p>Gets lazily initialized on the first invocation of
  320. * isIncluded or isExcluded and cleared at the end of the scan
  321. * method (cleared in clearCaches, actually).</p>
  322. *
  323. * @since Ant 1.8.0
  324. */
  325. private final Map<String, TokenizedPath> excludeNonPatterns = new HashMap<>();
  326. /**
  327. * Array of all include patterns that contain wildcards.
  328. *
  329. * <p>Gets lazily initialized on the first invocation of
  330. * isIncluded or isExcluded and cleared at the end of the scan
  331. * method (cleared in clearCaches, actually).</p>
  332. */
  333. private TokenizedPattern[] includePatterns;
  334. /**
  335. * Array of all exclude patterns that contain wildcards.
  336. *
  337. * <p>Gets lazily initialized on the first invocation of
  338. * isIncluded or isExcluded and cleared at the end of the scan
  339. * method (cleared in clearCaches, actually).</p>
  340. */
  341. private TokenizedPattern[] excludePatterns;
  342. /**
  343. * Have the non-pattern sets and pattern arrays for in- and
  344. * excludes been initialized?
  345. *
  346. * @since Ant 1.6.3
  347. */
  348. private boolean areNonPatternSetsReady = false;
  349. /**
  350. * Scanning flag.
  351. *
  352. * @since Ant 1.6.3
  353. */
  354. private boolean scanning = false;
  355. /**
  356. * Scanning lock.
  357. *
  358. * @since Ant 1.6.3
  359. */
  360. private final Object scanLock = new Object();
  361. /**
  362. * Slow scanning flag.
  363. *
  364. * @since Ant 1.6.3
  365. */
  366. private boolean slowScanning = false;
  367. /**
  368. * Slow scanning lock.
  369. *
  370. * @since Ant 1.6.3
  371. */
  372. private final Object slowScanLock = new Object();
  373. /**
  374. * Exception thrown during scan.
  375. *
  376. * @since Ant 1.6.3
  377. */
  378. private IllegalStateException illegal = null;
  379. /**
  380. * The maximum number of times a symbolic link may be followed
  381. * during a scan.
  382. *
  383. * @since Ant 1.8.0
  384. */
  385. private int maxLevelsOfSymlinks = MAX_LEVELS_OF_SYMLINKS;
  386. /**
  387. * Absolute paths of all symlinks that haven't been followed but
  388. * would have been if followsymlinks had been true or
  389. * maxLevelsOfSymlinks had been higher.
  390. *
  391. * @since Ant 1.8.0
  392. */
  393. private final Set<String> notFollowedSymlinks = new HashSet<>();
  394. /**
  395. * Test whether or not a given path matches the start of a given
  396. * pattern up to the first "**".
  397. * <p>
  398. * This is not a general purpose test and should only be used if you
  399. * can live with false positives. For example, <code>pattern=**\a</code>
  400. * and <code>str=b</code> will yield <code>true</code>.
  401. *
  402. * @param pattern The pattern to match against. Must not be
  403. * <code>null</code>.
  404. * @param str The path to match, as a String. Must not be
  405. * <code>null</code>.
  406. *
  407. * @return whether or not a given path matches the start of a given
  408. * pattern up to the first "**".
  409. */
  410. protected static boolean matchPatternStart(final String pattern, final String str) {
  411. return SelectorUtils.matchPatternStart(pattern, str);
  412. }
  413. /**
  414. * Test whether or not a given path matches the start of a given
  415. * pattern up to the first "**".
  416. * <p>
  417. * This is not a general purpose test and should only be used if you
  418. * can live with false positives. For example, <code>pattern=**\a</code>
  419. * and <code>str=b</code> will yield <code>true</code>.
  420. *
  421. * @param pattern The pattern to match against. Must not be
  422. * <code>null</code>.
  423. * @param str The path to match, as a String. Must not be
  424. * <code>null</code>.
  425. * @param isCaseSensitive Whether or not matching should be performed
  426. * case sensitively.
  427. *
  428. * @return whether or not a given path matches the start of a given
  429. * pattern up to the first "**".
  430. */
  431. protected static boolean matchPatternStart(final String pattern, final String str,
  432. final boolean isCaseSensitive) {
  433. return SelectorUtils.matchPatternStart(pattern, str, isCaseSensitive);
  434. }
  435. /**
  436. * Test whether or not a given path matches a given pattern.
  437. *
  438. * @param pattern The pattern to match against. Must not be
  439. * <code>null</code>.
  440. * @param str The path to match, as a String. Must not be
  441. * <code>null</code>.
  442. *
  443. * @return <code>true</code> if the pattern matches against the string,
  444. * or <code>false</code> otherwise.
  445. */
  446. protected static boolean matchPath(final String pattern, final String str) {
  447. return SelectorUtils.matchPath(pattern, str);
  448. }
  449. /**
  450. * Test whether or not a given path matches a given pattern.
  451. *
  452. * @param pattern The pattern to match against. Must not be
  453. * <code>null</code>.
  454. * @param str The path to match, as a String. Must not be
  455. * <code>null</code>.
  456. * @param isCaseSensitive Whether or not matching should be performed
  457. * case sensitively.
  458. *
  459. * @return <code>true</code> if the pattern matches against the string,
  460. * or <code>false</code> otherwise.
  461. */
  462. protected static boolean matchPath(final String pattern, final String str,
  463. final boolean isCaseSensitive) {
  464. return SelectorUtils.matchPath(pattern, str, isCaseSensitive);
  465. }
  466. /**
  467. * Test whether or not a string matches against a pattern.
  468. * The pattern may contain two special characters:<br>
  469. * '*' means zero or more characters<br>
  470. * '?' means one and only one character
  471. *
  472. * @param pattern The pattern to match against.
  473. * Must not be <code>null</code>.
  474. * @param str The string which must be matched against the pattern.
  475. * Must not be <code>null</code>.
  476. *
  477. * @return <code>true</code> if the string matches against the pattern,
  478. * or <code>false</code> otherwise.
  479. */
  480. public static boolean match(final String pattern, final String str) {
  481. return SelectorUtils.match(pattern, str);
  482. }
  483. /**
  484. * Test whether or not a string matches against a pattern.
  485. * The pattern may contain two special characters:<br>
  486. * '*' means zero or more characters<br>
  487. * '?' means one and only one character
  488. *
  489. * @param pattern The pattern to match against.
  490. * Must not be <code>null</code>.
  491. * @param str The string which must be matched against the pattern.
  492. * Must not be <code>null</code>.
  493. * @param isCaseSensitive Whether or not matching should be performed
  494. * case sensitively.
  495. *
  496. *
  497. * @return <code>true</code> if the string matches against the pattern,
  498. * or <code>false</code> otherwise.
  499. */
  500. protected static boolean match(final String pattern, final String str,
  501. final boolean isCaseSensitive) {
  502. return SelectorUtils.match(pattern, str, isCaseSensitive);
  503. }
  504. /**
  505. * Get the list of patterns that should be excluded by default.
  506. *
  507. * @return An array of <code>String</code> based on the current
  508. * contents of the <code>defaultExcludes</code>
  509. * <code>Set</code>.
  510. *
  511. * @since Ant 1.6
  512. */
  513. public static String[] getDefaultExcludes() {
  514. synchronized (defaultExcludes) {
  515. return defaultExcludes.toArray(new String[defaultExcludes
  516. .size()]);
  517. }
  518. }
  519. /**
  520. * Add a pattern to the default excludes unless it is already a
  521. * default exclude.
  522. *
  523. * @param s A string to add as an exclude pattern.
  524. * @return <code>true</code> if the string was added;
  525. * <code>false</code> if it already existed.
  526. *
  527. * @since Ant 1.6
  528. */
  529. public static boolean addDefaultExclude(final String s) {
  530. synchronized (defaultExcludes) {
  531. return defaultExcludes.add(s);
  532. }
  533. }
  534. /**
  535. * Remove a string if it is a default exclude.
  536. *
  537. * @param s The string to attempt to remove.
  538. * @return <code>true</code> if <code>s</code> was a default
  539. * exclude (and thus was removed);
  540. * <code>false</code> if <code>s</code> was not
  541. * in the default excludes list to begin with.
  542. *
  543. * @since Ant 1.6
  544. */
  545. public static boolean removeDefaultExclude(final String s) {
  546. synchronized (defaultExcludes) {
  547. return defaultExcludes.remove(s);
  548. }
  549. }
  550. /**
  551. * Go back to the hardwired default exclude patterns.
  552. *
  553. * @since Ant 1.6
  554. */
  555. public static void resetDefaultExcludes() {
  556. synchronized (defaultExcludes) {
  557. defaultExcludes.clear();
  558. Collections.addAll(defaultExcludes, DEFAULTEXCLUDES);
  559. }
  560. }
  561. /**
  562. * Set the base directory to be scanned. This is the directory which is
  563. * scanned recursively. All '/' and '\' characters are replaced by
  564. * <code>File.separatorChar</code>, so the separator used need not match
  565. * <code>File.separatorChar</code>.
  566. *
  567. * @param basedir The base directory to scan.
  568. */
  569. @Override
  570. public void setBasedir(final String basedir) {
  571. setBasedir(basedir == null ? null
  572. : new File(basedir.replace('/', File.separatorChar).replace(
  573. '\\', File.separatorChar)));
  574. }
  575. /**
  576. * Set the base directory to be scanned. This is the directory which is
  577. * scanned recursively.
  578. *
  579. * @param basedir The base directory for scanning.
  580. */
  581. @Override
  582. public synchronized void setBasedir(final File basedir) {
  583. this.basedir = basedir;
  584. }
  585. /**
  586. * Return the base directory to be scanned.
  587. * This is the directory which is scanned recursively.
  588. *
  589. * @return the base directory to be scanned.
  590. */
  591. @Override
  592. public synchronized File getBasedir() {
  593. return basedir;
  594. }
  595. /**
  596. * Find out whether include exclude patterns are matched in a
  597. * case sensitive way.
  598. * @return whether or not the scanning is case sensitive.
  599. * @since Ant 1.6
  600. */
  601. public synchronized boolean isCaseSensitive() {
  602. return isCaseSensitive;
  603. }
  604. /**
  605. * Set whether or not include and exclude patterns are matched
  606. * in a case sensitive way.
  607. *
  608. * @param isCaseSensitive whether or not the file system should be
  609. * regarded as a case sensitive one.
  610. */
  611. @Override
  612. public synchronized void setCaseSensitive(final boolean isCaseSensitive) {
  613. this.isCaseSensitive = isCaseSensitive;
  614. }
  615. /**
  616. * Sets whether or not a missing base directory is an error
  617. *
  618. * @param errorOnMissingDir whether or not a missing base directory
  619. * is an error
  620. * @since Ant 1.7.1
  621. */
  622. public void setErrorOnMissingDir(final boolean errorOnMissingDir) {
  623. this.errorOnMissingDir = errorOnMissingDir;
  624. }
  625. /**
  626. * Get whether or not a DirectoryScanner follows symbolic links.
  627. *
  628. * @return flag indicating whether symbolic links should be followed.
  629. *
  630. * @since Ant 1.6
  631. */
  632. public synchronized boolean isFollowSymlinks() {
  633. return followSymlinks;
  634. }
  635. /**
  636. * Set whether or not symbolic links should be followed.
  637. *
  638. * @param followSymlinks whether or not symbolic links should be followed.
  639. */
  640. public synchronized void setFollowSymlinks(final boolean followSymlinks) {
  641. this.followSymlinks = followSymlinks;
  642. }
  643. /**
  644. * The maximum number of times a symbolic link may be followed
  645. * during a scan.
  646. *
  647. * @param max int
  648. * @since Ant 1.8.0
  649. */
  650. public void setMaxLevelsOfSymlinks(final int max) {
  651. maxLevelsOfSymlinks = max;
  652. }
  653. /**
  654. * Set the list of include patterns to use. All '/' and '\' characters
  655. * are replaced by <code>File.separatorChar</code>, so the separator used
  656. * need not match <code>File.separatorChar</code>.
  657. * <p>
  658. * When a pattern ends with a '/' or '\', "**" is appended.
  659. *
  660. * @param includes A list of include patterns.
  661. * May be <code>null</code>, indicating that all files
  662. * should be included. If a non-<code>null</code>
  663. * list is given, all elements must be
  664. * non-<code>null</code>.
  665. */
  666. @Override
  667. public synchronized void setIncludes(final String[] includes) {
  668. if (includes == null) {
  669. this.includes = null;
  670. } else {
  671. this.includes = Stream.of(includes)
  672. .map(DirectoryScanner::normalizePattern).toArray(String[]::new);
  673. }
  674. }
  675. /**
  676. * Set the list of exclude patterns to use. All '/' and '\' characters
  677. * are replaced by <code>File.separatorChar</code>, so the separator used
  678. * need not match <code>File.separatorChar</code>.
  679. * <p>
  680. * When a pattern ends with a '/' or '\', "**" is appended.
  681. *
  682. * @param excludes A list of exclude patterns.
  683. * May be <code>null</code>, indicating that no files
  684. * should be excluded. If a non-<code>null</code> list is
  685. * given, all elements must be non-<code>null</code>.
  686. */
  687. @Override
  688. public synchronized void setExcludes(final String[] excludes) {
  689. if (excludes == null) {
  690. this.excludes = null;
  691. } else {
  692. this.excludes = Stream.of(excludes).map(DirectoryScanner::normalizePattern)
  693. .toArray(String[]::new);
  694. }
  695. }
  696. /**
  697. * Add to the list of exclude patterns to use. All '/' and '\'
  698. * characters are replaced by <code>File.separatorChar</code>, so
  699. * the separator used need not match <code>File.separatorChar</code>.
  700. * <p>
  701. * When a pattern ends with a '/' or '\', "**" is appended.
  702. *
  703. * @param excludes A list of exclude patterns.
  704. * May be <code>null</code>, in which case the
  705. * exclude patterns don't get changed at all.
  706. *
  707. * @since Ant 1.6.3
  708. */
  709. public synchronized void addExcludes(final String[] excludes) {
  710. if (excludes != null && excludes.length > 0) {
  711. if (this.excludes == null || this.excludes.length == 0) {
  712. setExcludes(excludes);
  713. } else {
  714. this.excludes = Stream.concat(Stream.of(this.excludes),
  715. Stream.of(excludes).map(DirectoryScanner::normalizePattern))
  716. .toArray(String[]::new);
  717. }
  718. }
  719. }
  720. /**
  721. * All '/' and '\' characters are replaced by
  722. * <code>File.separatorChar</code>, so the separator used need not
  723. * match <code>File.separatorChar</code>.
  724. *
  725. * <p>When a pattern ends with a '/' or '\', "**" is appended.</p>
  726. *
  727. * @since Ant 1.6.3
  728. */
  729. private static String normalizePattern(final String p) {
  730. String pattern = p.replace('/', File.separatorChar)
  731. .replace('\\', File.separatorChar);
  732. if (pattern.endsWith(File.separator)) {
  733. pattern += SelectorUtils.DEEP_TREE_MATCH;
  734. }
  735. return pattern;
  736. }
  737. /**
  738. * Set the selectors that will select the filelist.
  739. *
  740. * @param selectors specifies the selectors to be invoked on a scan.
  741. */
  742. @Override
  743. public synchronized void setSelectors(final FileSelector[] selectors) {
  744. this.selectors = selectors;
  745. }
  746. /**
  747. * Return whether or not the scanner has included all the files or
  748. * directories it has come across so far.
  749. *
  750. * @return <code>true</code> if all files and directories which have
  751. * been found so far have been included.
  752. */
  753. public synchronized boolean isEverythingIncluded() {
  754. return everythingIncluded;
  755. }
  756. /**
  757. * Scan for files which match at least one include pattern and don't match
  758. * any exclude patterns. If there are selectors then the files must pass
  759. * muster there, as well. Scans under basedir, if set; otherwise the
  760. * include patterns without leading wildcards specify the absolute paths of
  761. * the files that may be included.
  762. *
  763. * @exception IllegalStateException if the base directory was set
  764. * incorrectly (i.e. if it doesn't exist or isn't a directory).
  765. */
  766. @Override
  767. public void scan() throws IllegalStateException {
  768. synchronized (scanLock) {
  769. if (scanning) {
  770. while (scanning) {
  771. try {
  772. scanLock.wait();
  773. } catch (final InterruptedException ignored) {
  774. }
  775. }
  776. if (illegal != null) {
  777. throw illegal;
  778. }
  779. return;
  780. }
  781. scanning = true;
  782. }
  783. final File savedBase = basedir;
  784. try {
  785. synchronized (this) {
  786. illegal = null;
  787. clearResults();
  788. // set in/excludes to reasonable defaults if needed:
  789. final boolean nullIncludes = includes == null;
  790. includes = nullIncludes ? new String[] {SelectorUtils.DEEP_TREE_MATCH} : includes;
  791. final boolean nullExcludes = excludes == null;
  792. excludes = nullExcludes ? new String[0] : excludes;
  793. if (basedir != null && !followSymlinks
  794. && Files.isSymbolicLink(basedir.toPath())) {
  795. notFollowedSymlinks.add(basedir.getAbsolutePath());
  796. basedir = null;
  797. }
  798. if (basedir == null) {
  799. // if no basedir and no includes, nothing to do:
  800. if (nullIncludes) {
  801. return;
  802. }
  803. } else {
  804. if (!basedir.exists()) {
  805. if (errorOnMissingDir) {
  806. illegal = new IllegalStateException("basedir "
  807. + basedir
  808. + DOES_NOT_EXIST_POSTFIX);
  809. } else {
  810. // Nothing to do - basedir does not exist
  811. return;
  812. }
  813. } else if (!basedir.isDirectory()) {
  814. illegal = new IllegalStateException("basedir "
  815. + basedir
  816. + " is not a directory.");
  817. }
  818. if (illegal != null) {
  819. throw illegal;
  820. }
  821. }
  822. if (isIncluded(TokenizedPath.EMPTY_PATH)) {
  823. if (isExcluded(TokenizedPath.EMPTY_PATH)) {
  824. dirsExcluded.addElement("");
  825. } else if (isSelected("", basedir)) {
  826. dirsIncluded.addElement("");
  827. } else {
  828. dirsDeselected.addElement("");
  829. }
  830. } else {
  831. dirsNotIncluded.addElement("");
  832. }
  833. checkIncludePatterns();
  834. clearCaches();
  835. includes = nullIncludes ? null : includes;
  836. excludes = nullExcludes ? null : excludes;
  837. }
  838. } finally {
  839. basedir = savedBase;
  840. synchronized (scanLock) {
  841. scanning = false;
  842. scanLock.notifyAll();
  843. }
  844. }
  845. }
  846. /**
  847. * This routine is actually checking all the include patterns in
  848. * order to avoid scanning everything under base dir.
  849. * @since Ant 1.6
  850. */
  851. private void checkIncludePatterns() {
  852. ensureNonPatternSetsReady();
  853. final Map<TokenizedPath, String> newroots = new HashMap<>();
  854. // put in the newroots map the include patterns without
  855. // wildcard tokens
  856. for (TokenizedPattern includePattern : includePatterns) {
  857. final String pattern = includePattern.toString();
  858. if (!shouldSkipPattern(pattern)) {
  859. newroots.put(includePattern.rtrimWildcardTokens(), pattern);
  860. }
  861. }
  862. for (final Map.Entry<String, TokenizedPath> entry : includeNonPatterns
  863. .entrySet()) {
  864. final String pattern = entry.getKey();
  865. if (!shouldSkipPattern(pattern)) {
  866. newroots.put(entry.getValue(), pattern);
  867. }
  868. }
  869. if (newroots.containsKey(TokenizedPath.EMPTY_PATH)
  870. && basedir != null) {
  871. // we are going to scan everything anyway
  872. scandir(basedir, "", true);
  873. } else {
  874. File canonBase = null;
  875. if (basedir != null) {
  876. try {
  877. canonBase = basedir.getCanonicalFile();
  878. } catch (final IOException ex) {
  879. throw new BuildException(ex);
  880. }
  881. }
  882. // only scan directories that can include matched files or
  883. // directories
  884. for (final Map.Entry<TokenizedPath, String> entry : newroots.entrySet()) {
  885. TokenizedPath currentPath = entry.getKey();
  886. String currentelement = currentPath.toString();
  887. if (basedir == null && !FileUtils.isAbsolutePath(currentelement)) {
  888. continue;
  889. }
  890. File myfile = new File(basedir, currentelement);
  891. if (myfile.exists()) {
  892. // may be on a case insensitive file system. We want
  893. // the results to show what's really on the disk, so
  894. // we need to double check.
  895. try {
  896. final String path = (basedir == null)
  897. ? myfile.getCanonicalPath()
  898. : FILE_UTILS.removeLeadingPath(canonBase,
  899. myfile.getCanonicalFile());
  900. if (!path.equals(currentelement) || ON_VMS) {
  901. myfile = currentPath.findFile(basedir, true);
  902. if (myfile != null && basedir != null) {
  903. currentelement = FILE_UTILS.removeLeadingPath(
  904. basedir, myfile);
  905. if (!currentPath.toString().equals(currentelement)) {
  906. currentPath = new TokenizedPath(currentelement);
  907. }
  908. }
  909. }
  910. } catch (final IOException ex) {
  911. throw new BuildException(ex);
  912. }
  913. }
  914. if ((myfile == null || !myfile.exists()) && !isCaseSensitive()) {
  915. final File f = currentPath.findFile(basedir, false);
  916. if (f != null && f.exists()) {
  917. // adapt currentelement to the case we've
  918. // actually found
  919. currentelement = (basedir == null)
  920. ? f.getAbsolutePath()
  921. : FILE_UTILS.removeLeadingPath(basedir, f);
  922. myfile = f;
  923. currentPath = new TokenizedPath(currentelement);
  924. }
  925. }
  926. if (myfile != null && myfile.exists()) {
  927. if (!followSymlinks && currentPath.isSymlink(basedir)) {
  928. accountForNotFollowedSymlink(currentPath, myfile);
  929. continue;
  930. }
  931. if (myfile.isDirectory()) {
  932. if (isIncluded(currentPath)
  933. && currentelement.length() > 0) {
  934. accountForIncludedDir(currentPath, myfile, true);
  935. } else {
  936. scandir(myfile, currentPath, true);
  937. }
  938. } else if (myfile.isFile()) {
  939. final String originalpattern = entry.getValue();
  940. final boolean included = isCaseSensitive()
  941. ? originalpattern.equals(currentelement)
  942. : originalpattern.equalsIgnoreCase(currentelement);
  943. if (included) {
  944. accountForIncludedFile(currentPath, myfile);
  945. }
  946. }
  947. }
  948. }
  949. }
  950. }
  951. /**
  952. * true if the pattern specifies a relative path without basedir
  953. * or an absolute path not inside basedir.
  954. *
  955. * @since Ant 1.8.0
  956. */
  957. private boolean shouldSkipPattern(final String pattern) {
  958. if (FileUtils.isAbsolutePath(pattern)) {
  959. //skip abs. paths not under basedir, if set:
  960. return !(basedir == null || SelectorUtils.matchPatternStart(pattern,
  961. basedir.getAbsolutePath(), isCaseSensitive()));
  962. }
  963. return basedir == null;
  964. }
  965. /**
  966. * Clear the result caches for a scan.
  967. */
  968. protected synchronized void clearResults() {
  969. filesIncluded = new VectorSet<>();
  970. filesNotIncluded = new VectorSet<>();
  971. filesExcluded = new VectorSet<>();
  972. filesDeselected = new VectorSet<>();
  973. dirsIncluded = new VectorSet<>();
  974. dirsNotIncluded = new VectorSet<>();
  975. dirsExcluded = new VectorSet<>();
  976. dirsDeselected = new VectorSet<>();
  977. everythingIncluded = (basedir != null);
  978. scannedDirs.clear();
  979. notFollowedSymlinks.clear();
  980. }
  981. /**
  982. * Top level invocation for a slow scan. A slow scan builds up a full
  983. * list of excluded/included files/directories, whereas a fast scan
  984. * will only have full results for included files, as it ignores
  985. * directories which can't possibly hold any included files/directories.
  986. * <p>
  987. * Returns immediately if a slow scan has already been completed.
  988. */
  989. protected void slowScan() {
  990. synchronized (slowScanLock) {
  991. if (haveSlowResults) {
  992. return;
  993. }
  994. if (slowScanning) {
  995. while (slowScanning) {
  996. try {
  997. slowScanLock.wait();
  998. } catch (final InterruptedException e) {
  999. // Empty
  1000. }
  1001. }
  1002. return;
  1003. }
  1004. slowScanning = true;
  1005. }
  1006. try {
  1007. synchronized (this) {
  1008. // set in/excludes to reasonable defaults if needed:
  1009. final boolean nullIncludes = (includes == null);
  1010. includes = nullIncludes ? new String[] {SelectorUtils.DEEP_TREE_MATCH} : includes;
  1011. final boolean nullExcludes = (excludes == null);
  1012. excludes = nullExcludes ? new String[0] : excludes;
  1013. final String[] excl = new String[dirsExcluded.size()];
  1014. dirsExcluded.copyInto(excl);
  1015. final String[] notIncl = new String[dirsNotIncluded.size()];
  1016. dirsNotIncluded.copyInto(notIncl);
  1017. ensureNonPatternSetsReady();
  1018. processSlowScan(excl);
  1019. processSlowScan(notIncl);
  1020. clearCaches();
  1021. includes = nullIncludes ? null : includes;
  1022. excludes = nullExcludes ? null : excludes;
  1023. }
  1024. } finally {
  1025. synchronized (slowScanLock) {
  1026. haveSlowResults = true;
  1027. slowScanning = false;
  1028. slowScanLock.notifyAll();
  1029. }
  1030. }
  1031. }
  1032. private void processSlowScan(final String[] arr) {
  1033. for (String element : arr) {
  1034. final TokenizedPath path = new TokenizedPath(element);
  1035. if (!couldHoldIncluded(path) || contentsExcluded(path)) {
  1036. scandir(new File(basedir, element), path, false);
  1037. }
  1038. }
  1039. }
  1040. /**
  1041. * Scan the given directory for files and directories. Found files and
  1042. * directories are placed in their respective collections, based on the
  1043. * matching of includes, excludes, and the selectors. When a directory
  1044. * is found, it is scanned recursively.
  1045. *
  1046. * @param dir The directory to scan. Must not be <code>null</code>.
  1047. * @param vpath The path relative to the base directory (needed to
  1048. * prevent problems with an absolute path when using
  1049. * dir). Must not be <code>null</code>.
  1050. * @param fast Whether or not this call is part of a fast scan.
  1051. *
  1052. * @see #filesIncluded
  1053. * @see #filesNotIncluded
  1054. * @see #filesExcluded
  1055. * @see #dirsIncluded
  1056. * @see #dirsNotIncluded
  1057. * @see #dirsExcluded
  1058. * @see #slowScan
  1059. */
  1060. protected void scandir(final File dir, final String vpath, final boolean fast) {
  1061. scandir(dir, new TokenizedPath(vpath), fast);
  1062. }
  1063. /**
  1064. * Scan the given directory for files and directories. Found files and
  1065. * directories are placed in their respective collections, based on the
  1066. * matching of includes, excludes, and the selectors. When a directory
  1067. * is found, it is scanned recursively.
  1068. *
  1069. * @param dir The directory to scan. Must not be <code>null</code>.
  1070. * @param path The path relative to the base directory (needed to
  1071. * prevent problems with an absolute path when using
  1072. * dir). Must not be <code>null</code>.
  1073. * @param fast Whether or not this call is part of a fast scan.
  1074. *
  1075. * @see #filesIncluded
  1076. * @see #filesNotIncluded
  1077. * @see #filesExcluded
  1078. * @see #dirsIncluded
  1079. * @see #dirsNotIncluded
  1080. * @see #dirsExcluded
  1081. * @see #slowScan
  1082. */
  1083. private void scandir(final File dir, final TokenizedPath path, final boolean fast) {
  1084. if (dir == null) {
  1085. throw new BuildException("dir must not be null.");
  1086. }
  1087. final String[] newfiles = dir.list();
  1088. if (newfiles == null) {
  1089. if (!dir.exists()) {
  1090. throw new BuildException(dir + DOES_NOT_EXIST_POSTFIX);
  1091. } else if (!dir.isDirectory()) {
  1092. throw new BuildException("%s is not a directory.", dir);
  1093. } else {
  1094. throw new BuildException("IO error scanning directory '%s'",
  1095. dir.getAbsolutePath());
  1096. }
  1097. }
  1098. scandir(dir, path, fast, newfiles, new LinkedList<>());
  1099. }
  1100. private void scandir(final File dir, final TokenizedPath path, final boolean fast,
  1101. String[] newFiles, final Deque<String> directoryNamesFollowed) {
  1102. String vpath = path.toString();
  1103. if (vpath.length() > 0 && !vpath.endsWith(File.separator)) {
  1104. vpath += File.separator;
  1105. }
  1106. // avoid double scanning of directories, can only happen in fast mode
  1107. if (fast && hasBeenScanned(vpath)) {
  1108. return;
  1109. }
  1110. if (!followSymlinks) {
  1111. final ArrayList<String> noLinks = new ArrayList<>();
  1112. for (final String newFile : newFiles) {
  1113. final Path filePath;
  1114. if (dir == null) {
  1115. filePath = Paths.get(newFile);
  1116. } else {
  1117. filePath = Paths.get(dir.toPath().toString(), newFile);
  1118. }
  1119. if (Files.isSymbolicLink(filePath)) {
  1120. final String name = vpath + newFile;
  1121. final File file = new File(dir, newFile);
  1122. if (file.isDirectory()) {
  1123. dirsExcluded.addElement(name);
  1124. } else if (file.isFile()) {
  1125. filesExcluded.addElement(name);
  1126. }
  1127. accountForNotFollowedSymlink(name, file);
  1128. } else {
  1129. noLinks.add(newFile);
  1130. }
  1131. }
  1132. newFiles = noLinks.toArray(new String[noLinks.size()]);
  1133. } else {
  1134. directoryNamesFollowed.addFirst(dir.getName());
  1135. }
  1136. for (String newFile : newFiles) {
  1137. final String name = vpath + newFile;
  1138. final TokenizedPath newPath = new TokenizedPath(path, newFile);
  1139. final File file = new File(dir, newFile);
  1140. final String[] children = file.list();
  1141. if (children == null || (children.length == 0 && file.isFile())) {
  1142. if (isIncluded(newPath)) {
  1143. accountForIncludedFile(newPath, file);
  1144. } else {
  1145. everythingIncluded = false;
  1146. filesNotIncluded.addElement(name);
  1147. }
  1148. } else if (file.isDirectory()) { // dir
  1149. if (followSymlinks
  1150. && causesIllegalSymlinkLoop(newFile, dir, directoryNamesFollowed)) {
  1151. // will be caught and redirected to Ant's logging system
  1152. System.err.println("skipping symbolic link "
  1153. + file.getAbsolutePath()
  1154. + " -- too many levels of symbolic"
  1155. + " links.");
  1156. notFollowedSymlinks.add(file.getAbsolutePath());
  1157. continue;
  1158. }
  1159. if (isIncluded(newPath)) {
  1160. accountForIncludedDir(newPath, file, fast, children,
  1161. directoryNamesFollowed);
  1162. } else {
  1163. everythingIncluded = false;
  1164. dirsNotIncluded.addElement(name);
  1165. if (fast && couldHoldIncluded(newPath) && !contentsExcluded(newPath)) {
  1166. scandir(file, newPath, fast, children, directoryNamesFollowed);
  1167. }
  1168. }
  1169. if (!fast) {
  1170. scandir(file, newPath, fast, children, directoryNamesFollowed);
  1171. }
  1172. }
  1173. }
  1174. if (followSymlinks) {
  1175. directoryNamesFollowed.removeFirst();
  1176. }
  1177. }
  1178. /**
  1179. * Process included file.
  1180. * @param name path of the file relative to the directory of the FileSet.
  1181. * @param file included File.
  1182. */
  1183. private void accountForIncludedFile(final TokenizedPath name, final File file) {
  1184. processIncluded(name, file, filesIncluded, filesExcluded,
  1185. filesDeselected);
  1186. }
  1187. /**
  1188. * Process included directory.
  1189. * @param name path of the directory relative to the directory of
  1190. * the FileSet.
  1191. * @param file directory as File.
  1192. * @param fast whether to perform fast scans.
  1193. */
  1194. private void accountForIncludedDir(final TokenizedPath name, final File file,
  1195. final boolean fast) {
  1196. processIncluded(name, file, dirsIncluded, dirsExcluded, dirsDeselected);
  1197. if (fast && couldHoldIncluded(name) && !contentsExcluded(name)) {
  1198. scandir(file, name, fast);
  1199. }
  1200. }
  1201. private void accountForIncludedDir(final TokenizedPath name,
  1202. final File file, final boolean fast,
  1203. final String[] children,
  1204. final Deque<String> directoryNamesFollowed) {
  1205. processIncluded(name, file, dirsIncluded, dirsExcluded, dirsDeselected);
  1206. if (fast && couldHoldIncluded(name) && !contentsExcluded(name)) {
  1207. scandir(file, name, fast, children, directoryNamesFollowed);
  1208. }
  1209. }
  1210. private void accountForNotFollowedSymlink(final String name, final File file) {
  1211. accountForNotFollowedSymlink(new TokenizedPath(name), file);
  1212. }
  1213. private void accountForNotFollowedSymlink(final TokenizedPath name, final File file) {
  1214. if (!isExcluded(name) && (isIncluded(name)
  1215. || (file.isDirectory() && couldHoldIncluded(name) && !contentsExcluded(name)))) {
  1216. notFollowedSymlinks.add(file.getAbsolutePath());
  1217. }
  1218. }
  1219. private void processIncluded(final TokenizedPath path,
  1220. final File file, final List<String> inc, final List<String> exc,
  1221. final List<String> des) {
  1222. final String name = path.toString();
  1223. if (inc.contains(name) || exc.contains(name) || des.contains(name)) {
  1224. return;
  1225. }
  1226. boolean included = false;
  1227. if (isExcluded(path)) {
  1228. exc.add(name);
  1229. } else if (isSelected(name, file)) {
  1230. included = true;
  1231. inc.add(name);
  1232. } else {
  1233. des.add(name);
  1234. }
  1235. everythingIncluded &= included;
  1236. }
  1237. /**
  1238. * Test whether or not a name matches against at least one include
  1239. * pattern.
  1240. *
  1241. * @param name The path to match. Must not be <code>null</code>.
  1242. * @return <code>true</code> when the name matches against at least one
  1243. * include pattern, or <code>false</code> otherwise.
  1244. */
  1245. protected boolean isIncluded(final String name) {
  1246. return isIncluded(new TokenizedPath(name));
  1247. }
  1248. /**
  1249. * Test whether or not a name matches against at least one include
  1250. * pattern.
  1251. *
  1252. * @param path The tokenized path to match. Must not be <code>null</code>.
  1253. * @return <code>true</code> when the name matches against at least one
  1254. * include pattern, or <code>false</code> otherwise.
  1255. */
  1256. private boolean isIncluded(final TokenizedPath path) {
  1257. ensureNonPatternSetsReady();
  1258. String toMatch = path.toString();
  1259. if (!isCaseSensitive()) {
  1260. toMatch = toMatch.toUpperCase();
  1261. }
  1262. return includeNonPatterns.containsKey(toMatch)
  1263. || Stream.of(includePatterns).anyMatch(p -> p.matchPath(path, isCaseSensitive()));
  1264. }
  1265. /**
  1266. * Test whether or not a name matches the start of at least one include
  1267. * pattern.
  1268. *
  1269. * @param name The name to match. Must not be <code>null</code>.
  1270. * @return <code>true</code> when the name matches against the start of at
  1271. * least one include pattern, or <code>false</code> otherwise.
  1272. */
  1273. protected boolean couldHoldIncluded(final String name) {
  1274. return couldHoldIncluded(new TokenizedPath(name));
  1275. }
  1276. /**
  1277. * Test whether or not a name matches the start of at least one include
  1278. * pattern.
  1279. *
  1280. * @param tokenizedName The name to match. Must not be <code>null</code>.
  1281. * @return <code>true</code> when the name matches against the start of at
  1282. * least one include pattern, or <code>false</code> otherwise.
  1283. */
  1284. private boolean couldHoldIncluded(final TokenizedPath tokenizedName) {
  1285. return Stream.concat(Stream.of(includePatterns),
  1286. includeNonPatterns.values().stream().map(TokenizedPath::toPattern))
  1287. .anyMatch(pat -> couldHoldIncluded(tokenizedName, pat));
  1288. }
  1289. /**
  1290. * Test whether or not a name matches the start of the given
  1291. * include pattern.
  1292. *
  1293. * @param tokenizedName The name to match. Must not be <code>null</code>.
  1294. * @return <code>true</code> when the name matches against the start of the
  1295. * include pattern, or <code>false</code> otherwise.
  1296. */
  1297. private boolean couldHoldIncluded(final TokenizedPath tokenizedName,
  1298. final TokenizedPattern tokenizedInclude) {
  1299. return tokenizedInclude.matchStartOf(tokenizedName, isCaseSensitive())
  1300. && isMorePowerfulThanExcludes(tokenizedName.toString())
  1301. && isDeeper(tokenizedInclude, tokenizedName);
  1302. }
  1303. /**
  1304. * Verify that a pattern specifies files deeper
  1305. * than the level of the specified file.
  1306. * @param pattern the pattern to check.
  1307. * @param name the name to check.
  1308. * @return whether the pattern is deeper than the name.
  1309. * @since Ant 1.6.3
  1310. */
  1311. private boolean isDeeper(final TokenizedPattern pattern, final TokenizedPath name) {
  1312. return pattern.containsPattern(SelectorUtils.DEEP_TREE_MATCH)
  1313. || pattern.depth() > name.depth();
  1314. }
  1315. /**
  1316. * Find out whether one particular include pattern is more powerful
  1317. * than all the excludes.
  1318. * Note: the power comparison is based on the length of the include pattern
  1319. * and of the exclude patterns without the wildcards.
  1320. * Ideally the comparison should be done based on the depth
  1321. * of the match; that is to say how many file separators have been matched
  1322. * before the first ** or the end of the pattern.
  1323. *
  1324. * IMPORTANT : this function should return false "with care".
  1325. *
  1326. * @param name the relative path to test.
  1327. * @return true if there is no exclude pattern more powerful than
  1328. * this include pattern.
  1329. * @since Ant 1.6
  1330. */
  1331. private boolean isMorePowerfulThanExcludes(final String name) {
  1332. final String soughtexclude = name + File.separatorChar + SelectorUtils.DEEP_TREE_MATCH;
  1333. return Stream.of(excludePatterns).map(Object::toString)
  1334. .noneMatch(Predicate.isEqual(soughtexclude));
  1335. }
  1336. /**
  1337. * Test whether all contents of the specified directory must be excluded.
  1338. * @param path the path to check.
  1339. * @return whether all the specified directory's contents are excluded.
  1340. */
  1341. /* package */ boolean contentsExcluded(final TokenizedPath path) {
  1342. return Stream.of(excludePatterns)
  1343. .filter(p -> p.endsWith(SelectorUtils.DEEP_TREE_MATCH))
  1344. .map(TokenizedPattern::withoutLastToken)
  1345. .anyMatch(wlt -> wlt.matchPath(path, isCaseSensitive()));
  1346. }
  1347. /**
  1348. * Test whether or not a name matches against at least one exclude
  1349. * pattern.
  1350. *
  1351. * @param name The name to match. Must not be <code>null</code>.
  1352. * @return <code>true</code> when the name matches against at least one
  1353. * exclude pattern, or <code>false</code> otherwise.
  1354. */
  1355. protected boolean isExcluded(final String name) {
  1356. return isExcluded(new TokenizedPath(name));
  1357. }
  1358. /**
  1359. * Test whether or not a name matches against at least one exclude
  1360. * pattern.
  1361. *
  1362. * @param name The name to match. Must not be <code>null</code>.
  1363. * @return <code>true</code> when the name matches against at least one
  1364. * exclude pattern, or <code>false</code> otherwise.
  1365. */
  1366. private boolean isExcluded(final TokenizedPath name) {
  1367. ensureNonPatternSetsReady();
  1368. String toMatch = name.toString();
  1369. if (!isCaseSensitive()) {
  1370. toMatch = toMatch.toUpperCase();
  1371. }
  1372. return excludeNonPatterns.containsKey(toMatch)
  1373. || Stream.of(excludePatterns).anyMatch(p -> p.matchPath(name, isCaseSensitive()));
  1374. }
  1375. /**
  1376. * Test whether a file should be selected.
  1377. *
  1378. * @param name the filename to check for selecting.
  1379. * @param file the java.io.File object for this filename.
  1380. * @return <code>false</code> when the selectors says that the file
  1381. * should not be selected, <code>true</code> otherwise.
  1382. */
  1383. protected boolean isSelected(final String name, final File file) {
  1384. return selectors == null
  1385. || Stream.of(selectors).allMatch(sel -> sel.isSelected(basedir, name, file));
  1386. }
  1387. /**
  1388. * Return the names of the files which matched at least one of the
  1389. * include patterns and none of the exclude patterns.
  1390. * The names are relative to the base directory.
  1391. *
  1392. * @return the names of the files which matched at least one of the
  1393. * include patterns and none of the exclude patterns.
  1394. */
  1395. @Override
  1396. public String[] getIncludedFiles() {
  1397. String[] files;
  1398. synchronized (this) {
  1399. if (filesIncluded == null) {
  1400. throw new IllegalStateException("Must call scan() first");
  1401. }
  1402. files = filesIncluded.toArray(new String[filesIncluded.size()]);
  1403. }
  1404. Arrays.sort(files);
  1405. return files;
  1406. }
  1407. /**
  1408. * Return the count of included files.
  1409. * @return <code>int</code>.
  1410. * @since Ant 1.6.3
  1411. */
  1412. public synchronized int getIncludedFilesCount() {
  1413. if (filesIncluded == null) {
  1414. throw new IllegalStateException("Must call scan() first");
  1415. }
  1416. return filesIncluded.size();
  1417. }
  1418. /**
  1419. * Return the names of the files which matched none of the include
  1420. * patterns. The names are relative to the base directory. This involves
  1421. * performing a slow scan if one has not already been completed.
  1422. *
  1423. * @return the names of the files which matched none of the include
  1424. * patterns.
  1425. *
  1426. * @see #slowScan
  1427. */
  1428. @Override
  1429. public synchronized String[] getNotIncludedFiles() {
  1430. slowScan();
  1431. return filesNotIncluded.toArray(new String[filesNotIncluded.size()]);
  1432. }
  1433. /**
  1434. * Return the names of the files which matched at least one of the
  1435. * include patterns and at least one of the exclude patterns.
  1436. * The names are relative to the base directory. This involves
  1437. * performing a slow scan if one has not already been completed.
  1438. *
  1439. * @return the names of the files which matched at least one of the
  1440. * include patterns and at least one of the exclude patterns.
  1441. *
  1442. * @see #slowScan
  1443. */
  1444. @Override
  1445. public synchronized String[] getExcludedFiles() {
  1446. slowScan();
  1447. return filesExcluded.toArray(new String[filesExcluded.size()]);
  1448. }
  1449. /**
  1450. * <p>Return the names of the files which were selected out and
  1451. * therefore not ultimately included.</p>
  1452. *
  1453. * <p>The names are relative to the base directory. This involves
  1454. * performing a slow scan if one has not already been completed.</p>
  1455. *
  1456. * @return the names of the files which were deselected.
  1457. *
  1458. * @see #slowScan
  1459. */
  1460. @Override
  1461. public synchronized String[] getDeselectedFiles() {
  1462. slowScan();
  1463. return filesDeselected.toArray(new String[filesDeselected.size()]);
  1464. }
  1465. /**
  1466. * Return the names of the directories which matched at least one of the
  1467. * include patterns and none of the exclude patterns.
  1468. * The names are relative to the base directory.
  1469. *
  1470. * @return the names of the directories which matched at least one of the
  1471. * include patterns and none of the exclude patterns.
  1472. */
  1473. @Override
  1474. public String[] getIncludedDirectories() {
  1475. String[] directories;
  1476. synchronized (this) {
  1477. if (dirsIncluded == null) {
  1478. throw new IllegalStateException("Must call scan() first");
  1479. }
  1480. directories = dirsIncluded.toArray(new String[dirsIncluded.size()]);
  1481. }
  1482. Arrays.sort(directories);
  1483. return directories;
  1484. }
  1485. /**
  1486. * Return the count of included directories.
  1487. * @return <code>int</code>.
  1488. * @since Ant 1.6.3
  1489. */
  1490. public synchronized int getIncludedDirsCount() {
  1491. if (dirsIncluded == null) {
  1492. throw new IllegalStateException("Must call scan() first");
  1493. }
  1494. return dirsIncluded.size();
  1495. }
  1496. /**
  1497. * Return the names of the directories which matched none of the include
  1498. * patterns. The names are relative to the base directory. This involves
  1499. * performing a slow scan if one has not already been completed.
  1500. *
  1501. * @return the names of the directories which matched none of the include
  1502. * patterns.
  1503. *
  1504. * @see #slowScan
  1505. */
  1506. @Override
  1507. public synchronized String[] getNotIncludedDirectories() {
  1508. slowScan();
  1509. return dirsNotIncluded.toArray(new String[dirsNotIncluded.size()]);
  1510. }
  1511. /**
  1512. * Return the names of the directories which matched at least one of the
  1513. * include patterns and at least one of the exclude patterns.
  1514. * The names are relative to the base directory. This involves
  1515. * performing a slow scan if one has not already been completed.
  1516. *
  1517. * @return the names of the directories which matched at least one of the
  1518. * include patterns and at least one of the exclude patterns.
  1519. *
  1520. * @see #slowScan
  1521. */
  1522. @Override
  1523. public synchronized String[] getExcludedDirectories() {
  1524. slowScan();
  1525. return dirsExcluded.toArray(new String[dirsExcluded.size()]);
  1526. }
  1527. /**
  1528. * <p>Return the names of the directories which were selected out and
  1529. * therefore not ultimately included.</p>
  1530. *
  1531. * <p>The names are relative to the base directory. This involves
  1532. * performing a slow scan if one has not already been completed.</p>
  1533. *
  1534. * @return the names of the directories which were deselected.
  1535. *
  1536. * @see #slowScan
  1537. */
  1538. @Override
  1539. public synchronized String[] getDeselectedDirectories() {
  1540. slowScan();
  1541. return dirsDeselected.toArray(new String[dirsDeselected.size()]);
  1542. }
  1543. /**
  1544. * Absolute paths of all symbolic links that haven't been followed
  1545. * but would have been followed had followsymlinks been true or
  1546. * maxLevelsOfSymlinks been bigger.
  1547. *
  1548. * @return sorted array of not followed symlinks
  1549. * @since Ant 1.8.0
  1550. * @see #notFollowedSymlinks
  1551. */
  1552. public synchronized String[] getNotFollowedSymlinks() {
  1553. String[] links;
  1554. synchronized (this) {
  1555. links = notFollowedSymlinks.toArray(new String[notFollowedSymlinks.size()]);
  1556. }
  1557. Arrays.sort(links);
  1558. return links;
  1559. }
  1560. /**
  1561. * Add default exclusions to the current exclusions set.
  1562. */
  1563. @Override
  1564. public synchronized void addDefaultExcludes() {
  1565. Stream<String> s = Stream.of(getDefaultExcludes()).map(p -> p.replace('/',
  1566. File.separatorChar).replace('\\', File.separatorChar));
  1567. if (excludes != null) {
  1568. s = Stream.concat(Stream.of(excludes), s);
  1569. }
  1570. excludes = s.toArray(String[]::new);
  1571. }
  1572. /**
  1573. * Get the named resource.
  1574. * @param name path name of the file relative to the dir attribute.
  1575. *
  1576. * @return the resource with the given name.
  1577. * @since Ant 1.5.2
  1578. */
  1579. @Override
  1580. public synchronized Resource getResource(final String name) {
  1581. return new FileResource(basedir, name);
  1582. }
  1583. /**
  1584. * Has the directory with the given path relative to the base
  1585. * directory already been scanned?
  1586. *
  1587. * <p>Registers the given directory as scanned as a side effect.</p>
  1588. *
  1589. * @since Ant 1.6
  1590. */
  1591. private boolean hasBeenScanned(final String vpath) {
  1592. return !scannedDirs.add(vpath);
  1593. }
  1594. /**
  1595. * This method is of interest for testing purposes. The returned
  1596. * Set is live and should not be modified.
  1597. * @return the Set of relative directory names that have been scanned.
  1598. */
  1599. /* package-private */ Set<String> getScannedDirs() {
  1600. return scannedDirs;
  1601. }
  1602. /**
  1603. * Clear internal caches.
  1604. *
  1605. * @since Ant 1.6
  1606. */
  1607. private synchronized void clearCaches() {
  1608. includeNonPatterns.clear();
  1609. excludeNonPatterns.clear();
  1610. includePatterns = null;
  1611. excludePatterns = null;
  1612. areNonPatternSetsReady = false;
  1613. }
  1614. /**
  1615. * Ensure that the in|exclude &quot;patterns&quot;
  1616. * have been properly divided up.
  1617. *
  1618. * @since Ant 1.6.3
  1619. */
  1620. /* package */ synchronized void ensureNonPatternSetsReady() {
  1621. if (!areNonPatternSetsReady) {
  1622. includePatterns = fillNonPatternSet(includeNonPatterns, includes);
  1623. excludePatterns = fillNonPatternSet(excludeNonPatterns, excludes);
  1624. areNonPatternSetsReady = true;
  1625. }
  1626. }
  1627. /**
  1628. * Add all patterns that are not real patterns (do not contain
  1629. * wildcards) to the set and returns the real patterns.
  1630. *
  1631. * @param map Map to populate.
  1632. * @param patterns String[] of patterns.
  1633. * @since Ant 1.8.0
  1634. */
  1635. private TokenizedPattern[] fillNonPatternSet(final Map<String, TokenizedPath> map,
  1636. final String[] patterns) {
  1637. final List<TokenizedPattern> al = new ArrayList<>(patterns.length);
  1638. for (String pattern : patterns) {
  1639. if (SelectorUtils.hasWildcards(pattern)) {
  1640. al.add(new TokenizedPattern(pattern));
  1641. } else {
  1642. final String s = isCaseSensitive() ? pattern : pattern.toUpperCase();
  1643. map.put(s, new TokenizedPath(s));
  1644. }
  1645. }
  1646. return al.toArray(new TokenizedPattern[al.size()]);
  1647. }
  1648. /**
  1649. * Would following the given directory cause a loop of symbolic
  1650. * links deeper than allowed?
  1651. *
  1652. * <p>Can only happen if the given directory has been seen at
  1653. * least more often than allowed during the current scan and it is
  1654. * a symbolic link and enough other occurrences of the same name
  1655. * higher up are symbolic links that point to the same place.</p>
  1656. *
  1657. * @since Ant 1.8.0
  1658. */
  1659. private boolean causesIllegalSymlinkLoop(final String dirName, final File parent,
  1660. final Deque<String> directoryNamesFollowed) {
  1661. try {
  1662. final Path dirPath;
  1663. if (parent == null) {
  1664. dirPath = Paths.get(dirName);
  1665. } else {
  1666. dirPath = Paths.get(parent.toPath().toString(), dirName);
  1667. }
  1668. if (directoryNamesFollowed.size() >= maxLevelsOfSymlinks
  1669. && Collections.frequency(directoryNamesFollowed, dirName) >= maxLevelsOfSymlinks
  1670. && Files.isSymbolicLink(dirPath)) {
  1671. final List<String> files = new ArrayList<>();
  1672. File f = FILE_UTILS.resolveFile(parent, dirName);
  1673. final String target = f.getCanonicalPath();
  1674. files.add(target);
  1675. StringBuilder relPath = new StringBuilder();
  1676. for (final String dir : directoryNamesFollowed) {
  1677. relPath.append("../");
  1678. if (dirName.equals(dir)) {
  1679. f = FILE_UTILS.resolveFile(parent, relPath + dir);
  1680. files.add(f.getCanonicalPath());
  1681. if (files.size() > maxLevelsOfSymlinks
  1682. && Collections.frequency(files, target) > maxLevelsOfSymlinks) {
  1683. return true;
  1684. }
  1685. }
  1686. }
  1687. }
  1688. return false;
  1689. } catch (final IOException ex) {
  1690. throw new BuildException(
  1691. "Caught error while checking for symbolic links", ex);
  1692. }
  1693. }
  1694. }