builder.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. var Os = require('os');
  16. var Fs = require('fs');
  17. var Spawn = require('child_process').spawn;
  18. var nThen = require('nthen');
  19. var Extend = require('node.extend');
  20. var Crypto = require('crypto');
  21. var Semaphore = require('./Semaphore');
  22. /*
  23. * Why hello dear packager,
  24. *
  25. * I suppose you have found this place as you are trying to figure out how to work this into your
  26. * build system. You're probably faced with a decision between getting node.js into your build and
  27. * "fixing" this build process so it doesn't need such a silly thing. A 500 line script is certainly
  28. * not unapproachable, right?
  29. * The reason why I am speaking to you now is because I care about you. I want you to be happy
  30. * and live a carefree life, and because you are standing on the precipice of a cavern so dark and
  31. * deep that while you may well make it out alive, your personal pride and innocence almost
  32. * certainly will not. Imagine yourself after months of sleepless nights wallowing in the quicksand,
  33. * forever trying to slay the dragon which is always so close yet and so far away. Imagine the deep
  34. * hatred you will have for humanity, code, and the creator of this doomsday machine. I beg you to
  35. * turn back now while there is still hope. You need not die here, your life is important, and
  36. * whether you close this file now or not, in the end you will still end up including node.js in
  37. * your build.
  38. *
  39. * The Creator
  40. */
  41. // Since many of the compile operations are short, the best
  42. // performance seems to be when running 1.25x the number of jobs as
  43. // cpu cores. On BSD and iphone systems, os.cpus() is not reliable so
  44. // if it returns undefined let's just assume 1
  45. var WORKERS = Math.floor((typeof Os.cpus() == 'undefined' ? 1 : Os.cpus().length) * 1.25);
  46. var error = function (message)
  47. {
  48. try {
  49. throw new Error(message);
  50. } catch (e) {
  51. return e;
  52. }
  53. };
  54. var expandArgs = function (args) {
  55. var out = [];
  56. for (var i = 0; i < args.length; i++) {
  57. if (typeof(args[i]) === 'object') {
  58. if (Array.isArray(args[i])) {
  59. out.push.apply(out, expandArgs(args[i]));
  60. } else {
  61. throw new Error("object in arguments [" + args + "]");
  62. }
  63. } else {
  64. out.push(args[i]);
  65. }
  66. }
  67. return out;
  68. };
  69. var sema = Semaphore.create(WORKERS);
  70. var compiler = function (compilerPath, args, callback, content) {
  71. args = expandArgs(args);
  72. sema.take(function (returnAfter) {
  73. var gcc = Spawn(compilerPath, args);
  74. var err = '';
  75. var out = '';
  76. gcc.stdout.on('data', function(dat) { out += dat.toString(); });
  77. gcc.stderr.on('data', function(dat) { err += dat.toString(); });
  78. gcc.on('close', returnAfter(function(ret) {
  79. callback(ret, out, err);
  80. }));
  81. gcc.on('error', function(err) {
  82. // handle the error safely
  83. console.log(args);
  84. console.log(err);
  85. });
  86. if (content) {
  87. gcc.stdin.write(content, function (err) {
  88. if (err) { throw err; }
  89. gcc.stdin.end();
  90. });
  91. }
  92. });
  93. };
  94. var cc = function (gcc, args, callback, content) {
  95. compiler(gcc, args, function (ret, out, err) {
  96. if (ret) {
  97. callback(error("gcc " + args.join(' ') + "\n\n" + err));
  98. }
  99. if (err !== '') {
  100. debug(err);
  101. }
  102. callback(undefined, out);
  103. }, content);
  104. };
  105. var tmpFile = function (state, name) {
  106. name = name || '';
  107. return state.tempDir+'/jsmake-' + name + Crypto.pseudoRandomBytes(10).toString('hex');
  108. };
  109. var mkBuilder = function (state) {
  110. var builder = {
  111. cc: function (args, callback) {
  112. compiler(builder.config.gcc, args, callback);
  113. },
  114. buildExecutable: function (cFile, outputFile, callback) {
  115. compile(cFile, outputFile, builder, callback);
  116. },
  117. config: state,
  118. tmpFile: function (name) {
  119. return tmpFile(state, name);
  120. },
  121. rebuiltFiles: []
  122. };
  123. return builder;
  124. };
  125. // You Were Warned
  126. var execJs = function (js, builder, file, fileName, callback) {
  127. var res;
  128. var x;
  129. var err;
  130. // # 74 "./wire/Message.h"
  131. js = js.replace(/\n#.*\n/g, '');
  132. var to = setTimeout(function () {
  133. throw new Error("Inline JS did not return after 120 seconds [" + js + "]");
  134. }, 120000);
  135. nThen(function (waitFor) {
  136. try {
  137. /* jshint -W054 */ // Suppress jshint warning on Function being a form of eval
  138. var func = new Function('file','require','fileName','console','builder',js);
  139. func.async = function () {
  140. return waitFor(function (result) {
  141. res = result;
  142. });
  143. };
  144. x = func.call(func,
  145. file,
  146. require,
  147. fileName,
  148. console,
  149. builder);
  150. } catch (e) {
  151. err = e;
  152. err.message += "\nContent: [" + js + "]";
  153. clearTimeout(to);
  154. throw err;
  155. }
  156. }).nThen(function (waitFor) {
  157. if (err) { return; }
  158. res = res || x || '';
  159. clearTimeout(to);
  160. process.nextTick(function() { callback(undefined, res); });
  161. });
  162. };
  163. var debug = console.log;
  164. var preprocessBlock = function (block, builder, fileObj, fileName, callback) {
  165. // a block is an array of strings and arrays, any inside arrays must be
  166. // preprocessed first. deep first top to bottom.
  167. var error = false;
  168. var nt = nThen;
  169. block.forEach(function (elem, i) {
  170. if (typeof(elem) === 'string') { return; }
  171. nt = nt(function (waitFor) {
  172. preprocessBlock(elem, builder, fileObj, fileName, waitFor(function (err, ret) {
  173. if (err) { throw err; }
  174. block[i] = ret;
  175. }));
  176. }).nThen;
  177. });
  178. nt(function (waitFor) {
  179. if (error) { return; }
  180. var capture = block.join('');
  181. execJs(capture, builder, fileObj, fileName, waitFor(function (err, ret) {
  182. if (err) { throw err; }
  183. callback(undefined, ret);
  184. }));
  185. });
  186. };
  187. var preprocess = function (content, builder, fileObj, fileName, callback) {
  188. // <?js file.Test_mainFunc = "<?js return 'RootTest_'+file.RootTest_mainFunc; ?>" ?>
  189. // worse:
  190. // <?js file.Test_mainFunc = "<?js var done = this.async(); process.nextTick(done); ?>" ?>
  191. var flatArray = content.split(/(<\?js|\?>)/);
  192. var elems = [];
  193. var unflatten = function (array, startAt, out) {
  194. for (var i = startAt; i < array.length; i++) {
  195. /* jshint -W018 */ // Suppress jshint warning on ! being confusing
  196. if (!((i - startAt) % 2)) {
  197. out.push(array[i]);
  198. } else if (array[i] === '<?js') {
  199. var next = [];
  200. out.push(next);
  201. i = unflatten(array, i+1, next);
  202. } else if (array[i] === '?>') {
  203. return i;
  204. }
  205. }
  206. return i;
  207. };
  208. if (unflatten(flatArray, 0, elems) !== flatArray.length) { throw new Error(); }
  209. var nt = nThen;
  210. elems.forEach(function (elem, i) {
  211. if (typeof(elem) === 'string') { return; }
  212. nt = nt(function (waitFor) {
  213. preprocessBlock(elem, builder, fileObj, fileName, waitFor(function (err, ret) {
  214. if (err) { throw err; }
  215. elems[i] = ret;
  216. }));
  217. }).nThen;
  218. });
  219. nt(function (waitFor) {
  220. callback(undefined, elems.join(''));
  221. });
  222. };
  223. var getFile = function ()
  224. {
  225. return {
  226. includes: [],
  227. links: [],
  228. cflags: [],
  229. oldmtime: 0
  230. };
  231. };
  232. var getObjectFile = function (cFile) {
  233. return cFile.replace(/[^a-zA-Z0-9_-]/g, '_')+'.o';
  234. };
  235. var getFlags = function (state, fileName, includeDirs) {
  236. var flags = [];
  237. flags.push.apply(flags, state.cflags);
  238. flags.push.apply(flags, state['cflags'+fileName]);
  239. if (includeDirs) {
  240. for (var i = 0; i < state.includeDirs.length; i++) {
  241. if (flags[flags.indexOf(state.includeDirs[i])-1] === '-I') { continue; }
  242. flags.push('-I');
  243. flags.push(state.includeDirs[i]);
  244. }
  245. }
  246. for (var ii = flags.length-1; ii >= 0; ii--) {
  247. // might be undefined because splicing causes us to be off the end of the array
  248. if (typeof(flags[ii]) === 'string' && flags[ii][0] === '!') {
  249. var f = flags[ii].substring(1);
  250. flags.splice(ii, 1);
  251. var index;
  252. while ((index = flags.indexOf(f)) > -1) { flags.splice(index, 1); }
  253. }
  254. }
  255. return flags;
  256. };
  257. var currentlyCompiling = {};
  258. var compileFile = function (fileName, builder, tempDir, callback)
  259. {
  260. var state = builder.config;
  261. if (typeof(state.files[fileName]) !== 'undefined') {
  262. callback();
  263. return;
  264. }
  265. if (typeof(currentlyCompiling[fileName]) !== 'undefined') {
  266. currentlyCompiling[fileName].push(callback);
  267. return;
  268. } else {
  269. currentlyCompiling[fileName] = [];
  270. }
  271. currentlyCompiling[fileName].push(callback);
  272. //debug('\033[2;32mCompiling ' + fileName + '\033[0m');
  273. var preprocessed = state.buildDir+'/'+getObjectFile(fileName)+'.i';
  274. var outFile = state.buildDir+'/'+getObjectFile(fileName);
  275. var fileContent;
  276. var fileObj = getFile();
  277. nThen(function (waitFor) {
  278. (function() {
  279. //debug("CPP -MM");
  280. var flags = ['-E', '-MM'];
  281. flags.push.apply(flags, getFlags(state, fileName, true));
  282. flags.push(fileName);
  283. cc(state.gcc, flags, waitFor(function (err, output) {
  284. if (err) { throw err; }
  285. // replace the escapes and newlines
  286. output = output.replace(/ \\|\n/g, '').split(' ');
  287. // first 2 entries are crap
  288. output.splice(0,2);
  289. for (var i = output.length-1; i >= 0; i--) {
  290. //console.log('Removing empty dependency [' +
  291. // state.gcc + ' ' + flags.join(' ') + ']');
  292. if (output[i] === '') {
  293. output.splice(i,1);
  294. }
  295. }
  296. fileObj.includes = output;
  297. }));
  298. })();
  299. (function() {
  300. //debug("CPP");
  301. var flags = ['-E'];
  302. flags.push.apply(flags, getFlags(state, fileName, true));
  303. flags.push(fileName);
  304. cc(state.gcc, flags, waitFor(function (err, output) {
  305. if (err) { throw err; }
  306. fileContent = output;
  307. }));
  308. })();
  309. }).nThen(function (waitFor) {
  310. Fs.exists(preprocessed, waitFor(function (exists) {
  311. if (!exists) { return; }
  312. Fs.unlink(preprocessed, waitFor(function (err) {
  313. if (err) { throw err; }
  314. }));
  315. }));
  316. }).nThen(function (waitFor) {
  317. //debug("Preprocess");
  318. preprocess(fileContent, builder, fileObj, fileName, waitFor(function (err, output) {
  319. if (err) { throw err; }
  320. if (state.useTempFiles) {
  321. Fs.writeFile(preprocessed, output, waitFor(function (err) {
  322. if (err) { throw err; }
  323. }));
  324. // important, this will prevent the file from also being piped to gcc.
  325. fileContent = undefined;
  326. } else {
  327. fileContent = output;
  328. }
  329. }));
  330. Fs.exists(outFile, waitFor(function (exists) {
  331. if (!exists) { return; }
  332. Fs.unlink(outFile, waitFor(function (err) {
  333. if (err) { throw err; }
  334. }));
  335. }));
  336. }).nThen(function (waitFor) {
  337. //debug("CC");
  338. var flags = ['-c','-x','cpp-output','-o',outFile];
  339. flags.push.apply(flags, getFlags(state, fileName, false));
  340. if (state.useTempFiles) {
  341. flags.push(preprocessed);
  342. } else {
  343. flags.push('-');
  344. }
  345. cc(state.gcc, flags, waitFor(function (err) {
  346. if (err) { throw err; }
  347. fileObj.obj = outFile;
  348. }), fileContent);
  349. }).nThen(function (waitFor) {
  350. debug('\033[2;32mBuilding C object ' + fileName + ' complete\033[0m');
  351. state.files[fileName] = fileObj;
  352. var callbacks = currentlyCompiling[fileName];
  353. delete currentlyCompiling[fileName];
  354. callbacks.forEach(function (cb) { cb(); });
  355. });
  356. };
  357. /**
  358. * @param files state.files
  359. * @param mtimes a mapping of files to times for files for which the times are known
  360. * @param callback when done.
  361. */
  362. var getMTimes = function (files, mtimes, callback)
  363. {
  364. nThen(function (waitFor) {
  365. Object.keys(files).forEach(function (fileName) {
  366. mtimes[fileName] = mtimes[fileName] || 0;
  367. files[fileName].includes.forEach(function (incl) {
  368. mtimes[incl] = mtimes[incl] || 0;
  369. });
  370. });
  371. Object.keys(mtimes).forEach(function (fileName) {
  372. if (mtimes[fileName] !== 0) { return; }
  373. Fs.stat(fileName, waitFor(function (err, stat) {
  374. if (err) {
  375. waitFor.abort();
  376. callback(err);
  377. return;
  378. }
  379. mtimes[fileName] = stat.mtime.getTime();
  380. }));
  381. });
  382. }).nThen(function (waitFor) {
  383. callback(undefined, mtimes);
  384. });
  385. };
  386. var removeFile = function (state, fileName, callback)
  387. {
  388. debug("remove " + fileName);
  389. nThen(function (waitFor) {
  390. // And every file which includes it
  391. Object.keys(state.files).forEach(function (file) {
  392. // recursion could remove it
  393. if (typeof(state.files[file]) === 'undefined') { return; }
  394. if (state.files[file].includes.indexOf(fileName) !== -1) {
  395. removeFile(state, file, waitFor());
  396. }
  397. });
  398. // we'll set the oldmtime on the file to 0 since it's getting rebuilt.
  399. state.oldmtimes[fileName] = 0;
  400. var f = state.files[fileName];
  401. if (typeof(f) === 'undefined') { return; }
  402. delete state.files[fileName];
  403. if (typeof(f.obj) === 'string') {
  404. Fs.unlink(f.obj, waitFor(function (err) {
  405. if (err && err.code !== 'ENOENT') { throw err; }
  406. }));
  407. }
  408. }).nThen(function (waitFor) {
  409. callback();
  410. });
  411. };
  412. var recursiveCompile = function (fileName, builder, tempDir, callback)
  413. {
  414. // Recursive compilation
  415. var state = builder.config;
  416. var doCycle = function (toCompile, parentStack, callback) {
  417. if (toCompile.length === 0) { callback(); return; }
  418. nThen(function(waitFor) {
  419. var filefunc = function(file) {
  420. var stack = [];
  421. stack.push.apply(stack, parentStack);
  422. //debug("compiling " + file);
  423. stack.push(file);
  424. if (stack.indexOf(file) !== stack.length-1) {
  425. throw new Error("Dependency loops are bad and you should feel bad\n" +
  426. "Dependency stack:\n" + stack.reverse().join('\n'));
  427. }
  428. compileFile(file, builder, tempDir, waitFor(function () {
  429. var toCompile = [];
  430. state.files[file].links.forEach(function(link) {
  431. if (link === file) { return; }
  432. toCompile.push(link);
  433. });
  434. doCycle(toCompile, stack, waitFor(function () {
  435. if (stack[stack.length-1] !== file) { throw new Error(); }
  436. stack.pop();
  437. }));
  438. }));
  439. };
  440. for (var file = toCompile.pop(); file; file = toCompile.pop()) {
  441. filefunc(file);
  442. }
  443. }).nThen(function (waitFor) {
  444. callback();
  445. });
  446. };
  447. doCycle([fileName], [], callback);
  448. };
  449. var getLinkOrder = function (fileName, files) {
  450. var completeFiles = [];
  451. var getFile = function (name) {
  452. var f = files[name];
  453. //debug('Resolving links for ' + name + ' ' + f);
  454. for (var i = 0; i < f.links.length; i++) {
  455. if (f.links[i] === name) { continue; }
  456. if (completeFiles.indexOf(f.links[i]) > -1) { continue; }
  457. getFile(f.links[i]);
  458. }
  459. completeFiles.push(name);
  460. };
  461. getFile(fileName);
  462. return completeFiles;
  463. };
  464. var needsToLink = function (fileName, state) {
  465. if (typeof(state.oldmtimes[fileName]) !== 'number') {
  466. return true;
  467. }
  468. if (state.oldmtimes[fileName] !== state.mtimes[fileName]) {
  469. return true;
  470. }
  471. var links = state.files[fileName].links;
  472. for (var i = 0; i < links.length; i++) {
  473. if (links[i] !== fileName && needsToLink(links[i], state)) {
  474. return true;
  475. }
  476. }
  477. return false;
  478. };
  479. var makeTime = function () {
  480. return function () {
  481. var oldTime = this.time || 0;
  482. var newTime = this.time = new Date().getTime();
  483. return newTime - oldTime;
  484. };
  485. };
  486. var compile = function (file, outputFile, builder, callback) {
  487. var state = builder.config;
  488. var tempDir;
  489. if (!needsToLink(file, state)) {
  490. process.nextTick(callback);
  491. return;
  492. }
  493. nThen(function(waitFor) {
  494. if (!state.useTempFiles) { return; }
  495. tempDir = tmpFile(state);
  496. Fs.mkdir(tempDir, waitFor(function (err) {
  497. if (err) { throw err; }
  498. }));
  499. }).nThen(function(waitFor) {
  500. recursiveCompile(file, builder, tempDir, waitFor());
  501. }).nThen(function(waitFor) {
  502. var linkOrder = getLinkOrder(file, state.files);
  503. for (var i = 0; i < linkOrder.length; i++) {
  504. linkOrder[i] = state.buildDir + '/' + getObjectFile(linkOrder[i]);
  505. }
  506. var ldArgs = [];
  507. ldArgs.push.apply(ldArgs, state.ldflags);
  508. ldArgs.push.apply(ldArgs, ['-o', outputFile]);
  509. ldArgs.push.apply(ldArgs, linkOrder);
  510. ldArgs.push.apply(ldArgs, state.libs);
  511. debug('\033[1;31mLinking C executable ' + outputFile + '\033[0m');
  512. cc(state.gcc, ldArgs, waitFor(function (err, ret) {
  513. if (err) { throw err; }
  514. }));
  515. }).nThen(function(waitFor) {
  516. if (!state.useTempFiles) { return; }
  517. Fs.readdir(tempDir, waitFor(function(err, files) {
  518. if (err) { throw err; }
  519. files.forEach(function(file) {
  520. Fs.unlink(tempDir + '/' + file, waitFor(function(err) {
  521. if (err) { throw err; }
  522. }));
  523. });
  524. }));
  525. }).nThen(function(waitFor) {
  526. if (!state.useTempFiles) { return; }
  527. Fs.rmdir(tempDir, waitFor(function(err) {
  528. if (err) { throw err; }
  529. }));
  530. }).nThen(function(waitFor) {
  531. if (callback) { callback(); }
  532. });
  533. };
  534. var getStatePrototype = function () {
  535. return {
  536. includeDirs: ['.'],
  537. files: {},
  538. mtimes: {},
  539. cflags: [],
  540. ldflags: [],
  541. libs: [],
  542. // Using temp files instead of pipes shaves about 400ms off a clean build.
  543. // TODO(cjd): Understand why our use of pipes is not good.
  544. tempDir: '/tmp',
  545. useTempFiles: true,
  546. systemName: 'linux'
  547. };
  548. };
  549. module.exports.configure = function (params, configure) {
  550. // Track time taken for various steps
  551. var time = makeTime();
  552. time();
  553. if (typeof(params.buildDir) !== 'string') {
  554. throw new Error("buildDir not specified");
  555. }
  556. var rebuildIfChangesHash = '';
  557. if (typeof(params.rebuildIfChanges) !== 'undefined') {
  558. rebuildIfChangesHash =
  559. Crypto.createHash('sha256').update(params.rebuildIfChanges).digest('hex');
  560. }
  561. var state;
  562. var builder;
  563. var buildStage = function () {};
  564. var testStage = function () {};
  565. var packStage = function () {};
  566. nThen(function(waitFor) {
  567. // make the build directory
  568. Fs.exists(params.buildDir, waitFor(function (exists) {
  569. if (exists) { return; }
  570. Fs.mkdir(params.buildDir, waitFor(function (err) {
  571. if (err) { throw err; }
  572. }));
  573. }));
  574. }).nThen(function(waitFor) {
  575. // read out the state if it exists
  576. Fs.exists(params.buildDir + '/state.json', waitFor(function (exists) {
  577. if (!exists) { return; }
  578. Fs.readFile(params.buildDir + '/state.json', waitFor(function (err, ret) {
  579. if (err) { throw err; }
  580. var storedState = JSON.parse(ret);
  581. if (storedState.rebuildIfChangesHash === rebuildIfChangesHash) {
  582. state = storedState;
  583. } else {
  584. debug("rebuildIfChanges changed, rebuilding");
  585. }
  586. }));
  587. }));
  588. }).nThen(function(waitFor) {
  589. debug("Initialize " + time() + "ms");
  590. // Do the configuration step
  591. if (state) {
  592. builder = mkBuilder(state);
  593. return;
  594. }
  595. state = getStatePrototype();
  596. builder = mkBuilder(state);
  597. configure(builder, waitFor);
  598. }).nThen(function(waitFor) {
  599. state.buildDir = params.buildDir;
  600. debug("Configure " + time() + "ms");
  601. }).nThen(function(waitFor) {
  602. state.rebuildIfChangesHash = rebuildIfChangesHash;
  603. state.oldmtimes = state.mtimes;
  604. state.mtimes = {};
  605. Object.keys(state.oldmtimes).forEach(function (fileName) {
  606. Fs.stat(fileName, waitFor(function (err, stat) {
  607. if (err) { throw err; }
  608. state.mtimes[fileName] = stat.mtime.getTime();
  609. if (state.oldmtimes[fileName] !== stat.mtime.getTime()) {
  610. debug(fileName + ' is out of date, rebuilding');
  611. removeFile(state, fileName, waitFor());
  612. }
  613. }));
  614. });
  615. }).nThen(function(waitFor) {
  616. debug("Scan for out of date files " + time() + "ms");
  617. }).nThen(function(waitFor) {
  618. buildStage(builder, waitFor);
  619. }).nThen(function(waitFor) {
  620. debug("Compile " + time() + "ms");
  621. var allFiles = {};
  622. Object.keys(state.files).forEach(function (fileName) {
  623. allFiles[fileName] = 1;
  624. state.files[fileName].includes.forEach(function (fileName) {
  625. allFiles[fileName] = 1;
  626. });
  627. });
  628. Object.keys(allFiles).forEach(function (fileName) {
  629. var omt = state.oldmtimes[fileName];
  630. if (omt > 0 && omt === state.mtimes[fileName]) { return; }
  631. builder.rebuiltFiles.push(fileName);
  632. });
  633. testStage(builder, waitFor);
  634. }).nThen(function(waitFor) {
  635. debug("Test " + time() + "ms");
  636. }).nThen(function(waitFor) {
  637. packStage(builder, waitFor);
  638. }).nThen(function(waitFor) {
  639. debug("Pack " + time() + "ms");
  640. getMTimes(state.files, state.mtimes, waitFor(function (err, mtimes) {
  641. if (err) { throw err; }
  642. state.mtimes = mtimes;
  643. debug("Get mtimes " + time() + "ms");
  644. }));
  645. }).nThen(function(waitFor) {
  646. // save state
  647. var stateJson = JSON.stringify(state, null, ' ');
  648. Fs.writeFile(state.buildDir+'/state.json', stateJson, waitFor(function(err) {
  649. if (err) { throw err; }
  650. debug("Save State " + time() + "ms");
  651. }));
  652. });
  653. return {
  654. build: function (build) {
  655. buildStage = build;
  656. return {
  657. test: function (test) {
  658. testStage = test;
  659. return {
  660. pack: function (pack) {
  661. packStage = pack;
  662. }
  663. };
  664. }
  665. };
  666. }
  667. };
  668. };