Skip to content

feat: add the "valid-license" rule #786

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ The default settings don't conflict, and Prettier plugins can quickly fix up ord
| [restrict-dependency-ranges](docs/rules/restrict-dependency-ranges.md) | Restricts the range of dependencies to allow or disallow specific types of ranges. | | | 💡 | |
| [sort-collections](docs/rules/sort-collections.md) | Dependencies, scripts, and configuration values must be declared in alphabetical order. | ✔️ ✅ | 🔧 | | |
| [unique-dependencies](docs/rules/unique-dependencies.md) | Checks a dependency isn't specified more than once (i.e. in `dependencies` and `devDependencies`) | ✔️ ✅ | | 💡 | |
| [valid-license](docs/rules/valid-license.md) | Enforce the 'license' field to be a specific value/values | | | | |
| [valid-local-dependency](docs/rules/valid-local-dependency.md) | Checks existence of local dependencies in the package.json | ✔️ ✅ | | | |
| [valid-name](docs/rules/valid-name.md) | Enforce that package names are valid npm package names | ✔️ ✅ | | | |
| [valid-package-def](docs/rules/valid-package-def.md) | Enforce that package.json has all properties required by the npm spec | | | | ❌ |
Expand Down
102 changes: 102 additions & 0 deletions docs/rules/valid-license.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# valid-license

💼 This rule is enabled in the ✅ `recommended` config.

<!-- end auto-generated rule header -->

This rule applies two validations to the `"license"` property:

- It must be a string rather than any other data type
- If provided, it's value should match one of the values provided in the options

Example of **incorrect** code for this rule:

When the rule is configured with

```json
{
"valid-license": ["error", "GPL"]
}
```

```json
{
"license": "MIT"
}
```

When the rule is configured with

```json
{
"valid-license": ["error", ["MIT", "GPL"]]
}
```

```json
{
"license": "Apache"
}
```

Example of **correct** code for this rule:

When the rule is configured with

```json
{
"valid-license": ["error"]
}
```

```json
{
"license": "GPL"
}
```

```json
{
"license": "Apache"
}
```

```json
{
"license": "Custom License Value"
}
```

When the rule is configured with

```json
{
"valid-license": ["error", "GPL"]
}
```

```json
{
"license": "GPL"
}
```

When the rule is configured with

```json
{
"valid-license": ["error", ["Apache", "MIT"]]
}
```

```json
{
"license": "Apache"
}
```

```json
{
"license": "MIT"
}
```
2 changes: 2 additions & 0 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { rules as requireRules } from "./rules/require-properties.js";
import { rule as restrictDependencyRanges } from "./rules/restrict-dependency-ranges.js";
import { rule as sortCollections } from "./rules/sort-collections.js";
import { rule as uniqueDependencies } from "./rules/unique-dependencies.js";
import { rule as validLicense } from "./rules/valid-license.js";
import { rule as validLocalDependency } from "./rules/valid-local-dependency.js";
import { rule as validName } from "./rules/valid-name.js";
import { rule as validPackageDefinition } from "./rules/valid-package-definition.js";
Expand All @@ -34,6 +35,7 @@ const rules: Record<string, PackageJsonRuleModule> = {
"restrict-dependency-ranges": restrictDependencyRanges,
"sort-collections": sortCollections,
"unique-dependencies": uniqueDependencies,
"valid-license": validLicense,
"valid-local-dependency": validLocalDependency,
"valid-name": validName,
"valid-package-definition": validPackageDefinition,
Expand Down
87 changes: 87 additions & 0 deletions src/rules/valid-license.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import type { AST as JsonAST } from "jsonc-eslint-parser";

import * as ESTree from "estree";

import { createRule } from "../createRule.js";

export type AllowedValues = string | string[] | undefined;
export type Options = [AllowedValues];

export function generateReportData(allowed: string[]) {
return {
allowed: allowed.map((v) => `'${v}'`).join(","),
multiple: allowed.length > 1 ? " one of" : "",
};
}

function forceToArray<T>(item: T | T[]): T[] {
return Array.isArray(item) ? item : [item];
}

export const rule = createRule<Options>({
create(context) {

const allowedValues =
context.options[0] === undefined ? undefined : forceToArray(context.options[0]);

return {
"Program > JSONExpressionStatement > JSONObjectExpression > JSONProperty[key.value=license]"(
node: JsonAST.JSONProperty,
) {
if (
node.value.type !== "JSONLiteral" ||
typeof node.value.value !== "string"
) {
context.report({
messageId: "nonString",
node: node.value as unknown as ESTree.Node,
});
return;
}

if (
allowedValues !== undefined &&
!allowedValues.includes(node.value.value)
) {
context.report({
data: generateReportData(allowedValues),
loc: node.loc,
messageId: "invalidValue",
});
}
},
};
},

meta: {
docs: {
category: "Best Practices",
description:
"Enforce the 'license' field to be a specific value/values",
recommended: false,
},
messages: {
invalidValue: '"license" must be{{multiple}} {{allowed}}"',
nonString: '"license" must be a string"',
},
schema: {
items: [
{
oneOf: [
{
items: {
type: "string",
},
type: "array",
},
{
type: "string",
},
],
},
],
type: "array",
},
type: "problem",
},
});
82 changes: 82 additions & 0 deletions src/tests/rules/valid-license.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { generateReportData, rule } from "../../rules/valid-license.js";
import { ruleTester } from "./ruleTester.js";

ruleTester.run("valid-license", rule, {
invalid: [
{
code: JSON.stringify({
license: "CC BY-SA",
name: "some-test-package",
}),
errors: [
{
data: generateReportData(["GPL"]),
messageId: "invalidValue",
},
],
name: "Invalid with single valid value",
options: ["GPL"],
},
{
code: JSON.stringify({
license: "Apache",
name: "some-test-package",
}),
errors: [
{
data: generateReportData(["MIT", "GPL"]),
messageId: "invalidValue",
},
],
name: "Invalid with multiple valid values",
options: [["MIT", "GPL"]],
},
{
code: JSON.stringify({
license: 1234,
name: "some-test-package",
}),
errors: [
{
data: generateReportData(["GPL"]),
messageId: "nonString",
},
],
name: "Invalid property type",
options: ["GPL"],
},
],
valid: [
{
code: JSON.stringify({
license: "Apache",
name: "some-test-package",
}),
name: "Valid value with no configuration",
options: [],
},
{
code: JSON.stringify({
license: "Apache",
name: "some-test-package",
}),
name: "Valid value from single valid value",
options: ["Apache"],
},
{
code: JSON.stringify({
license: "GPL",
name: "some-test-package",
}),
name: "Valid value from multiple valid values",
options: [["MIT", "GPL"]],
},
{
code: JSON.stringify({
name: "some-test-package",
}),
name: "Missing property",
options: [["MIT", "GPL"]],
},
],
});