builder.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  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. var REQUIRE = function (str) {
  136. if (typeof(str) !== 'string') { throw new Error("must be a string"); }
  137. try { return require(str); } catch (e) { }
  138. return require(process.cwd() + '/' + str);
  139. };
  140. nThen(function (waitFor) {
  141. try {
  142. /* jshint -W054 */ // Suppress jshint warning on Function being a form of eval
  143. var func = new Function('file','require','fileName','console','builder',js);
  144. func.async = function () {
  145. return waitFor(function (result) {
  146. res = result;
  147. });
  148. };
  149. x = func.call(func,
  150. file,
  151. REQUIRE,
  152. fileName,
  153. console,
  154. builder);
  155. } catch (e) {
  156. err = e;
  157. err.message += "\nContent: [" + js + "]";
  158. clearTimeout(to);
  159. throw err;
  160. }
  161. }).nThen(function (waitFor) {
  162. if (err) { return; }
  163. res = res || x || '';
  164. clearTimeout(to);
  165. process.nextTick(function() { callback(undefined, res); });
  166. });
  167. };
  168. var debug = console.log;
  169. var preprocessBlock = function (block, builder, fileObj, fileName, callback) {
  170. // a block is an array of strings and arrays, any inside arrays must be
  171. // preprocessed first. deep first top to bottom.
  172. var error = false;
  173. var nt = nThen;
  174. block.forEach(function (elem, i) {
  175. if (typeof(elem) === 'string') { return; }
  176. nt = nt(function (waitFor) {
  177. preprocessBlock(elem, builder, fileObj, fileName, waitFor(function (err, ret) {
  178. if (err) { throw err; }
  179. block[i] = ret;
  180. }));
  181. }).nThen;
  182. });
  183. nt(function (waitFor) {
  184. if (error) { return; }
  185. var capture = block.join('');
  186. execJs(capture, builder, fileObj, fileName, waitFor(function (err, ret) {
  187. if (err) { throw err; }
  188. callback(undefined, ret);
  189. }));
  190. });
  191. };
  192. var preprocess = function (content, builder, fileObj, fileName, callback) {
  193. // <?js file.Test_mainFunc = "<?js return 'RootTest_'+file.RootTest_mainFunc; ?>" ?>
  194. // worse:
  195. // <?js file.Test_mainFunc = "<?js var done = this.async(); process.nextTick(done); ?>" ?>
  196. var flatArray = content.split(/(<\?js|\?>)/);
  197. var elems = [];
  198. var unflatten = function (array, startAt, out) {
  199. for (var i = startAt; i < array.length; i++) {
  200. /* jshint -W018 */ // Suppress jshint warning on ! being confusing
  201. if (!((i - startAt) % 2)) {
  202. out.push(array[i]);
  203. } else if (array[i] === '<?js') {
  204. var next = [];
  205. out.push(next);
  206. i = unflatten(array, i+1, next);
  207. } else if (array[i] === '?>') {
  208. return i;
  209. }
  210. }
  211. return i;
  212. };
  213. if (unflatten(flatArray, 0, elems) !== flatArray.length) { throw new Error(); }
  214. var nt = nThen;
  215. elems.forEach(function (elem, i) {
  216. if (typeof(elem) === 'string') { return; }
  217. nt = nt(function (waitFor) {
  218. preprocessBlock(elem, builder, fileObj, fileName, waitFor(function (err, ret) {
  219. if (err) { throw err; }
  220. elems[i] = ret;
  221. }));
  222. }).nThen;
  223. });
  224. nt(function (waitFor) {
  225. callback(undefined, elems.join(''));
  226. });
  227. };
  228. var getFile = function ()
  229. {
  230. return {
  231. includes: [],
  232. links: [],
  233. cflags: [],
  234. oldmtime: 0
  235. };
  236. };
  237. var getObjectFile = function (cFile) {
  238. return cFile.replace(/[^a-zA-Z0-9_-]/g, '_')+'.o';
  239. };
  240. var getFlags = function (state, fileName, includeDirs) {
  241. var flags = [];
  242. flags.push.apply(flags, state.cflags);
  243. flags.push.apply(flags, state['cflags'+fileName]);
  244. if (includeDirs) {
  245. for (var i = 0; i < state.includeDirs.length; i++) {
  246. if (flags[flags.indexOf(state.includeDirs[i])-1] === '-I') { continue; }
  247. flags.push('-I');
  248. flags.push(state.includeDirs[i]);
  249. }
  250. }
  251. for (var ii = flags.length-1; ii >= 0; ii--) {
  252. // might be undefined because splicing causes us to be off the end of the array
  253. if (typeof(flags[ii]) === 'string' && flags[ii][0] === '!') {
  254. var f = flags[ii].substring(1);
  255. flags.splice(ii, 1);
  256. var index;
  257. while ((index = flags.indexOf(f)) > -1) { flags.splice(index, 1); }
  258. }
  259. }
  260. return flags;
  261. };
  262. var currentlyCompiling = {};
  263. var compileFile = function (fileName, builder, tempDir, callback)
  264. {
  265. var state = builder.config;
  266. if (typeof(state.files[fileName]) !== 'undefined') {
  267. callback();
  268. return;
  269. }
  270. if (typeof(currentlyCompiling[fileName]) !== 'undefined') {
  271. currentlyCompiling[fileName].push(callback);
  272. return;
  273. } else {
  274. currentlyCompiling[fileName] = [];
  275. }
  276. currentlyCompiling[fileName].push(callback);
  277. //debug('\033[2;32mCompiling ' + fileName + '\033[0m');
  278. var preprocessed = state.buildDir+'/'+getObjectFile(fileName)+'.i';
  279. var outFile = state.buildDir+'/'+getObjectFile(fileName);
  280. var fileContent;
  281. var fileObj = getFile();
  282. nThen(function (waitFor) {
  283. (function() {
  284. //debug("CPP -MM");
  285. var flags = ['-E', '-MM'];
  286. flags.push.apply(flags, getFlags(state, fileName, true));
  287. flags.push(fileName);
  288. cc(state.gcc, flags, waitFor(function (err, output) {
  289. if (err) { throw err; }
  290. // replace the escapes and newlines
  291. output = output.replace(/ \\|\n/g, '').split(' ');
  292. // first 2 entries are crap
  293. output.splice(0,2);
  294. for (var i = output.length-1; i >= 0; i--) {
  295. //console.log('Removing empty dependency [' +
  296. // state.gcc + ' ' + flags.join(' ') + ']');
  297. if (output[i] === '') {
  298. output.splice(i,1);
  299. }
  300. }
  301. fileObj.includes = output;
  302. }));
  303. })();
  304. (function() {
  305. //debug("CPP");
  306. var flags = ['-E'];
  307. flags.push.apply(flags, getFlags(state, fileName, true));
  308. flags.push(fileName);
  309. cc(state.gcc, flags, waitFor(function (err, output) {
  310. if (err) { throw err; }
  311. fileContent = output;
  312. }));
  313. })();
  314. }).nThen(function (waitFor) {
  315. Fs.exists(preprocessed, waitFor(function (exists) {
  316. if (!exists) { return; }
  317. Fs.unlink(preprocessed, waitFor(function (err) {
  318. if (err) { throw err; }
  319. }));
  320. }));
  321. }).nThen(function (waitFor) {
  322. //debug("Preprocess");
  323. preprocess(fileContent, builder, fileObj, fileName, waitFor(function (err, output) {
  324. if (err) { throw err; }
  325. if (state.useTempFiles) {
  326. Fs.writeFile(preprocessed, output, waitFor(function (err) {
  327. if (err) { throw err; }
  328. }));
  329. // important, this will prevent the file from also being piped to gcc.
  330. fileContent = undefined;
  331. } else {
  332. fileContent = output;
  333. }
  334. }));
  335. Fs.exists(outFile, waitFor(function (exists) {
  336. if (!exists) { return; }
  337. Fs.unlink(outFile, waitFor(function (err) {
  338. if (err) { throw err; }
  339. }));
  340. }));
  341. }).nThen(function (waitFor) {
  342. //debug("CC");
  343. var flags = ['-c','-x','cpp-output','-o',outFile];
  344. flags.push.apply(flags, getFlags(state, fileName, false));
  345. if (state.useTempFiles) {
  346. flags.push(preprocessed);
  347. } else {
  348. flags.push('-');
  349. }
  350. cc(state.gcc, flags, waitFor(function (err) {
  351. if (err) { throw err; }
  352. fileObj.obj = outFile;
  353. }), fileContent);
  354. }).nThen(function (waitFor) {
  355. debug('\033[2;32mBuilding C object ' + fileName + ' complete\033[0m');
  356. state.files[fileName] = fileObj;
  357. var callbacks = currentlyCompiling[fileName];
  358. delete currentlyCompiling[fileName];
  359. callbacks.forEach(function (cb) { cb(); });
  360. });
  361. };
  362. /**
  363. * @param files state.files
  364. * @param mtimes a mapping of files to times for files for which the times are known
  365. * @param callback when done.
  366. */
  367. var getMTimes = function (files, mtimes, callback)
  368. {
  369. nThen(function (waitFor) {
  370. Object.keys(files).forEach(function (fileName) {
  371. mtimes[fileName] = mtimes[fileName] || 0;
  372. files[fileName].includes.forEach(function (incl) {
  373. mtimes[incl] = mtimes[incl] || 0;
  374. });
  375. });
  376. Object.keys(mtimes).forEach(function (fileName) {
  377. if (mtimes[fileName] !== 0) { return; }
  378. Fs.stat(fileName, waitFor(function (err, stat) {
  379. if (err) {
  380. waitFor.abort();
  381. callback(err);
  382. return;
  383. }
  384. mtimes[fileName] = stat.mtime.getTime();
  385. }));
  386. });
  387. }).nThen(function (waitFor) {
  388. callback(undefined, mtimes);
  389. });
  390. };
  391. var removeFile = function (state, fileName, callback)
  392. {
  393. debug("remove " + fileName);
  394. nThen(function (waitFor) {
  395. // And every file which includes it
  396. Object.keys(state.files).forEach(function (file) {
  397. // recursion could remove it
  398. if (typeof(state.files[file]) === 'undefined') { return; }
  399. if (state.files[file].includes.indexOf(fileName) !== -1) {
  400. removeFile(state, file, waitFor());
  401. }
  402. });
  403. // we'll set the oldmtime on the file to 0 since it's getting rebuilt.
  404. state.oldmtimes[fileName] = 0;
  405. var f = state.files[fileName];
  406. if (typeof(f) === 'undefined') { return; }
  407. delete state.files[fileName];
  408. if (typeof(f.obj) === 'string') {
  409. Fs.unlink(f.obj, waitFor(function (err) {
  410. if (err && err.code !== 'ENOENT') { throw err; }
  411. }));
  412. }
  413. }).nThen(function (waitFor) {
  414. callback();
  415. });
  416. };
  417. var recursiveCompile = function (fileName, builder, tempDir, callback)
  418. {
  419. // Recursive compilation
  420. var state = builder.config;
  421. var doCycle = function (toCompile, parentStack, callback) {
  422. if (toCompile.length === 0) { callback(); return; }
  423. nThen(function(waitFor) {
  424. var filefunc = function(file) {
  425. var stack = [];
  426. stack.push.apply(stack, parentStack);
  427. //debug("compiling " + file);
  428. stack.push(file);
  429. if (stack.indexOf(file) !== stack.length-1) {
  430. throw new Error("Dependency loops are bad and you should feel bad\n" +
  431. "Dependency stack:\n" + stack.reverse().join('\n'));
  432. }
  433. compileFile(file, builder, tempDir, waitFor(function () {
  434. var toCompile = [];
  435. state.files[file].links.forEach(function(link) {
  436. if (link === file) { return; }
  437. toCompile.push(link);
  438. });
  439. doCycle(toCompile, stack, waitFor(function () {
  440. if (stack[stack.length-1] !== file) { throw new Error(); }
  441. stack.pop();
  442. }));
  443. }));
  444. };
  445. for (var file = toCompile.pop(); file; file = toCompile.pop()) {
  446. filefunc(file);
  447. }
  448. }).nThen(function (waitFor) {
  449. callback();
  450. });
  451. };
  452. doCycle([fileName], [], callback);
  453. };
  454. var getLinkOrder = function (fileName, files) {
  455. var completeFiles = [];
  456. var getFile = function (name) {
  457. var f = files[name];
  458. //debug('Resolving links for ' + name + ' ' + f);
  459. for (var i = 0; i < f.links.length; i++) {
  460. if (f.links[i] === name) { continue; }
  461. if (completeFiles.indexOf(f.links[i]) > -1) { continue; }
  462. getFile(f.links[i]);
  463. }
  464. completeFiles.push(name);
  465. };
  466. getFile(fileName);
  467. return completeFiles;
  468. };
  469. var needsToLink = function (fileName, state) {
  470. if (typeof(state.oldmtimes[fileName]) !== 'number') {
  471. return true;
  472. }
  473. if (state.oldmtimes[fileName] !== state.mtimes[fileName]) {
  474. return true;
  475. }
  476. var links = state.files[fileName].links;
  477. for (var i = 0; i < links.length; i++) {
  478. if (links[i] !== fileName && needsToLink(links[i], state)) {
  479. return true;
  480. }
  481. }
  482. return false;
  483. };
  484. var makeTime = function () {
  485. return function () {
  486. var oldTime = this.time || 0;
  487. var newTime = this.time = new Date().getTime();
  488. return newTime - oldTime;
  489. };
  490. };
  491. var compile = function (file, outputFile, builder, callback) {
  492. var state = builder.config;
  493. var tempDir;
  494. if (!needsToLink(file, state)) {
  495. process.nextTick(callback);
  496. return;
  497. }
  498. nThen(function(waitFor) {
  499. if (!state.useTempFiles) { return; }
  500. tempDir = tmpFile(state);
  501. Fs.mkdir(tempDir, waitFor(function (err) {
  502. if (err) { throw err; }
  503. }));
  504. }).nThen(function(waitFor) {
  505. recursiveCompile(file, builder, tempDir, waitFor());
  506. }).nThen(function(waitFor) {
  507. var linkOrder = getLinkOrder(file, state.files);
  508. for (var i = 0; i < linkOrder.length; i++) {
  509. linkOrder[i] = state.buildDir + '/' + getObjectFile(linkOrder[i]);
  510. }
  511. var ldArgs = [];
  512. ldArgs.push.apply(ldArgs, state.ldflags);
  513. ldArgs.push.apply(ldArgs, ['-o', outputFile]);
  514. ldArgs.push.apply(ldArgs, linkOrder);
  515. ldArgs.push.apply(ldArgs, state.libs);
  516. debug('\033[1;31mLinking C executable ' + outputFile + '\033[0m');
  517. cc(state.gcc, ldArgs, waitFor(function (err, ret) {
  518. if (err) { throw err; }
  519. }));
  520. }).nThen(function(waitFor) {
  521. if (!state.useTempFiles) { return; }
  522. Fs.readdir(tempDir, waitFor(function(err, files) {
  523. if (err) { throw err; }
  524. files.forEach(function(file) {
  525. Fs.unlink(tempDir + '/' + file, waitFor(function(err) {
  526. if (err) { throw err; }
  527. }));
  528. });
  529. }));
  530. }).nThen(function(waitFor) {
  531. if (!state.useTempFiles) { return; }
  532. Fs.rmdir(tempDir, waitFor(function(err) {
  533. if (err) { throw err; }
  534. }));
  535. }).nThen(function(waitFor) {
  536. if (callback) { callback(); }
  537. });
  538. };
  539. var getStatePrototype = function () {
  540. return {
  541. includeDirs: ['.'],
  542. files: {},
  543. mtimes: {},
  544. cflags: [],
  545. ldflags: [],
  546. libs: [],
  547. // Using temp files instead of pipes shaves about 400ms off a clean build.
  548. // TODO(cjd): Understand why our use of pipes is not good.
  549. tempDir: '/tmp',
  550. useTempFiles: true,
  551. systemName: 'linux'
  552. };
  553. };
  554. module.exports.configure = function (params, configure) {
  555. // Track time taken for various steps
  556. var time = makeTime();
  557. time();
  558. if (typeof(params.buildDir) !== 'string') {
  559. throw new Error("buildDir not specified");
  560. }
  561. var rebuildIfChangesHash = '';
  562. if (typeof(params.rebuildIfChanges) !== 'undefined') {
  563. rebuildIfChangesHash =
  564. Crypto.createHash('sha256').update(params.rebuildIfChanges).digest('hex');
  565. }
  566. var state;
  567. var builder;
  568. var buildStage = function () {};
  569. var testStage = function () {};
  570. var packStage = function () {};
  571. nThen(function(waitFor) {
  572. // make the build directory
  573. Fs.exists(params.buildDir, waitFor(function (exists) {
  574. if (exists) { return; }
  575. Fs.mkdir(params.buildDir, waitFor(function (err) {
  576. if (err) { throw err; }
  577. }));
  578. }));
  579. }).nThen(function(waitFor) {
  580. // read out the state if it exists
  581. Fs.exists(params.buildDir + '/state.json', waitFor(function (exists) {
  582. if (!exists) { return; }
  583. Fs.readFile(params.buildDir + '/state.json', waitFor(function (err, ret) {
  584. if (err) { throw err; }
  585. var storedState = JSON.parse(ret);
  586. if (storedState.rebuildIfChangesHash === rebuildIfChangesHash) {
  587. state = storedState;
  588. } else {
  589. debug("rebuildIfChanges changed, rebuilding");
  590. }
  591. }));
  592. }));
  593. }).nThen(function(waitFor) {
  594. debug("Initialize " + time() + "ms");
  595. // Do the configuration step
  596. if (state) {
  597. builder = mkBuilder(state);
  598. return;
  599. }
  600. state = getStatePrototype();
  601. builder = mkBuilder(state);
  602. configure(builder, waitFor);
  603. }).nThen(function(waitFor) {
  604. state.buildDir = params.buildDir;
  605. debug("Configure " + time() + "ms");
  606. }).nThen(function(waitFor) {
  607. state.rebuildIfChangesHash = rebuildIfChangesHash;
  608. state.oldmtimes = state.mtimes;
  609. state.mtimes = {};
  610. Object.keys(state.oldmtimes).forEach(function (fileName) {
  611. Fs.stat(fileName, waitFor(function (err, stat) {
  612. if (err) { throw err; }
  613. state.mtimes[fileName] = stat.mtime.getTime();
  614. if (state.oldmtimes[fileName] !== stat.mtime.getTime()) {
  615. debug(fileName + ' is out of date, rebuilding');
  616. removeFile(state, fileName, waitFor());
  617. }
  618. }));
  619. });
  620. }).nThen(function(waitFor) {
  621. debug("Scan for out of date files " + time() + "ms");
  622. }).nThen(function(waitFor) {
  623. buildStage(builder, waitFor);
  624. }).nThen(function(waitFor) {
  625. debug("Compile " + time() + "ms");
  626. var allFiles = {};
  627. Object.keys(state.files).forEach(function (fileName) {
  628. allFiles[fileName] = 1;
  629. state.files[fileName].includes.forEach(function (fileName) {
  630. allFiles[fileName] = 1;
  631. });
  632. });
  633. Object.keys(allFiles).forEach(function (fileName) {
  634. var omt = state.oldmtimes[fileName];
  635. if (omt > 0 && omt === state.mtimes[fileName]) { return; }
  636. builder.rebuiltFiles.push(fileName);
  637. });
  638. testStage(builder, waitFor);
  639. }).nThen(function(waitFor) {
  640. debug("Test " + time() + "ms");
  641. }).nThen(function(waitFor) {
  642. packStage(builder, waitFor);
  643. }).nThen(function(waitFor) {
  644. debug("Pack " + time() + "ms");
  645. getMTimes(state.files, state.mtimes, waitFor(function (err, mtimes) {
  646. if (err) { throw err; }
  647. state.mtimes = mtimes;
  648. debug("Get mtimes " + time() + "ms");
  649. }));
  650. }).nThen(function(waitFor) {
  651. // save state
  652. var stateJson = JSON.stringify(state, null, ' ');
  653. Fs.writeFile(state.buildDir+'/state.json', stateJson, waitFor(function(err) {
  654. if (err) { throw err; }
  655. debug("Save State " + time() + "ms");
  656. }));
  657. });
  658. return {
  659. build: function (build) {
  660. buildStage = build;
  661. return {
  662. test: function (test) {
  663. testStage = test;
  664. return {
  665. pack: function (pack) {
  666. packStage = pack;
  667. }
  668. };
  669. }
  670. };
  671. }
  672. };
  673. };