generate-build-json.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. const fs = require('fs-extra');
  2. const path = require('path');
  3. const git = require('git-rev-sync');
  4. const buildfile = require('./build');
  5. const yargs = require('yargs')(process.argv.slice(2));
  6. const argv = yargs
  7. .usage('Usage: $0 -f <file>')
  8. .help('help')
  9. .alias('version', 'v')
  10. .option('help', {
  11. alias: 'h'
  12. })
  13. .option('file', {
  14. alias: 'f',
  15. type: 'string',
  16. requiresArg: true,
  17. describe: 'The target file path which would be generated.',
  18. })
  19. .option('dryrun', {
  20. type: 'boolean',
  21. describe: 'Display the generated content instead of saving to target file.',
  22. })
  23. .option('verbose', {
  24. alias: 'V',
  25. type: 'boolean',
  26. describe: 'Enable verbose log.',
  27. })
  28. .argv;
  29. function getBuildJson() {
  30. let commit = buildfile.gitCommit;
  31. try {
  32. commit = git.short();
  33. } catch (ex) {
  34. console.log('cannot get commit, because ' + ex);
  35. }
  36. return {
  37. gitCommit: commit
  38. };
  39. }
  40. if (!argv.file || argv.help) {
  41. yargs.showHelp();
  42. } else {
  43. const buildJsonObj = getBuildJson();
  44. const buildJsonContent = JSON.stringify(buildJsonObj);
  45. if (argv.dryrun) {
  46. console.log(buildJsonContent);
  47. } else {
  48. if (!fs.existsSync(path.dirname(argv.file))) {
  49. fs.mkdirpSync(path.dirname(argv.file));
  50. }
  51. fs.writeFileSync(argv.file, buildJsonContent, {
  52. encoding: 'UTF-8'
  53. });
  54. }
  55. }