forked from newrelic/node-newrelic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eslint-plugin-newrelic-header.js
71 lines (64 loc) · 1.59 KB
/
eslint-plugin-newrelic-header.js
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
/*
* Copyright 2024 New Relic Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
'use strict'
const headerTmpl = `
/*
* Copyright {{year}} New Relic Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
`.trim()
const rule = {
meta: {
type: 'layout',
fixable: 'whitespace',
schema: false
},
create(context) {
return {
Program(node) {
const src = context.sourceCode.getText()
if (hasHeader(src) === true) {
return
}
context.report({
loc: node.loc,
message: 'missing or invalid header',
fix(fixer) {
const rendered = headerTmpl.replace('{{year}}', new Date().getFullYear() + '') + '\n\n'
if (hasShebang(src) === true) {
return fixer.insertTextAfterRange([0, src.indexOf('\n')], '\n' + rendered)
}
return fixer.insertTextBefore(
node,
rendered
)
}
})
}
}
}
}
module.exports = {
meta: {
name: 'eslint-plugin-newrelic-header',
version: '1.0.0'
},
rules: {
header: rule
}
}
function hasShebang(src) {
return /^#!\s?\//.test(src)
}
function hasHeader(src) {
const headerLines = src.split('\n').slice(0, 5)
if (hasShebang(src) === true) {
headerLines.shift()
}
return headerLines[0] === '/*' &&
/ \* Copyright \d{4} New Relic Corporation\. All rights reserved\./.test(headerLines[1]) === true &&
/ \* SPDX-License-Identifier: Apache-2\.0/.test(headerLines[2]) === true &&
headerLines[3] === ' */'
}