summaryrefslogtreecommitdiffstats
path: root/remote/test/puppeteer/.eslintplugin.js
blob: 0e61040f45fb6b8e35c01e855b1ba48ec42f4d2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const prettier = require('prettier');

const cleanupBlockComment = value => {
  return value
    .trim()
    .split('\n')
    .map(value => {
      value = value.trim();
      if (value.startsWith('*')) {
        value = value.slice(1);
        if (value.startsWith(' ')) {
          value = value.slice(1);
        }
      }
      return value.trimEnd();
    })
    .join('\n')
    .trim();
};

const format = (value, offset, prettierOptions) => {
  return prettier
    .format(value, {
      ...prettierOptions,
      // This is the print width minus 3 (the length of ` * `) and the offset.
      printWidth: prettierOptions.printWidth - (offset + 3),
    })
    .trim();
};

const buildBlockComment = (value, offset) => {
  const spaces = ' '.repeat(offset);
  const lines = value.split('\n').map(line => {
    return ` * ${line}`;
  });
  lines.unshift('/**');
  lines.push(' */');
  lines.forEach((line, i) => {
    lines[i] = `${spaces}${line}`;
  });
  return lines.join('\n');
};

/**
 * @type import("eslint").Rule.RuleModule
 */
const rule = {
  meta: {
    type: 'suggestion',
    docs: {
      description: 'Enforce Prettier formatting on comments',
      recommended: false,
    },
    fixable: 'code',
    schema: [],
    messages: {},
  },

  create(context) {
    const prettierOptions = {
      printWidth: 80,
      ...prettier.resolveConfig.sync(context.getPhysicalFilename()),
      parser: 'markdown',
    };
    for (const comment of context.getSourceCode().getAllComments()) {
      switch (comment.type) {
        case 'Block': {
          const offset = comment.loc.start.column;
          const value = cleanupBlockComment(comment.value);
          const formattedValue = format(value, offset, prettierOptions);
          if (formattedValue !== value) {
            context.report({
              node: comment,
              message: `Comment is not formatted correctly.`,
              fix(fixer) {
                return fixer.replaceText(
                  comment,
                  buildBlockComment(formattedValue, offset).trimStart()
                );
              },
            });
          }
          break;
        }
      }
    }
    return {};
  },
};

module.exports = {
  rules: {
    'prettier-comments': rule,
  },
};