builder.js 23 KB

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