Skip to content

Commit

Permalink
fix header plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
jsumners-nr committed Dec 27, 2024
1 parent af3771d commit e7d8868
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 1 deletion.
71 changes: 71 additions & 0 deletions eslint-plugin-newrelic-header.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,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] === ' */'
}
14 changes: 13 additions & 1 deletion eslint.config.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
/*
* Copyright 2024 New Relic Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/

'use strict'

const neostandard = require('neostandard')
const jsdoc = require('eslint-plugin-jsdoc')
const sonarjs = require('eslint-plugin-sonarjs')
const header = require('./eslint-plugin-newrelic-header.js')

// The new eslint configuration format is a simple array of configuration
// objects. See https://eslint.org/docs/latest/use/configure/configuration-files#configuration-objects.
Expand All @@ -20,9 +26,15 @@ const globalIgnores = {
}

const localConfig = {
plugins: {
header
},

rules: {
'consistent-return': 'off',
'header/header': 'off',

// Enable file header checking and autocorrection.
'header/header': 'error',

// This one enforces `!!thing` syntax, which some folks find difficult
// to read:
Expand Down

0 comments on commit e7d8868

Please sign in to comment.