build-version.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/env node
  2. const fs = require("fs");
  3. const path = require("path");
  4. const versionFile = path.join("build", "version.json");
  5. const indexFile = path.join("build", "index.html");
  6. const versionDate = (date) => date.toISOString().replace(".000", "");
  7. const commitHash = () => {
  8. try {
  9. return require("child_process")
  10. .execSync("git rev-parse --short HEAD")
  11. .toString()
  12. .trim();
  13. } catch {
  14. return "none";
  15. }
  16. };
  17. const commitDate = (hash) => {
  18. try {
  19. const unix = require("child_process")
  20. .execSync(`git show -s --format=%ct ${hash}`)
  21. .toString()
  22. .trim();
  23. const date = new Date(parseInt(unix) * 1000);
  24. return versionDate(date);
  25. } catch {
  26. return versionDate(new Date());
  27. }
  28. };
  29. const getFullVersion = () => {
  30. const hash = commitHash();
  31. return `${commitDate(hash)}-${hash}`;
  32. };
  33. const data = JSON.stringify(
  34. {
  35. version: getFullVersion(),
  36. },
  37. undefined,
  38. 2,
  39. );
  40. fs.writeFileSync(versionFile, data);
  41. // https://stackoverflow.com/a/14181136/8418
  42. fs.readFile(indexFile, "utf8", (error, data) => {
  43. if (error) {
  44. return console.error(error);
  45. }
  46. const result = data.replace(/{version}/g, getFullVersion());
  47. fs.writeFile(indexFile, result, "utf8", (error) => {
  48. if (error) {
  49. return console.error(error);
  50. }
  51. });
  52. });