index.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. /*
  2. * Jake JavaScript build tool
  3. * Copyright 2112 Matthew Eernisse ([email protected])
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * 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. var fs = require('fs')
  19. , path = require('path')
  20. , minimatch = require('minimatch')
  21. , utils = require('utilities')
  22. , globSync;
  23. globSync = function (pat) {
  24. var dirname = utils.file.basedir(pat)
  25. , files
  26. , matches;
  27. try {
  28. files = utils.file.readdirR(dirname).map(function(file){
  29. return file.replace(/\\/g, '/');
  30. });
  31. }
  32. // Bail if path doesn't exist -- assume no files
  33. catch(e) {
  34. console.error(e.message);
  35. }
  36. if (files) {
  37. pat = path.normalize(pat);
  38. // Hack, Minimatch doesn't support backslashes in the pattern
  39. // https://github.com/isaacs/minimatch/issues/7
  40. pat = pat.replace(/\\/g, '/');
  41. matches = minimatch.match(files, pat, {});
  42. }
  43. return matches || [];
  44. };
  45. // Constants
  46. // ---------------
  47. // List of all the builtin Array methods we want to override
  48. var ARRAY_METHODS = Object.getOwnPropertyNames(Array.prototype)
  49. // Array methods that return a copy instead of affecting the original
  50. , SPECIAL_RETURN = {
  51. 'concat': true
  52. , 'slice': true
  53. , 'filter': true
  54. , 'map': true
  55. }
  56. // Default file-patterns we want to ignore
  57. , DEFAULT_IGNORE_PATTERNS = [
  58. /(^|[\/\\])CVS([\/\\]|$)/
  59. , /(^|[\/\\])\.svn([\/\\]|$)/
  60. , /(^|[\/\\])\.git([\/\\]|$)/
  61. , /\.bak$/
  62. , /~$/
  63. ]
  64. // Ignore core files
  65. , DEFAULT_IGNORE_FUNCS = [
  66. function (name) {
  67. var isDir = false
  68. , stats;
  69. try {
  70. stats = fs.statSync(name);
  71. isDir = stats.isDirectory();
  72. }
  73. catch(e) {}
  74. return (/(^|[\/\\])core$/).test(name) && !isDir;
  75. }
  76. ];
  77. var FileList = function () {
  78. var self = this
  79. , wrap;
  80. // List of glob-patterns or specific filenames
  81. this.pendingAdd = [];
  82. // Switched to false after lazy-eval of files
  83. this.pending = true;
  84. // Used to calculate exclusions from the list of files
  85. this.excludes = {
  86. pats: DEFAULT_IGNORE_PATTERNS.slice()
  87. , funcs: DEFAULT_IGNORE_FUNCS.slice()
  88. , regex: null
  89. };
  90. this.items = [];
  91. // Wrap the array methods with the delegates
  92. wrap = function (prop) {
  93. var arr;
  94. self[prop] = function () {
  95. if (self.pending) {
  96. self.resolve();
  97. }
  98. if (typeof self.items[prop] == 'function') {
  99. // Special method that return a copy
  100. if (SPECIAL_RETURN[prop]) {
  101. arr = self.items[prop].apply(self.items, arguments);
  102. return FileList.clone(self, arr);
  103. }
  104. else {
  105. return self.items[prop].apply(self.items, arguments);
  106. }
  107. }
  108. else {
  109. return self.items[prop];
  110. }
  111. };
  112. };
  113. for (var i = 0, ii = ARRAY_METHODS.length; i < ii; i++) {
  114. wrap(ARRAY_METHODS[i]);
  115. }
  116. // Include whatever files got passed to the constructor
  117. this.include.apply(this, arguments);
  118. // Fix constructor linkage
  119. this.constructor = FileList;
  120. };
  121. FileList.prototype = new (function () {
  122. var globPattern = /[*?\[\{]/;
  123. var _addMatching = function (pat) {
  124. var matches = globSync(pat);
  125. this.items = this.items.concat(matches);
  126. }
  127. , _resolveAdd = function (name) {
  128. if (globPattern.test(name)) {
  129. _addMatching.call(this, name);
  130. }
  131. else {
  132. this.push(name);
  133. }
  134. }
  135. , _calculateExcludeRe = function () {
  136. var pats = this.excludes.pats
  137. , pat
  138. , excl = []
  139. , matches = [];
  140. for (var i = 0, ii = pats.length; i < ii; i++) {
  141. pat = pats[i];
  142. if (typeof pat == 'string') {
  143. // Glob, look up files
  144. if (/[*?]/.test(pat)) {
  145. matches = globSync(pat);
  146. matches = matches.map(function (m) {
  147. return utils.string.escapeRegExpChars(m);
  148. });
  149. excl = excl.concat(matches);
  150. }
  151. // String for regex
  152. else {
  153. excl.push(utils.string.escapeRegExpChars(pat));
  154. }
  155. }
  156. // Regex, grab the string-representation
  157. else if (pat instanceof RegExp) {
  158. excl.push(pat.toString().replace(/^\/|\/$/g, ''));
  159. }
  160. }
  161. if (excl.length) {
  162. this.excludes.regex = new RegExp('(' + excl.join(')|(') + ')');
  163. }
  164. else {
  165. this.excludes.regex = /^$/;
  166. }
  167. }
  168. , _resolveExclude = function () {
  169. var self = this;
  170. _calculateExcludeRe.call(this);
  171. // No `reject` method, so use reverse-filter
  172. this.items = this.items.filter(function (name) {
  173. return !self.shouldExclude(name);
  174. });
  175. };
  176. /**
  177. * Includes file-patterns in the FileList. Should be called with one or more
  178. * pattern for finding file to include in the list. Arguments should be strings
  179. * for either a glob-pattern or a specific file-name, or an array of them
  180. */
  181. this.include = function (items) {
  182. if (items) {
  183. this.pendingAdd = this.pendingAdd.concat(items).filter(function (item) {
  184. return !!item;
  185. });
  186. }
  187. return this;
  188. };
  189. /**
  190. * Indicates whether a particular file would be filtered out by the current
  191. * exclusion rules for this FileList.
  192. * @param {String} name The filename to check
  193. * @return {Boolean} Whether or not the file should be excluded
  194. */
  195. this.shouldExclude = function (name) {
  196. if (!this.excludes.regex) {
  197. _calculateExcludeRe.call(this);
  198. }
  199. var excl = this.excludes;
  200. return excl.regex.test(name) || excl.funcs.some(function (f) {
  201. return !!f(name);
  202. });
  203. };
  204. /**
  205. * Excludes file-patterns from the FileList. Should be called with one or more
  206. * pattern for finding file to include in the list. Arguments can be:
  207. * 1. Strings for either a glob-pattern or a specific file-name
  208. * 2. Regular expression literals
  209. * 3. Functions to be run on the filename that return a true/false
  210. */
  211. this.exclude = function () {
  212. var args = Array.isArray(arguments[0]) ? arguments[0] : arguments
  213. , arg;
  214. for (var i = 0, ii = args.length; i < ii; i++) {
  215. arg = args[i];
  216. if (typeof arg == 'function' && !(arg instanceof RegExp)) {
  217. this.excludes.funcs.push(arg);
  218. }
  219. else {
  220. this.excludes.pats.push(arg);
  221. }
  222. }
  223. if (!this.pending) {
  224. _resolveExclude.call(this);
  225. }
  226. return this;
  227. };
  228. /**
  229. * Populates the FileList from the include/exclude rules with a list of
  230. * actual files
  231. */
  232. this.resolve = function () {
  233. var name
  234. , uniqueFunc = function (p, c) {
  235. if (p.indexOf(c) < 0) {
  236. p.push(c);
  237. }
  238. return p;
  239. };
  240. if (this.pending) {
  241. this.pending = false;
  242. while ((name = this.pendingAdd.shift())) {
  243. _resolveAdd.call(this, name);
  244. }
  245. // Reduce to a unique list
  246. this.items = this.items.reduce(uniqueFunc, []);
  247. // Remove exclusions
  248. _resolveExclude.call(this);
  249. }
  250. return this;
  251. };
  252. /**
  253. * Convert to a plain-jane array
  254. */
  255. this.toArray = function () {
  256. // Call slice to ensure lazy-resolution before slicing items
  257. var ret = this.slice().items.slice();
  258. return ret;
  259. };
  260. /**
  261. * Clear any pending items -- only useful before
  262. * calling `resolve`
  263. */
  264. this.clearInclusions = function () {
  265. this.pendingAdd = [];
  266. return this;
  267. };
  268. /**
  269. * Clear any current exclusion rules
  270. */
  271. this.clearExclusions = function () {
  272. this.excludes = {
  273. pats: []
  274. , funcs: []
  275. , regex: null
  276. };
  277. return this;
  278. };
  279. })();
  280. // Static method, used to create copy returned by special
  281. // array methods
  282. FileList.clone = function (list, items) {
  283. var clone = new FileList();
  284. if (items) {
  285. clone.items = items;
  286. }
  287. clone.pendingAdd = list.pendingAdd;
  288. clone.pending = list.pending;
  289. for (var p in list.excludes) {
  290. clone.excludes[p] = list.excludes[p];
  291. }
  292. return clone;
  293. };
  294. exports.FileList = FileList;