unicode-bom.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * @fileoverview Require or disallow Unicode BOM
  3. * @author Andrew Johnston <https://github.com/ehjay>
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. /** @type {import('../shared/types').Rule} */
  10. module.exports = {
  11. meta: {
  12. type: "layout",
  13. docs: {
  14. description: "Require or disallow Unicode byte order mark (BOM)",
  15. recommended: false,
  16. url: "https://eslint.org/docs/rules/unicode-bom"
  17. },
  18. fixable: "whitespace",
  19. schema: [
  20. {
  21. enum: ["always", "never"]
  22. }
  23. ],
  24. messages: {
  25. expected: "Expected Unicode BOM (Byte Order Mark).",
  26. unexpected: "Unexpected Unicode BOM (Byte Order Mark)."
  27. }
  28. },
  29. create(context) {
  30. //--------------------------------------------------------------------------
  31. // Public
  32. //--------------------------------------------------------------------------
  33. return {
  34. Program: function checkUnicodeBOM(node) {
  35. const sourceCode = context.getSourceCode(),
  36. location = { column: 0, line: 1 },
  37. requireBOM = context.options[0] || "never";
  38. if (!sourceCode.hasBOM && (requireBOM === "always")) {
  39. context.report({
  40. node,
  41. loc: location,
  42. messageId: "expected",
  43. fix(fixer) {
  44. return fixer.insertTextBeforeRange([0, 1], "\uFEFF");
  45. }
  46. });
  47. } else if (sourceCode.hasBOM && (requireBOM === "never")) {
  48. context.report({
  49. node,
  50. loc: location,
  51. messageId: "unexpected",
  52. fix(fixer) {
  53. return fixer.removeRange([-1, 0]);
  54. }
  55. });
  56. }
  57. }
  58. };
  59. }
  60. };