utils.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // @ts-check
  2. "use strict";
  3. Object.defineProperty(exports, "__esModule", {
  4. value: true
  5. });
  6. function _export(target, all) {
  7. for(var name in all)Object.defineProperty(target, name, {
  8. enumerable: true,
  9. get: all[name]
  10. });
  11. }
  12. _export(exports, {
  13. indentRecursive: function() {
  14. return indentRecursive;
  15. },
  16. formatNodes: function() {
  17. return formatNodes;
  18. },
  19. readFileWithRetries: function() {
  20. return readFileWithRetries;
  21. },
  22. drainStdin: function() {
  23. return drainStdin;
  24. },
  25. outputFile: function() {
  26. return outputFile;
  27. }
  28. });
  29. const _fs = /*#__PURE__*/ _interop_require_default(require("fs"));
  30. const _path = /*#__PURE__*/ _interop_require_default(require("path"));
  31. function _interop_require_default(obj) {
  32. return obj && obj.__esModule ? obj : {
  33. default: obj
  34. };
  35. }
  36. function indentRecursive(node, indent = 0) {
  37. node.each && node.each((child, i)=>{
  38. if (!child.raws.before || !child.raws.before.trim() || child.raws.before.includes("\n")) {
  39. child.raws.before = `\n${node.type !== "rule" && i > 0 ? "\n" : ""}${" ".repeat(indent)}`;
  40. }
  41. child.raws.after = `\n${" ".repeat(indent)}`;
  42. indentRecursive(child, indent + 1);
  43. });
  44. }
  45. function formatNodes(root) {
  46. indentRecursive(root);
  47. if (root.first) {
  48. root.first.raws.before = "";
  49. }
  50. }
  51. async function readFileWithRetries(path, tries = 5) {
  52. for(let n = 0; n <= tries; n++){
  53. try {
  54. return await _fs.default.promises.readFile(path, "utf8");
  55. } catch (err) {
  56. if (n !== tries) {
  57. if (err.code === "ENOENT" || err.code === "EBUSY") {
  58. await new Promise((resolve)=>setTimeout(resolve, 10));
  59. continue;
  60. }
  61. }
  62. throw err;
  63. }
  64. }
  65. }
  66. function drainStdin() {
  67. return new Promise((resolve, reject)=>{
  68. let result = "";
  69. process.stdin.on("data", (chunk)=>{
  70. result += chunk;
  71. });
  72. process.stdin.on("end", ()=>resolve(result));
  73. process.stdin.on("error", (err)=>reject(err));
  74. });
  75. }
  76. async function outputFile(file, newContents) {
  77. try {
  78. let currentContents = await _fs.default.promises.readFile(file, "utf8");
  79. if (currentContents === newContents) {
  80. return; // Skip writing the file
  81. }
  82. } catch {}
  83. // Write the file
  84. await _fs.default.promises.mkdir(_path.default.dirname(file), {
  85. recursive: true
  86. });
  87. await _fs.default.promises.writeFile(file, newContents, "utf8");
  88. }