jake.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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 available 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. let taskParams;
  104. let len;
  105. for (p in jake.Task) {
  106. if (!Object.prototype.hasOwnProperty.call(jake.Task, p)) {
  107. continue;
  108. }
  109. if (filter && p.indexOf(filter) == -1) {
  110. continue;
  111. }
  112. task = jake.Task[p];
  113. taskParams = task.params;
  114. // Record the length of the longest task name -- used for
  115. // pretty alignment of the task descriptions
  116. if (task.description) {
  117. len = p.length + taskParams.length;
  118. maxTaskNameLength = len > maxTaskNameLength ?
  119. len : maxTaskNameLength;
  120. }
  121. }
  122. // Print out each entry with descriptions neatly aligned
  123. for (p in jake.Task) {
  124. if (!Object.prototype.hasOwnProperty.call(jake.Task, p)) {
  125. continue;
  126. }
  127. if (filter && p.indexOf(filter) == -1) {
  128. continue;
  129. }
  130. task = jake.Task[p];
  131. taskParams = "";
  132. if (task.params != "") {
  133. taskParams = "[" + task.params + "]";
  134. }
  135. //name = '\033[32m' + p + '\033[39m ';
  136. name = chalk.green(p);
  137. descr = task.description;
  138. if (descr) {
  139. descr = chalk.gray('# ' + descr);
  140. // Create padding-string with calculated length
  141. padding = (new Array(maxTaskNameLength - p.length - taskParams.length + 4)).join(' ');
  142. console.log('jake ' + name + taskParams + padding + descr);
  143. }
  144. }
  145. };
  146. this.createTask = function () {
  147. let args = Array.prototype.slice.call(arguments);
  148. let arg;
  149. let obj;
  150. let task;
  151. let type;
  152. let name;
  153. let action;
  154. let opts = {};
  155. let prereqs = [];
  156. type = args.shift();
  157. // name, [deps], [action]
  158. // Name (string) + deps (array) format
  159. if (typeof args[0] == 'string') {
  160. name = args.shift();
  161. if (Array.isArray(args[0])) {
  162. prereqs = args.shift();
  163. }
  164. }
  165. // name:deps, [action]
  166. // Legacy object-literal syntax, e.g.: {'name': ['depA', 'depB']}
  167. else {
  168. obj = args.shift();
  169. for (let p in obj) {
  170. prereqs = prereqs.concat(obj[p]);
  171. name = p;
  172. }
  173. }
  174. // Optional opts/callback or callback/opts
  175. while ((arg = args.shift())) {
  176. if (typeof arg == 'function') {
  177. action = arg;
  178. }
  179. else {
  180. opts = Object.assign(Object.create(null), arg);
  181. }
  182. }
  183. task = jake.currentNamespace.resolveTask(name);
  184. if (task && !action) {
  185. // Task already exists and no action, just update prereqs, and return it.
  186. task.prereqs = task.prereqs.concat(prereqs);
  187. return task;
  188. }
  189. switch (type) {
  190. case 'directory':
  191. action = function action() {
  192. jake.mkdirP(name);
  193. };
  194. task = new DirectoryTask(name, prereqs, action, opts);
  195. break;
  196. case 'file':
  197. task = new FileTask(name, prereqs, action, opts);
  198. break;
  199. default:
  200. task = new Task(name, prereqs, action, opts);
  201. }
  202. jake.currentNamespace.addTask(task);
  203. if (jake.currentTaskDescription) {
  204. task.description = jake.currentTaskDescription;
  205. jake.currentTaskDescription = null;
  206. }
  207. // FIXME: Should only need to add a new entry for the current
  208. // task-definition, not reparse the entire structure
  209. jake.parseAllTasks();
  210. return task;
  211. };
  212. this.attemptRule = function (name, ns, level) {
  213. let prereqRule;
  214. let prereq;
  215. if (level > MAX_RULE_RECURSION_LEVEL) {
  216. return null;
  217. }
  218. // Check Rule
  219. prereqRule = ns.matchRule(name);
  220. if (prereqRule) {
  221. prereq = prereqRule.createTask(name, level);
  222. }
  223. return prereq || null;
  224. };
  225. this.createPlaceholderFileTask = function (name, namespace) {
  226. let parsed = name.split(':');
  227. let filePath = parsed.pop(); // Strip any namespace
  228. let task;
  229. task = namespace.resolveTask(name);
  230. // If there's not already an existing dummy FileTask for it,
  231. // create one
  232. if (!task) {
  233. // Create a dummy FileTask only if file actually exists
  234. if (fs.existsSync(filePath)) {
  235. task = new jake.FileTask(filePath);
  236. task.dummy = true;
  237. let ns;
  238. if (parsed.length) {
  239. ns = namespace.resolveNamespace(parsed.join(':'));
  240. }
  241. else {
  242. ns = namespace;
  243. }
  244. if (!namespace) {
  245. throw new Error('Invalid namespace, cannot add FileTask');
  246. }
  247. ns.addTask(task);
  248. // Put this dummy Task in the global Tasks list so
  249. // modTime will be eval'd correctly
  250. jake.Task[`${ns.path}:${filePath}`] = task;
  251. }
  252. }
  253. return task || null;
  254. };
  255. this.run = function () {
  256. let args = Array.prototype.slice.call(arguments);
  257. let program = this.program;
  258. let loader = this.loader;
  259. let preempt;
  260. let opts;
  261. program.parseArgs(args);
  262. program.init();
  263. preempt = program.firstPreemptiveOption();
  264. if (preempt) {
  265. preempt();
  266. }
  267. else {
  268. opts = program.opts;
  269. // jakefile flag set but no jakefile yet
  270. if (opts.autocomplete && opts.jakefile === true) {
  271. process.stdout.write('no-complete');
  272. return;
  273. }
  274. // Load Jakefile and jakelibdir files
  275. let jakefileLoaded = loader.loadFile(opts.jakefile);
  276. let jakelibdirLoaded = loader.loadDirectory(opts.jakelibdir);
  277. if(!jakefileLoaded && !jakelibdirLoaded && !opts.autocomplete) {
  278. fail('No Jakefile. Specify a valid path with -f/--jakefile, ' +
  279. 'or place one in the current directory.');
  280. }
  281. program.run();
  282. }
  283. };
  284. })());
  285. }
  286. module.exports = jake;