run-prettier.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. "use strict";
  2. const prettier = require("prettier");
  3. const fs = require("fs");
  4. const chalk = require("chalk");
  5. /**
  6. *
  7. * Runs prettier and later prints the output configuration
  8. *
  9. * @param {String} outputPath - Path to write the config to
  10. * @param {Node} source - AST to write at the given path
  11. * @param {Function} cb - executes a callback after execution if supplied
  12. * @returns {Function} Writes a file at given location and prints messages accordingly
  13. */
  14. module.exports = function runPrettier(outputPath, source, cb) {
  15. function validateConfig() {
  16. let prettySource;
  17. let error;
  18. try {
  19. prettySource = prettier.format(source, {
  20. singleQuote: true,
  21. useTabs: true,
  22. tabWidth: 1
  23. });
  24. } catch (err) {
  25. process.stdout.write(
  26. "\n" +
  27. chalk.yellow(
  28. `WARNING: Could not apply prettier to ${outputPath}` +
  29. " due validation error, but the file has been created\n"
  30. )
  31. );
  32. prettySource = source;
  33. error = err;
  34. }
  35. if (cb) {
  36. return cb(error);
  37. }
  38. return fs.writeFileSync(outputPath, prettySource, "utf8");
  39. }
  40. return fs.writeFile(outputPath, source, "utf8", validateConfig);
  41. };