1
0

builder.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  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 Crypto = require('crypto');
  20. var Semaphore = require('../tools/lib/Semaphore');
  21. var GetVersion = require('./GetVersion');
  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 cpus = Os.cpus(); // workaround, nodejs seems to be broken on openbsd (undefined result after second call)
  46. var PROCESSORS = Math.floor((typeof cpus === 'undefined' ? 1 : cpus.length) * 1.25);
  47. var error = function (message)
  48. {
  49. try {
  50. throw new Error(message);
  51. } catch (e) {
  52. return e;
  53. }
  54. };
  55. var throwIfErr = function(err) {
  56. if (err) {
  57. throw new Error(err);
  58. }
  59. };
  60. var expandArgs = function (args) {
  61. var out = [];
  62. for (var i = 0; i < args.length; i++) {
  63. if (typeof(args[i]) === 'object') {
  64. if (Array.isArray(args[i])) {
  65. out.push.apply(out, expandArgs(args[i]));
  66. } else {
  67. throw new Error("object in arguments [" + args + "]");
  68. }
  69. } else {
  70. out.push(args[i]);
  71. }
  72. }
  73. return out;
  74. };
  75. var sema = Semaphore.create(PROCESSORS);
  76. var compiler = function (compilerPath, args, callback, content) {
  77. args = expandArgs(args);
  78. sema.take(function (returnAfter) {
  79. var gcc = Spawn(compilerPath, args);
  80. var err = '';
  81. var out = '';
  82. gcc.stdout.on('data', function (dat) { out += dat.toString(); });
  83. gcc.stderr.on('data', function (dat) { err += dat.toString(); });
  84. gcc.on('close', returnAfter(function (ret) {
  85. callback(ret, out, err);
  86. }));
  87. gcc.on('error', function (err) {
  88. if (err.code === 'ENOENT') {
  89. console.error('\033[1;31mError: ' + compilerPath + ' is required!\033[0m');
  90. } else {
  91. console.error(
  92. '\033[1;31mFail run ' + process.cwd() + ': ' + compilerPath + ' '
  93. + args.join(' ') + '\033[0m'
  94. );
  95. console.error('Message:' + err);
  96. }
  97. // handle the error safely
  98. console.log(args);
  99. });
  100. if (content) {
  101. gcc.stdin.write(content, function (err) {
  102. if (err) { throw err; }
  103. gcc.stdin.end();
  104. });
  105. }
  106. });
  107. };
  108. var cc = function (gcc, args, callback, content) {
  109. compiler(gcc, args, function (ret, out, err) {
  110. if (ret) {
  111. callback(error("gcc " + args.join(' ') + "\n\n" + err));
  112. }
  113. if (err !== '') {
  114. debug(err);
  115. }
  116. callback(undefined, out);
  117. }, content);
  118. };
  119. var tmpFile = function (state, name) {
  120. name = name || '';
  121. return state.tempDir + '/jsmake-' + name + Crypto.pseudoRandomBytes(10).toString('hex');
  122. };
  123. var mkBuilder = function (state) {
  124. var builder = {
  125. cc: function (args, callback) {
  126. compiler(builder.config.gcc, args, callback);
  127. },
  128. buildExecutable: function (cFile, outputFile) {
  129. if (!outputFile) {
  130. outputFile = cFile.replace(/^.*\/([^\/\.]*).*$/, function (a, b) { return b; });
  131. }
  132. if (state.systemName === 'win32' && !(/\.exe$/.test(outputFile))) {
  133. outputFile += '.exe';
  134. }
  135. var temp = state.buildDir + '/' + getExecutableFile(cFile);
  136. compile(cFile, temp, builder, builder.waitFor());
  137. builder.executables.push([temp, outputFile]);
  138. return temp;
  139. },
  140. buildTest: function (cFile) {
  141. return builder.buildExecutable(cFile, state.buildDir + '/' + getExecutableFile(cFile));
  142. },
  143. runTest: function (outFile, testRunner) {
  144. builder.tests.push(function (cb) { testRunner(outFile, cb); });
  145. },
  146. lintFiles: function (linter) {
  147. builder.linters.push(linter);
  148. },
  149. config: state,
  150. tmpFile: function (name) {
  151. return tmpFile(state, name);
  152. },
  153. rebuiltFiles: [],
  154. // Test executables (arrays containing name in build dir and test runner)
  155. tests: [],
  156. // Executables (arrays containing name in build dir and final name)
  157. executables: [],
  158. linters: [],
  159. // Concurrency...
  160. processors: PROCESSORS
  161. };
  162. return builder;
  163. };
  164. // You Were Warned
  165. var execJs = function (js, builder, file, fileName, callback) {
  166. var res;
  167. var x;
  168. var err;
  169. // # 74 "./wire/Message.h"
  170. js = js.replace(/\n#.*\n/g, '');
  171. var to = setTimeout(function () {
  172. throw new Error("Inline JS did not return after 120 seconds [" + js + "]");
  173. }, 120000);
  174. var REQUIRE = function (str) {
  175. if (typeof(str) !== 'string') {
  176. throw new Error("must be a string");
  177. }
  178. try { return require(str); } catch (e) { }
  179. return require(process.cwd() + '/' + str);
  180. };
  181. nThen(function (waitFor) {
  182. try {
  183. /* jshint -W054 */ // Suppress jshint warning on Function being a form of eval
  184. var func = new Function('file', 'require', 'fileName', 'console', 'builder', js);
  185. func.async = function () {
  186. return waitFor(function (result) {
  187. res = result;
  188. });
  189. };
  190. x = func.call(func,
  191. file,
  192. REQUIRE,
  193. fileName,
  194. console,
  195. builder);
  196. } catch (e) {
  197. err = e;
  198. err.message += "\nContent: [" + js + "]";
  199. clearTimeout(to);
  200. throw err;
  201. }
  202. }).nThen(function (waitFor) {
  203. if (err) { return; }
  204. res = res || x || '';
  205. clearTimeout(to);
  206. process.nextTick(function () { callback(undefined, res); });
  207. });
  208. };
  209. var debug = console.log;
  210. var preprocessBlock = function (block, builder, fileObj, fileName, callback) {
  211. // a block is an array of strings and arrays, any inside arrays must be
  212. // preprocessed first. deep first top to bottom.
  213. var error = false;
  214. var nt = nThen;
  215. block.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. block[i] = ret;
  221. }));
  222. }).nThen;
  223. });
  224. nt(function (waitFor) {
  225. if (error) { return; }
  226. var capture = block.join('');
  227. execJs(capture, builder, fileObj, fileName, waitFor(function (err, ret) {
  228. if (err) { throw err; }
  229. callback(undefined, ret);
  230. }));
  231. });
  232. };
  233. var preprocess = function (content, builder, fileObj, fileName, callback) {
  234. // <?js file.Test_mainFunc = "<?js return 'RootTest_'+file.RootTest_mainFunc; ?>" ?>
  235. // worse:
  236. // <?js file.Test_mainFunc = "<?js var done = this.async(); process.nextTick(done); ?>" ?>
  237. var flatArray = content.split(/(<\?js|\?>)/);
  238. var elems = [];
  239. var unflatten = function (array, startAt, out) {
  240. for (var i = startAt; i < array.length; i++) {
  241. /* jshint -W018 */ // Suppress jshint warning on ! being confusing
  242. if (!((i - startAt) % 2)) {
  243. out.push(array[i]);
  244. } else if (array[i] === '<?js') {
  245. var next = [];
  246. out.push(next);
  247. i = unflatten(array, i+1, next);
  248. } else if (array[i] === '?>') {
  249. return i;
  250. }
  251. }
  252. return i;
  253. };
  254. if (unflatten(flatArray, 0, elems) !== flatArray.length) {
  255. throw new Error();
  256. }
  257. var nt = nThen;
  258. elems.forEach(function (elem, i) {
  259. if (typeof(elem) === 'string') { return; }
  260. nt = nt(function (waitFor) {
  261. preprocessBlock(elem, builder, fileObj, fileName, waitFor(function (err, ret) {
  262. if (err) { throw err; }
  263. elems[i] = ret;
  264. }));
  265. }).nThen;
  266. });
  267. nt(function (waitFor) {
  268. callback(undefined, elems.join(''));
  269. });
  270. };
  271. var getFile = function ()
  272. {
  273. return {
  274. includes: [],
  275. links: [],
  276. cflags: [],
  277. oldmtime: 0
  278. };
  279. };
  280. var getObjectFile = function (cFile) {
  281. return cFile.replace(/[^a-zA-Z0-9_-]/g, '_') + '.o';
  282. };
  283. var getExecutableFile = function (cFile) {
  284. return cFile.replace(/[^a-zA-Z0-9_-]/g, '_');
  285. };
  286. var getFlags = function (state, fileName, includeDirs) {
  287. var flags = [];
  288. flags.push.apply(flags, state.cflags);
  289. flags.push.apply(flags, state['cflags'+fileName]);
  290. if (includeDirs) {
  291. for (var i = 0; i < state.includeDirs.length; i++) {
  292. if (flags[flags.indexOf(state.includeDirs[i])-1] === '-I') {
  293. continue;
  294. }
  295. flags.push('-I');
  296. flags.push(state.includeDirs[i]);
  297. }
  298. }
  299. for (var ii = flags.length-1; ii >= 0; ii--) {
  300. // might be undefined because splicing causes us to be off the end of the array
  301. if (typeof(flags[ii]) === 'string' && flags[ii][0] === '!') {
  302. var f = flags[ii].substring(1);
  303. flags.splice(ii, 1);
  304. var index;
  305. while ((index = flags.indexOf(f)) > -1) {
  306. flags.splice(index, 1);
  307. }
  308. }
  309. }
  310. return flags;
  311. };
  312. var currentlyCompiling = {};
  313. var compileFile = function (fileName, builder, tempDir, callback)
  314. {
  315. var state = builder.config;
  316. if (typeof(state.files[fileName]) !== 'undefined') {
  317. callback();
  318. return;
  319. }
  320. if (typeof(currentlyCompiling[fileName]) !== 'undefined') {
  321. currentlyCompiling[fileName].push(callback);
  322. return;
  323. } else {
  324. currentlyCompiling[fileName] = [];
  325. }
  326. currentlyCompiling[fileName].push(callback);
  327. //debug('\033[2;32mCompiling ' + fileName + '\033[0m');
  328. var preprocessed = state.buildDir + '/' + getObjectFile(fileName) + '.i';
  329. var outFile = state.buildDir + '/' + getObjectFile(fileName);
  330. var fileContent;
  331. var fileObj = getFile();
  332. nThen(function (waitFor) {
  333. (function () {
  334. //debug("CPP -MM");
  335. var flags = ['-E', '-MM'];
  336. flags.push.apply(flags, getFlags(state, fileName, true));
  337. flags.push(fileName);
  338. cc(state.gcc, flags, waitFor(function (err, output) {
  339. if (err) { throw err; }
  340. // replace the escapes and newlines
  341. output = output.replace(/ \\|\n/g, '').split(' ');
  342. // first 2 entries are crap
  343. output.splice(0, 2);
  344. for (var i = output.length-1; i >= 0; i--) {
  345. //console.log('Removing empty dependency [' +
  346. // state.gcc + ' ' + flags.join(' ') + ']');
  347. if (output[i] === '') {
  348. output.splice(i, 1);
  349. }
  350. }
  351. fileObj.includes = output;
  352. }));
  353. })();
  354. (function () {
  355. //debug("CPP");
  356. var flags = ['-E'];
  357. flags.push.apply(flags, getFlags(state, fileName, true));
  358. flags.push(fileName);
  359. cc(state.gcc, flags, waitFor(function (err, output) {
  360. if (err) { throw err; }
  361. fileContent = output;
  362. }));
  363. })();
  364. }).nThen(function (waitFor) {
  365. Fs.exists(preprocessed, waitFor(function (exists) {
  366. if (!exists) { return; }
  367. Fs.unlink(preprocessed, waitFor(function (err) {
  368. if (err) { throw err; }
  369. }));
  370. }));
  371. }).nThen(function (waitFor) {
  372. //debug("Preprocess");
  373. preprocess(fileContent, builder, fileObj, fileName, waitFor(function (err, output) {
  374. if (err) { throw err; }
  375. Fs.writeFile(preprocessed, output, waitFor(function (err) {
  376. if (err) { throw err; }
  377. }));
  378. // important, this will prevent the file from also being piped to gcc.
  379. fileContent = undefined;
  380. }));
  381. Fs.exists(outFile, waitFor(function (exists) {
  382. if (!exists) { return; }
  383. Fs.unlink(outFile, waitFor(function (err) {
  384. if (err) { throw err; }
  385. }));
  386. }));
  387. }).nThen(function (waitFor) {
  388. //debug("CC");
  389. var flags = ['-c', '-x', 'cpp-output', '-o', outFile];
  390. flags.push.apply(flags, getFlags(state, fileName, false));
  391. flags.push(preprocessed);
  392. cc(state.gcc, flags, waitFor(function (err) {
  393. if (err) { throw err; }
  394. fileObj.obj = outFile;
  395. }), fileContent);
  396. }).nThen(function (waitFor) {
  397. debug('\033[2;32mBuilding C object ' + fileName + ' complete\033[0m');
  398. state.files[fileName] = fileObj;
  399. var callbacks = currentlyCompiling[fileName];
  400. delete currentlyCompiling[fileName];
  401. callbacks.forEach(function (cb) { cb(); });
  402. });
  403. };
  404. /**
  405. * @param files state.files
  406. * @param mtimes a mapping of files to times for files for which the times are known
  407. * @param callback when done.
  408. */
  409. var getMTimes = function (files, mtimes, callback)
  410. {
  411. nThen(function (waitFor) {
  412. Object.keys(files).forEach(function (fileName) {
  413. mtimes[fileName] = mtimes[fileName] || 0;
  414. files[fileName].includes.forEach(function (incl) {
  415. mtimes[incl] = mtimes[incl] || 0;
  416. });
  417. });
  418. Object.keys(mtimes).forEach(function (fileName) {
  419. if (mtimes[fileName] !== 0) { return; }
  420. Fs.stat(fileName, waitFor(function (err, stat) {
  421. if (err) {
  422. waitFor.abort();
  423. callback(err);
  424. return;
  425. }
  426. mtimes[fileName] = stat.mtime.getTime();
  427. }));
  428. });
  429. }).nThen(function (waitFor) {
  430. callback(undefined, mtimes);
  431. });
  432. };
  433. var removeFile = function (state, fileName, callback)
  434. {
  435. //debug("remove " + fileName);
  436. nThen(function (waitFor) {
  437. // And every file which includes it
  438. Object.keys(state.files).forEach(function (file) {
  439. // recursion could remove it
  440. if (typeof(state.files[file]) === 'undefined') {
  441. return;
  442. }
  443. if (state.files[file].includes.indexOf(fileName) !== -1) {
  444. removeFile(state, file, waitFor());
  445. }
  446. });
  447. // we'll set the oldmtime on the file to 0 since it's getting rebuilt.
  448. state.oldmtimes[fileName] = 0;
  449. var f = state.files[fileName];
  450. if (typeof(f) === 'undefined') {
  451. return;
  452. }
  453. delete state.files[fileName];
  454. if (typeof(f.obj) === 'string') {
  455. Fs.unlink(f.obj, waitFor(function (err) {
  456. if (err && err.code !== 'ENOENT') {
  457. throw err;
  458. }
  459. }));
  460. }
  461. }).nThen(function (waitFor) {
  462. callback();
  463. });
  464. };
  465. var recursiveCompile = function (fileName, builder, tempDir, callback)
  466. {
  467. // Recursive compilation
  468. var state = builder.config;
  469. var doCycle = function (toCompile, parentStack, callback) {
  470. if (toCompile.length === 0) {
  471. callback();
  472. return;
  473. }
  474. nThen(function (waitFor) {
  475. var filefunc = function (file) {
  476. var stack = [];
  477. stack.push.apply(stack, parentStack);
  478. //debug("compiling " + file);
  479. stack.push(file);
  480. if (stack.indexOf(file) !== stack.length - 1) {
  481. throw new Error("Dependency loops are bad and you should feel bad\n" +
  482. "Dependency stack:\n" + stack.reverse().join('\n'));
  483. }
  484. compileFile(file, builder, tempDir, waitFor(function () {
  485. var toCompile = [];
  486. state.files[file].links.forEach(function (link) {
  487. if (link === file) {
  488. return;
  489. }
  490. toCompile.push(link);
  491. });
  492. doCycle(toCompile, stack, waitFor(function () {
  493. if (stack[stack.length - 1] !== file) {
  494. throw new Error();
  495. }
  496. stack.pop();
  497. }));
  498. }));
  499. };
  500. for (var file = toCompile.pop(); file; file = toCompile.pop()) {
  501. filefunc(file);
  502. }
  503. }).nThen(function (waitFor) {
  504. callback();
  505. });
  506. };
  507. doCycle([fileName], [], callback);
  508. };
  509. var getLinkOrder = function (fileName, files) {
  510. var completeFiles = [];
  511. var getFile = function (name) {
  512. var f = files[name];
  513. //debug('Resolving links for ' + name + ' ' + f);
  514. for (var i = 0; i < f.links.length; i++) {
  515. if (f.links[i] === name) {
  516. continue;
  517. }
  518. if (completeFiles.indexOf(f.links[i]) > -1) {
  519. continue;
  520. }
  521. getFile(f.links[i]);
  522. }
  523. completeFiles.push(name);
  524. };
  525. getFile(fileName);
  526. return completeFiles;
  527. };
  528. var needsToLink = function (fileName, state) {
  529. if (typeof(state.oldmtimes[fileName]) !== 'number') {
  530. return true;
  531. }
  532. if (state.oldmtimes[fileName] !== state.mtimes[fileName]) {
  533. return true;
  534. }
  535. var links = state.files[fileName].links;
  536. for (var i = 0; i < links.length; i++) {
  537. if (links[i] !== fileName && needsToLink(links[i], state)) {
  538. return true;
  539. }
  540. }
  541. return false;
  542. };
  543. var makeTime = function () {
  544. return function () {
  545. var oldTime = this.time || 0;
  546. var newTime = this.time = new Date().getTime();
  547. return newTime - oldTime;
  548. };
  549. };
  550. var compile = function (file, outputFile, builder, callback) {
  551. var state = builder.config;
  552. var tempDir;
  553. if (!needsToLink(file, state)) {
  554. process.nextTick(callback);
  555. return;
  556. }
  557. nThen(function (waitFor) {
  558. tempDir = tmpFile(state);
  559. Fs.mkdir(tempDir, waitFor(function (err) {
  560. if (err) { throw err; }
  561. }));
  562. }).nThen(function (waitFor) {
  563. recursiveCompile(file, builder, tempDir, waitFor());
  564. }).nThen(function (waitFor) {
  565. var linkOrder = getLinkOrder(file, state.files);
  566. for (var i = 0; i < linkOrder.length; i++) {
  567. linkOrder[i] = state.buildDir + '/' + getObjectFile(linkOrder[i]);
  568. }
  569. var ldArgs = [state.ldflags, '-o', outputFile, linkOrder, state.libs];
  570. debug('\033[1;31mLinking C executable ' + file + '\033[0m');
  571. cc(state.gcc, ldArgs, waitFor(function (err, ret) {
  572. if (err) { throw err; }
  573. }));
  574. }).nThen(function (waitFor) {
  575. Fs.readdir(tempDir, waitFor(function (err, files) {
  576. if (err) { throw err; }
  577. files.forEach(function (file) {
  578. Fs.unlink(tempDir + '/' + file, waitFor(function (err) {
  579. if (err) { throw err; }
  580. }));
  581. });
  582. }));
  583. }).nThen(function (waitFor) {
  584. Fs.rmdir(tempDir, waitFor(function (err) {
  585. if (err) { throw err; }
  586. }));
  587. }).nThen(function (waitFor) {
  588. if (callback) {
  589. callback();
  590. }
  591. });
  592. };
  593. var getStatePrototype = function (params) {
  594. var base = {
  595. includeDirs: ['.'],
  596. files: {},
  597. mtimes: {},
  598. cflags: [],
  599. ldflags: [],
  600. libs: [],
  601. rebuildIfChanges: [],
  602. rebuildIfChangesHash: undefined,
  603. tempDir: '/tmp',
  604. systemName: 'linux'
  605. };
  606. for (var key in params) {
  607. if (params.hasOwnProperty(key)) {
  608. if (typeof params[key] !== 'object') {
  609. base[key] = params[key];
  610. }
  611. }
  612. }
  613. return base;
  614. };
  615. /**
  616. * Get a copy of process.env with a few entries which are constantly changing removed.
  617. * This prevents isStaleState from returning true every time one builds in a different
  618. * window.
  619. */
  620. var normalizedProcessEnv = function () {
  621. var out = process.env;
  622. delete out.WINDOWID;
  623. delete out.OLDPWD;
  624. return out;
  625. };
  626. var getRebuildIfChangesHash = function (rebuildIfChanges, callback) {
  627. var ret = false;
  628. var hash = Crypto.createHash('sha256');
  629. var rebIfChg = [];
  630. nThen(function (waitFor) {
  631. rebuildIfChanges.forEach(function (fileName, i) {
  632. Fs.readFile(fileName, waitFor(function (err, ret) {
  633. if (err) { throw err; }
  634. rebIfChg[i] = ret;
  635. }));
  636. });
  637. hash.update(JSON.stringify(normalizedProcessEnv()));
  638. }).nThen(function (waitFor) {
  639. rebIfChg.forEach(function (data) {
  640. hash.update(data);
  641. });
  642. callback(hash.digest('hex'));
  643. });
  644. };
  645. var throwIfErr = function (err) { if (err) { throw err; } };
  646. var probeCompiler = function (state, callback) {
  647. nThen(function (waitFor) {
  648. var compilerType = state.compilerType = {
  649. isLLVM: false,
  650. isClang: false,
  651. isGCC: false,
  652. version: undefined
  653. };
  654. compiler(state.gcc, ['-v'], waitFor(function (ret, out, err) {
  655. if (ret !== 0) { throw new Error("Failed to probe compiler ret[" + ret + "]\n" + err); }
  656. if (/Apple LLVM version /.test(err)) {
  657. compilerType.isLLVM = true;
  658. if (/clang/.test(err)) {
  659. // Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)
  660. // Target: x86_64-apple-darwin14.4.0
  661. // Thread model: posix
  662. compilerType.isClang = true;
  663. compilerType.version = err.match(/Apple LLVM version ([^ ]+) /)[1];
  664. } else if (/gcc version /.test(err)) {
  665. // Using built-in specs.
  666. // Target: i686-apple-darwin11
  667. // Configured with: /private/var/tmp/llvmgcc42/llvmgcc42.......
  668. // Thread model: posix
  669. // gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)
  670. compilerType.isGCC = true;
  671. compilerType.version = err.match(/gcc version ([^ ]+) /)[1];
  672. }
  673. } else if (/clang version /.test(err)) {
  674. // FreeBSD clang version 3.0 (tags/RELEASE_30/final 145349) 20111210
  675. // Target: x86_64-unknown-freebsd10.0
  676. // Thread model: posix
  677. // clang version 3.2 (trunk)
  678. // Target: x86_64-unknown-linux-gnu
  679. // Thread model: posix
  680. compilerType.isLLVM = true;
  681. compilerType.isClang = true;
  682. compilerType.version = err.match(/clang version ([^ ]+) /)[1];
  683. } else if (/gcc version /.test(err)) {
  684. compilerType.isGCC = true;
  685. compilerType.version = err.match(/gcc version ([^ ]+) /)[1];
  686. }
  687. console.log(JSON.stringify(compilerType));
  688. }));
  689. }).nThen(callback);
  690. };
  691. process.on('exit', function () {
  692. console.log("Total build time: " + Math.floor(process.uptime() * 1000) + "ms.");
  693. });
  694. var stage = function (st, builder, waitFor) {
  695. builder.waitFor = waitFor;
  696. st(builder, waitFor);
  697. };
  698. var configure = module.exports.configure = function (params, configFunc) {
  699. // Track time taken for various steps
  700. var time = makeTime();
  701. time();
  702. if (typeof(params.systemName) !== 'string') {
  703. throw new Error("system not specified");
  704. }
  705. params.buildDir = params.buildDir || 'build_' + params.systemName;
  706. var version;
  707. var state;
  708. var builder;
  709. var buildStage = function () {};
  710. var testStage = function () {};
  711. var packStage = function () {};
  712. var successStage = function () {};
  713. var failureStage = function () {};
  714. var completeStage = function () {};
  715. nThen(function (waitFor) {
  716. // make the build directory
  717. Fs.exists(params.buildDir, waitFor(function (exists) {
  718. if (exists) { return; }
  719. Fs.mkdir(params.buildDir, waitFor(function (err) {
  720. if (err) { throw err; }
  721. }));
  722. }));
  723. }).nThen(function (waitFor) {
  724. // read out the state if it exists
  725. Fs.exists(params.buildDir + '/state.json', waitFor(function (exists) {
  726. if (!exists) { return; }
  727. Fs.readFile(params.buildDir + '/state.json', waitFor(function (err, ret) {
  728. if (err) { throw err; }
  729. state = JSON.parse(ret);
  730. }));
  731. }));
  732. }).nThen(function (waitFor) {
  733. if (process.env["CJDNS_RELEASE_VERSION"]) {
  734. version = '' + process.env["CJDNS_RELEASE_VERSION"];
  735. } else {
  736. GetVersion(waitFor(function(err, data) {
  737. if (err === null) {
  738. version = '' + data;
  739. version = version.replace(/(\r\n|\n|\r)/gm, "");
  740. } else {
  741. version = 'unknown';
  742. }
  743. }));
  744. }
  745. }).nThen(function (waitFor) {
  746. if (!state || !state.rebuildIfChanges) {
  747. // no state
  748. state = undefined;
  749. } else {
  750. getRebuildIfChangesHash(state.rebuildIfChanges, waitFor(function (rich) {
  751. if (rich !== state.rebuildIfChangesHash) {
  752. debug("rebuildIfChanges changed, rebuilding");
  753. state = undefined;
  754. }
  755. }));
  756. }
  757. }).nThen(function (waitFor) {
  758. debug("Initialize " + time() + "ms");
  759. // Do the configuration step
  760. if (state) {
  761. builder = mkBuilder(state);
  762. builder.config.version = version;
  763. return;
  764. }
  765. state = getStatePrototype(params);
  766. builder = mkBuilder(state);
  767. builder.config.version = version;
  768. probeCompiler(state, waitFor());
  769. }).nThen(function (waitFor) {
  770. configFunc(builder, waitFor);
  771. }).nThen(function (waitFor) {
  772. debug("Configure " + time() + "ms");
  773. if (state.rebuildIfChangesHash) {
  774. return;
  775. }
  776. if (state.rebuildIfChanges.indexOf(module.parent.filename) === -1) {
  777. // Always always rebuild if the makefile was changed.
  778. state.rebuildIfChanges.push(module.parent.filename);
  779. }
  780. getRebuildIfChangesHash(state.rebuildIfChanges, waitFor(function (rich) {
  781. state.rebuildIfChangesHash = rich;
  782. }));
  783. }).nThen(function (waitFor) {
  784. state.oldmtimes = state.mtimes;
  785. state.mtimes = {};
  786. Object.keys(state.oldmtimes).forEach(function (fileName) {
  787. Fs.stat(fileName, waitFor(function (err, stat) {
  788. if (err) {
  789. if (err.code === 'ENOENT') {
  790. // Doesn't matter as long as it's not referenced...
  791. debug("File [" + fileName + "] was removed");
  792. delete state.files[fileName];
  793. return;
  794. } else {
  795. throw err;
  796. }
  797. }
  798. state.mtimes[fileName] = stat.mtime.getTime();
  799. if (state.oldmtimes[fileName] !== stat.mtime.getTime()) {
  800. debug(fileName + ' is out of date, rebuilding');
  801. removeFile(state, fileName, waitFor());
  802. }
  803. }));
  804. });
  805. }).nThen(function (waitFor) {
  806. debug("Scan for out of date files " + time() + "ms");
  807. }).nThen(function (waitFor) {
  808. stage(buildStage, builder, waitFor);
  809. }).nThen(function (waitFor) {
  810. debug("Compile " + time() + "ms");
  811. var allFiles = {};
  812. Object.keys(state.files).forEach(function (fileName) {
  813. allFiles[fileName] = 1;
  814. state.files[fileName].includes.forEach(function (fileName) {
  815. allFiles[fileName] = 1;
  816. });
  817. });
  818. Object.keys(allFiles).forEach(function (fileName) {
  819. var omt = state.oldmtimes[fileName];
  820. if (omt > 0 && omt === state.mtimes[fileName]) {
  821. return;
  822. }
  823. builder.rebuiltFiles.push(fileName);
  824. });
  825. }).nThen(function (waitFor) {
  826. builder.tests.forEach(function (test) {
  827. test(waitFor(function (output, failure) {
  828. debug(output);
  829. if (failure) {
  830. builder.failure = true;
  831. }
  832. }));
  833. });
  834. }).nThen(function (waitFor) {
  835. if (builder.linters.length === 0) {
  836. return;
  837. }
  838. debug("Checking codestyle");
  839. var sema = Semaphore.create(64);
  840. builder.rebuiltFiles.forEach(function (fileName) {
  841. sema.take(waitFor(function (returnAfter) {
  842. Fs.readFile(fileName, waitFor(function (err, ret) {
  843. if (err) { throw err; }
  844. ret = ret.toString('utf8');
  845. nThen(function (waitFor) {
  846. builder.linters.forEach(function (linter) {
  847. linter(fileName, ret, waitFor(function (out, isErr) {
  848. if (isErr) {
  849. debug("\033[1;31m" + out + "\033[0m");
  850. builder.failure = true;
  851. }
  852. }));
  853. });
  854. }).nThen(returnAfter(waitFor()));
  855. }));
  856. }));
  857. });
  858. }).nThen(function (waitFor) {
  859. stage(testStage, builder, waitFor);
  860. }).nThen(function (waitFor) {
  861. if (builder.failure) { return; }
  862. debug("Test " + time() + "ms");
  863. builder.executables.forEach(function (array) {
  864. if (array[1] === array[0]) { return; }
  865. Fs.rename(array[0], array[1], waitFor(function (err) {
  866. // TODO(cjd): It would be better to know in advance whether to expect the file.
  867. if (err && err.code !== 'ENOENT') {
  868. throw err;
  869. }
  870. }));
  871. });
  872. }).nThen(function (waitFor) {
  873. if (builder.failure) { return; }
  874. stage(packStage, builder, waitFor);
  875. }).nThen(function (waitFor) {
  876. if (builder.failure) { return; }
  877. debug("Pack " + time() + "ms");
  878. getMTimes(state.files, state.mtimes, waitFor(function (err, mtimes) {
  879. if (err) { throw err; }
  880. state.mtimes = mtimes;
  881. debug("Get mtimes " + time() + "ms");
  882. }));
  883. }).nThen(function (waitFor) {
  884. if (builder.failure) { return; }
  885. // save state
  886. var stateJson = JSON.stringify(state, null, ' ');
  887. Fs.writeFile(state.buildDir + '/state.json', stateJson, waitFor(function (err) {
  888. if (err) { throw err; }
  889. debug("Save State " + time() + "ms");
  890. }));
  891. }).nThen(function (waitFor) {
  892. if (builder.failure) { return; }
  893. stage(successStage, builder, waitFor);
  894. }).nThen(function (waitFor) {
  895. if (!builder.failure) { return; }
  896. stage(failureStage, builder, waitFor);
  897. }).nThen(function (waitFor) {
  898. stage(completeStage, builder, waitFor);
  899. });
  900. var out = {
  901. build: function (x) { buildStage = x; return out; },
  902. test: function (x) { testStage = x; return out; },
  903. pack: function (x) { packStage = x; return out; },
  904. failure: function (x) { failureStage = x; return out; },
  905. success: function (x) { successStage = x; return out; },
  906. complete: function (x) { completeStage = x; return out; },
  907. };
  908. return out;
  909. };