stuk / eslint-plugin-header Goto Github PK
View Code? Open in Web Editor NEWESLint plugin to ensure that files begin with given comment
License: MIT License
ESLint plugin to ensure that files begin with given comment
License: MIT License
Given the following .eslintrc:
{
"plugins": [
"header"
],
"rules": {
"header/header": [2, "block", "Copyright 2016"]
}
}
If a file has exactly the comment:
/*Copyright 2016*/
it will pass linting, but if the first comment is instead:
/* Copyright 2016 */
(not the whitespace) it will fail. I'd like the ability to specify a string pattern or regular expression for headers to be matched against.
It would be really nice, if it would be possible to automatically add e.g. current year instead of using hard coded values.
In VSCode there is the possibility to use e.g. $CURRENT_YEAR
in the snippets.
We have a file with shebang header (because of Mac users).
We have core.autocrlf=true therefore the line endings on Macs are \n
and Win \r\n
.
When checking headers on Windows it never finds headers. It has to detect them in a file starting with:
#!/usr/bin/env node\r\n/**\r\n * Copyright\r\n */
There is a little mistake in hasHeader
method:
var m = src.match(/(\r\n|\r|\n)/);
does not fit to the:
src = src.slice(m.index + 1);
- in case of Windows' EOL the are two characters instead of one.
I have a fix proposition in this pull request
I have a repo in which different files should have different copyrights. Such files are separated by different folders. Is there a way to configure different copyrights for different relative paths?
Thanks for a neat project, we started using this in a new project a few weeks ago and just like @maksnester requested in one of the issue threads we'd like to have a newline after our header. I made a PR.
I am trying to use a template header from file but due to the fact that it trims when loading from file it is removing the trailing new lines which I require due to microsoft/TypeScript#12307 (comment). I am also unable to specify a newline going the route with a single argument.
It would be good to either not trim the comment when loading from a file (though this would be a major breaking change as some users may depend on it) or maybe support adding newlines when using the template file?
As far as I can tell there is not a way to have an optional pattern.
This would be nice for matching pragmas that may not be in every file.
using eslint version 9.4.0 with eslint-plugin-header gives this error -
Error: Key "rules": Key "header/header":
Value ["block",{"pattern":"Copyright \\d{4}, CompanyName, Inc. All rights reserved.","template":"Copyright 2024, CompanyName, Inc. All rights reserved."}] should NOT have more than 0 items.
at RuleValidator.validate (/Users/vineet/Documents/learn_eslint/node_modules/eslint/lib/config/rule-validator.js:170:27)
at [finalizeConfig] (/Users/vineet/Documents/learn_eslint/node_modules/eslint/lib/config/flat-config-array.js:317:23)
at FlatConfigArray.getConfigWithStatus (/Users/vineet/Documents/learn_eslint/node_modules/@eslint/config-array/dist/cjs/index.cjs:1145:55)
at FlatConfigArray.getConfig (/Users/vineet/Documents/learn_eslint/node_modules/@eslint/config-array/dist/cjs/index.cjs:1163:15)
at ESLint.calculateConfigForFile (/Users/vineet/Documents/learn_eslint/node_modules/eslint/lib/eslint/eslint.js:1169:24)
at async ESLint.isPathIgnored (/Users/vineet/Documents/learn_eslint/node_modules/eslint/lib/eslint/eslint.js:1191:24)
see https://github.com/firefoxNX/learn_eslint to reproduce the issue.
Updating to ESLint: 7.0.0, it seems like this plug-in stopped working.
In the previously working build-chain, I now get
INFO] Running 'npm ci' in /home/travis/build/opencast/opencast/modules/lti
[INFO] added 143 packages in 2.609s
...
[INFO] Running 'npm run eslint' in /home/travis/build/opencast/opencast/modules/lti
[INFO]
[INFO] > opencast-lit-tools@ eslint /home/travis/build/opencast/opencast/modules/lti
[INFO] > eslint --config ../../docs/checkstyle/eslintrc.js src/main/resources/
[INFO]
[ERROR]
[ERROR] Oops! Something went wrong! :(
[ERROR]
[ERROR] ESLint: 7.0.0
[ERROR]
[ERROR] ESLint couldn't find the plugin "eslint-plugin-header".
[ERROR]
[ERROR] (The package "eslint-plugin-header" was not found when loaded as a Node module from the directory "/home/travis/build/opencast/opencast/docs/checkstyle".)
[ERROR]
[ERROR] It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:
[ERROR]
[ERROR] npm install eslint-plugin-header@latest --save-dev
[ERROR]
[ERROR] The plugin "eslint-plugin-header" was referenced from the config file in "--config".
[ERROR]
[ERROR] If you still can't figure out the problem, please stop by https://gitter.im/eslint/eslint to chat with the team.
$ npm audit
=== npm audit security report ===
# Run npm install --save-dev [email protected] to resolve 3 vulnerabilities
SEMVER WARNING: Recommended action is a potentially breaking change
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Low │ Regular Expression Denial of Service │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package │ debug │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ mocha [dev] │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path │ mocha > debug │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info │ https://nodesecurity.io/advisories/534 │
└───────────────┴──────────────────────────────────────────────────────────────┘
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ High │ Regular Expression Denial of Service │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package │ minimatch │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ mocha [dev] │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path │ mocha > glob > minimatch │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info │ https://nodesecurity.io/advisories/118 │
└───────────────┴──────────────────────────────────────────────────────────────┘
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Critical │ Command Injection │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package │ growl │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ mocha [dev] │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path │ mocha > growl │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info │ https://nodesecurity.io/advisories/146 │
└───────────────┴──────────────────────────────────────────────────────────────┘
# Run npm install --save-dev [email protected] to resolve 1 vulnerability
SEMVER WARNING: Recommended action is a potentially breaking change
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Low │ Prototype Pollution │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package │ lodash │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ eslint [dev] │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path │ eslint > inquirer > lodash │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info │ https://nodesecurity.io/advisories/577 │
└───────────────┴──────────────────────────────────────────────────────────────┘
found 4 vulnerabilities (2 low, 1 high, 1 critical) in 395 scanned packages
4 vulnerabilities require semver-major dependency updates.
My file starts with // @flow
, but that comment gets erased with autofix.
I'll gladly fix this, I'm just wondering if it's ok that I completely remove the replacing behavior. I think it was meant to replace wrong headers, but in reality it's replacing any first non-shebang comment, which is not always what we want.
Or maybe we could measure how closely the header is matching given pattern using string-similarity and decide if it's a wrong header or an unrelated comment?
tl;dr for anyone who doesn't feel like reading all of these comments, basically the plugin cannot know whether the existing header comment is an old header that should be replaced (e.g. the year changed) or an unrelated comment. This issue was raised before v3 was released, i.e. before the pattern
option, so now we're discussing how we can use it, and ESLint suggestions, to our advantage.
Hi, we are using your module in VS Code and would like to provide proper attribution.
Based on the repository's package.json
, Here is how we are currently attributing the module:
MIT License
Copyright (c) 2015 - present, Stuart Knightley
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Can you add a top-level LICENSE.md
with the text so that everyone can attribute your work correctly?
Thanks in advance!
Right now this library can detect if a given header is in violation of the rules specified in a pattern. If the pattern is partially matched, it would be nice to be able to reference capture groups in the pattern and apply those capture groups into the template (if matched), otherwise leave blank.
For example:
Say my header & configuration looked like the following:
header:
// Copyright 2017-2020 Uber Technologies Inc.
rule:
const currentYear = (new Date()).getFullYear(); // = '2020'
...
{
pattern: ` Copyright (20\\d{2}\\-)?${currentYear} Uber Technologies Inc\.`,
template: ` Copyright ${currentYear} Uber Technologies Inc.`,
}
and time ticked over to 2021
header (fixed):
// Copyright 2021 Uber Technologies Inc.
header:
// Copyright 2017-2020 Uber Technologies Inc.
rule:
const currentYear = (new Date()).getFullYear(); // = '2020'
...
{
pattern: ` Copyright (?<firstYear>20\\d{2}\\-)?${currentYear} Uber Technologies Inc\.`,
template: ` Copyright (\\k<firstYear>)${currentYear} Uber Technologies Inc.`,
}
When the year ticks over to 2021, it would be nice if it updated current year only, and left first year as-is.
header (fixed):
// Copyright 2017-2021 Uber Technologies Inc.
Currently if the first line is emtpy in the source file and the header starts at line 2 the fixer causes the header to be output many(non consistent but 10+ times) times in succession.
Hello 🙂
Header comments in my project files always contain a few words of description of what the file is and what it does. Now, depending on whether it is a huge file or not, the description may be single- or multiline. I have tried to construct a config that would match my comment in both cases, so I came up with a regex containing a newline and a multiplier symbol, such as: .+(\n.+)*
. Unfortunately, the header plugin does not match any comments if the regex contains \n
.
How can I make the plugin match newlines or otherwise prepare a proper config for a case when the number of lines of description is not known beforehand?
Kind regards,
Hubert
If a file has a file header, say for the year 2018, and if I then change the template to 2019 and run autofix, the file header will be correctly replaced, but also adds a blank line after the file header. It does that for every autofix. So over the years, blank lines will pile up.
Is that a known issue?
Example:
/* ***
* Copyright 2018
*** */
console.log("hello");
When now the template is changed to use 2019, after auto-fix the file will look like this:
/* ***
* Copyright 2019
*** */
console.log("hello");
Again, when the template is changed again to say 2020, the file will be auto-fixed to:
/* ***
* Copyright 2020
*** */
console.log("hello");
Issue:
When using the regex pattern/template format like:
"header/header": [2, "block", [
{"pattern": " Copyright \\d{4}", "template": " Copyright 2021"},
"My Company"
]]
Each file is reporting as incorrect header. Using the original method of pointing to a .txt
file works correctly, so I know plugin is functioning. I've tried every combination of not providing template, or doing "line"
instead of block and none of them work when providing a template.
This is with eslint 7.6 and 7.25 (updating eslint did not fix the issue)
In case you have a very long copyright that spans several lines, you want to use the array variant. eg:
'header/header': [2, 'block', ['',
' * Copyright 2018 Company. All rights reserved.',
' * This file is licensed to you under the Apache License, Version 2.0 (the "License");',
' * you may not use this file except in compliance with the License. You may obtain a copy',
' * of the License at http://www.apache.org/licenses/LICENSE-2.0',
' *',
' * Unless required by applicable law or agreed to in writing, software distributed under',
' * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS',
' * OF ANY KIND, either express or implied. See the License for the specific language',
' * governing permissions and limitations under the License.',
' ',
]]
but this is a problem when the year changes. so it would be cool to do:
'header/header': [2, 'block', ['',
/ \* Copyright \d{4} Company\. All rights reserved\./,
' * This file is licensed to you under the Apache License, Version 2.0 (the "License");',
' * you may not use this file except in compliance with the License. You may obtain a copy',
' * of the License at http://www.apache.org/licenses/LICENSE-2.0',
' *',
' * Unless required by applicable law or agreed to in writing, software distributed under',
' * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS',
' * OF ANY KIND, either express or implied. See the License for the specific language',
' * governing permissions and limitations under the License.',
' ',
]]
but looking at the code, it currently just concatenates the array and matches with the entire comment.
if matching is done with a pattern, then the plugin can't fix wrong headers.
if we could specify a template for those lines, fixing would be possible.
for example:
"rules": {
"header/header": [2, "block", [
{ pattern: "Copyright \\d{4}", template: "Copyright 2019" },
"My Company"
]]
}
Hey Stewart!
It'd be nice to have clearer error messages. Right now "header error" is a bit generic and might be confusing.
We're ready to provide a PR, but I wanted to discuss solutions. Would it make sense to make an expectedHeader
option to provide an exact expected message value?
Expected file to start with:
// Copyright 2017 Cie Name Ltd.
This would allow to pass filled copyright message that is easy to copy/paste.
I feel an auto-fixer (eg eslint --fix
) would also require such an option.
Let's say I have a file with an existing comment:
// log 1
console.log(1);
Is there a way I can prevent eslint-plugin-header from removing the existing comment, and prepend the header template instead?
First of all: I love your plugin! It saved me from the cumbersome task of adding a license header to all code that I write during business hours. 🙇
In my config I am using the "template"
functionality and I was wondering if it is possible to add placeholders to it so that the current year can be used?
Example:
"header/header": [
"error",
"block",
[
{
"pattern": "Copyright",
"template": "\r\n * Title\r\n * Copyright ({{ currentYear }}) 2021 Company\r\n"
}
],
2
]
To build this feature a templating engine like "Nunjucks" could be used: https://mozilla.github.io/nunjucks/
I was looking at #12 and figured having some sort of CI like Travis would catch errors like this faster and speed up the review cycle :)
It would be nice if this package can support .vue file.
leadingComments[0]
is HTML in .vue file.
I have a CLI tool written in TypeScript which needs to have a Shebang in the top of the file. Thus the copyright header has to follow afterwards and this is not recognized with my config:
"header/header": [
"error",
"block",
[
{
"pattern": "Copyright",
"template": "Copyright Test"
}
],
2
],
cli.ts
#!/usr/bin/env node
/*
* Copyright (C) 2021
*/
// Some code here...
Using rule:
'header/header': [2, 'line', 'my header comment.']
with file:
// my header comment.
console.log(1);
reports incorrect header
. Changing rule to:
'header/header': [2, 'line', ' my header comment.']
will not report error and unblocks use.
In both rule cases --fix
will produce:
// my header comment.
console.log(1);
if error is detected. (Added line per issue #24 Autofix adds new line has been removed.)
In my setup, I am using eslint 6.8.0
.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.