jake.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. /*
  2. * Jake JavaScript build tool
  3. * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
  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. if (!global.jake) {
  19. let EventEmitter = require('events').EventEmitter;
  20. // And so it begins
  21. global.jake = new EventEmitter();
  22. let fs = require('fs');
  23. let chalk = require('chalk');
  24. let taskNs = require('./task');
  25. let Task = taskNs.Task;
  26. let FileTask = taskNs.FileTask;
  27. let DirectoryTask = taskNs.DirectoryTask;
  28. let Rule = require('./rule').Rule;
  29. let Namespace = require('./namespace').Namespace;
  30. let RootNamespace = require('./namespace').RootNamespace;
  31. let api = require('./api');
  32. let utils = require('./utils');
  33. let Program = require('./program').Program;
  34. let loader = require('./loader')();
  35. let pkg = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString());
  36. const MAX_RULE_RECURSION_LEVEL = 16;
  37. // Globalize jake and top-level API methods (e.g., `task`, `desc`)
  38. Object.assign(global, api);
  39. // Copy utils onto base jake
  40. jake.logger = utils.logger;
  41. jake.exec = utils.exec;
  42. // File utils should be aliased directly on base jake as well
  43. Object.assign(jake, utils.file);
  44. // Also add top-level API methods to exported object for those who don't want to
  45. // use the globals (`file` here will overwrite the 'file' utils namespace)
  46. Object.assign(jake, api);
  47. Object.assign(jake, new (function () {
  48. this._invocationChain = [];
  49. this._taskTimeout = 30000;
  50. // Public properties
  51. // =================
  52. this.version = pkg.version;
  53. // Used when Jake exits with a specific error-code
  54. this.errorCode = null;
  55. // Loads Jakefiles/jakelibdirs
  56. this.loader = loader;
  57. // The root of all ... namespaces
  58. this.rootNamespace = new RootNamespace();
  59. // Non-namespaced tasks are placed into the default
  60. this.defaultNamespace = this.rootNamespace;
  61. // Start in the default
  62. this.currentNamespace = this.defaultNamespace;
  63. // Saves the description created by a 'desc' call that prefaces a
  64. // 'task' call that defines a task.
  65. this.currentTaskDescription = null;
  66. this.program = new Program();
  67. this.FileList = require('filelist').FileList;
  68. this.PackageTask = require('./package_task').PackageTask;
  69. this.PublishTask = require('./publish_task').PublishTask;
  70. this.TestTask = require('./test_task').TestTask;
  71. this.Task = Task;
  72. this.FileTask = FileTask;
  73. this.DirectoryTask = DirectoryTask;
  74. this.Namespace = Namespace;
  75. this.Rule = Rule;
  76. this.parseAllTasks = function () {
  77. let _parseNs = function (ns) {
  78. let nsTasks = ns.tasks;
  79. let nsNamespaces = ns.childNamespaces;
  80. for (let q in nsTasks) {
  81. let nsTask = nsTasks[q];
  82. jake.Task[nsTask.fullName] = nsTask;
  83. }
  84. for (let p in nsNamespaces) {
  85. let nsNamespace = nsNamespaces[p];
  86. _parseNs(nsNamespace);
  87. }
  88. };
  89. _parseNs(jake.defaultNamespace);
  90. };
  91. /**
  92. * Displays the list of descriptions avaliable for tasks defined in
  93. * a Jakefile
  94. */
  95. this.showAllTaskDescriptions = function (f) {
  96. let p;
  97. let maxTaskNameLength = 0;
  98. let task;
  99. let padding;
  100. let name;
  101. let descr;
  102. let filter = typeof f == 'string' ? f : null;
  103. for (p in jake.Task) {
  104. if (!Object.prototype.hasOwnProperty.call(jake.Task, p)) {
  105. continue;
  106. }
  107. if (filter && p.indexOf(filter) == -1) {
  108. continue;
  109. }
  110. task = jake.Task[p];
  111. // Record the length of the longest task name -- used for
  112. // pretty alignment of the task descriptions
  113. if (task.description) {
  114. maxTaskNameLength = p.length > maxTaskNameLength ?
  115. p.length : maxTaskNameLength;
  116. }
  117. }
  118. // Print out each entry with descriptions neatly aligned
  119. for (p in jake.Task) {
  120. if (!Object.prototype.hasOwnProperty.call(jake.Task, p)) {
  121. continue;
  122. }
  123. if (filter && p.indexOf(filter) == -1) {
  124. continue;
  125. }
  126. task = jake.Task[p];
  127. //name = '\033[32m' + p + '\033[39m ';
  128. name = chalk.green(p);
  129. descr = task.description;
  130. if (descr) {
  131. descr = chalk.gray('# ' + descr);
  132. // Create padding-string with calculated length
  133. padding = (new Array(maxTaskNameLength - p.length + 2)).join(' ');
  134. console.log('jake ' + name + padding + descr);
  135. }
  136. }
  137. };
  138. this.createTask = function () {
  139. let args = Array.prototype.slice.call(arguments);
  140. let arg;
  141. let obj;
  142. let task;
  143. let type;
  144. let name;
  145. let action;
  146. let opts = {};
  147. let prereqs = [];
  148. type = args.shift();
  149. // name, [deps], [action]
  150. // Name (string) + deps (array) format
  151. if (typeof args[0] == 'string') {
  152. name = args.shift();
  153. if (Array.isArray(args[0])) {
  154. prereqs = args.shift();
  155. }
  156. }
  157. // name:deps, [action]
  158. // Legacy object-literal syntax, e.g.: {'name': ['depA', 'depB']}
  159. else {
  160. obj = args.shift();
  161. for (let p in obj) {
  162. prereqs = prereqs.concat(obj[p]);
  163. name = p;
  164. }
  165. }
  166. // Optional opts/callback or callback/opts
  167. while ((arg = args.shift())) {
  168. if (typeof arg == 'function') {
  169. action = arg;
  170. }
  171. else {
  172. opts = Object.assign(Object.create(null), arg);
  173. }
  174. }
  175. task = jake.currentNamespace.resolveTask(name);
  176. if (task && !action) {
  177. // Task already exists and no action, just update prereqs, and return it.
  178. task.prereqs = task.prereqs.concat(prereqs);
  179. return task;
  180. }
  181. switch (type) {
  182. case 'directory':
  183. action = function () {
  184. jake.mkdirP(name);
  185. };
  186. task = new DirectoryTask(name, prereqs, action, opts);
  187. break;
  188. case 'file':
  189. task = new FileTask(name, prereqs, action, opts);
  190. break;
  191. default:
  192. task = new Task(name, prereqs, action, opts);
  193. }
  194. jake.currentNamespace.addTask(task);
  195. if (jake.currentTaskDescription) {
  196. task.description = jake.currentTaskDescription;
  197. jake.currentTaskDescription = null;
  198. }
  199. // FIXME: Should only need to add a new entry for the current
  200. // task-definition, not reparse the entire structure
  201. jake.parseAllTasks();
  202. return task;
  203. };
  204. this.attemptRule = function (name, ns, level) {
  205. let prereqRule;
  206. let prereq;
  207. if (level > MAX_RULE_RECURSION_LEVEL) {
  208. return null;
  209. }
  210. // Check Rule
  211. prereqRule = ns.matchRule(name);
  212. if (prereqRule) {
  213. prereq = prereqRule.createTask(name, level);
  214. }
  215. return prereq || null;
  216. };
  217. this.createPlaceholderFileTask = function (name, namespace) {
  218. let parsed = name.split(':');
  219. let filePath = parsed.pop(); // Strip any namespace
  220. let task;
  221. task = namespace.resolveTask(name);
  222. // If there's not already an existing dummy FileTask for it,
  223. // create one
  224. if (!task) {
  225. // Create a dummy FileTask only if file actually exists
  226. if (fs.existsSync(filePath)) {
  227. task = new jake.FileTask(filePath);
  228. task.dummy = true;
  229. let ns;
  230. if (parsed.length) {
  231. ns = namespace.resolveNamespace(parsed.join(':'));
  232. }
  233. else {
  234. ns = namespace;
  235. }
  236. if (!namespace) {
  237. throw new Error('Invalid namespace, cannot add FileTask');
  238. }
  239. ns.addTask(task);
  240. // Put this dummy Task in the global Tasks list so
  241. // modTime will be eval'd correctly
  242. jake.Task[`${ns.path}:${filePath}`] = task;
  243. }
  244. }
  245. return task || null;
  246. };
  247. this.run = function () {
  248. let args = Array.prototype.slice.call(arguments);
  249. let program = this.program;
  250. let loader = this.loader;
  251. let preempt;
  252. let opts;
  253. program.parseArgs(args);
  254. program.init();
  255. preempt = program.firstPreemptiveOption();
  256. if (preempt) {
  257. preempt();
  258. }
  259. else {
  260. opts = program.opts;
  261. // jakefile flag set but no jakefile yet
  262. if (opts.autocomplete && opts.jakefile === true) {
  263. process.stdout.write('no-complete');
  264. return;
  265. }
  266. // Load Jakefile and jakelibdir files
  267. let jakefileLoaded = loader.loadFile(opts.jakefile);
  268. let jakelibdirLoaded = loader.loadDirectory(opts.jakelibdir);
  269. if(!jakefileLoaded && !jakelibdirLoaded && !opts.autocomplete) {
  270. fail('No Jakefile. Specify a valid path with -f/--jakefile, ' +
  271. 'or place one in the current directory.');
  272. }
  273. program.run();
  274. }
  275. };
  276. })());
  277. }
  278. module.exports = jake;