39 | {/* Noncompliant: these properties can be grouped together in the "margin" property */}
40 |
;
41 | ```
42 |
43 | ```jsx
44 |
45 | const property = styleAttribute.value.expression.properties.find(
46 | (prop) =>
47 | forbiddenProperties.some((forbidProp) =>
48 | prop.key.name.includes(forbidProp),
49 | ),
50 | );
51 | if (property != null) {
52 | context.report({
53 | node: property,
54 | messageId: "AvoidCSSAnimations",
55 | data: {
56 | attribute: property.key.name,
57 | },
58 | });
59 | }
60 | }
61 | },
62 | };
63 | },
64 | };
65 |
--------------------------------------------------------------------------------
/eslint-plugin/lib/rules/avoid-high-accuracy-geolocation.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | const geolocationLibrariesMethods = {
22 | "expo-location": ["enableNetworkProviderAsync"],
23 | };
24 |
25 | /** @type {import("eslint").Rule.RuleModule} */
26 | module.exports = {
27 | meta: {
28 | type: "suggestion",
29 | docs: {
30 | description: "Avoid using high accuracy geolocation in web applications",
31 | category: "eco-design",
32 | recommended: "warn",
33 | },
34 | messages: {
35 | AvoidUsingAccurateGeolocation: "Avoid using high accuracy geolocation",
36 | },
37 | schema: [],
38 | },
39 | create: function (context) {
40 | const librariesFoundInImports = [];
41 |
42 | return {
43 | ImportDeclaration(node) {
44 | const currentLibrary = node.source.value;
45 |
46 | if (geolocationLibrariesMethods[currentLibrary]) {
47 | librariesFoundInImports.push(currentLibrary);
48 | }
49 | },
50 | MemberExpression(node) {
51 | if (librariesFoundInImports.length === 0) {
52 | return;
53 | }
54 |
55 | if (
56 | librariesFoundInImports.some((library) =>
57 | geolocationLibrariesMethods[library].includes(node.property.name),
58 | )
59 | ) {
60 | reportAvoidUsingAccurateGeolocation(context, node);
61 | }
62 | },
63 | Property(node) {
64 | if (
65 | node?.key.name === "enableHighAccuracy" &&
66 | node?.value.value === true
67 | ) {
68 | reportAvoidUsingAccurateGeolocation(context, node);
69 | }
70 | },
71 | };
72 | },
73 | };
74 |
75 | function reportAvoidUsingAccurateGeolocation(context, node) {
76 | context.report({ node, messageId: "AvoidUsingAccurateGeolocation" });
77 | }
78 |
--------------------------------------------------------------------------------
/eslint-plugin/lib/rules/avoid-keep-awake.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | const keepAwakeLibrariesMethods = {
22 | "expo-keep-awake": ["activateKeepAwake", "useKeepAwake"],
23 | };
24 |
25 | /** @type {import("eslint").Rule.RuleModule} */
26 | module.exports = {
27 | meta: {
28 | type: "suggestion",
29 | docs: {
30 | description: "Avoid screen keep awake",
31 | category: "eco-design",
32 | recommended: "warn",
33 | },
34 | messages: {
35 | AvoidKeepAwake: "Avoid screen keep awake",
36 | },
37 | schema: [],
38 | },
39 | create: function (context) {
40 | const librariesFoundInImports = [];
41 |
42 | return {
43 | ImportDeclaration(node) {
44 | const currentLibrary = node.source.value;
45 |
46 | if (keepAwakeLibrariesMethods[currentLibrary]) {
47 | librariesFoundInImports.push(currentLibrary);
48 | }
49 | },
50 | CallExpression(node) {
51 | if (librariesFoundInImports.length === 0) {
52 | return;
53 | }
54 |
55 | if (
56 | librariesFoundInImports.some((library) =>
57 | keepAwakeLibrariesMethods[library].includes(node.callee.name),
58 | )
59 | ) {
60 | context.report({ node, messageId: "AvoidKeepAwake" });
61 | }
62 | },
63 | };
64 | },
65 | };
66 |
--------------------------------------------------------------------------------
/eslint-plugin/lib/rules/limit-db-query-results.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | /** @type {import('eslint').Rule.RuleModule} */
22 | module.exports = {
23 | meta: {
24 | type: "suggestion",
25 | docs: {
26 | description: "Should limit the number of returns for a SQL query",
27 | category: "eco-design",
28 | recommended: "warn",
29 | },
30 | messages: {
31 | LimitTheNumberOfReturns:
32 | "Try and limit the number of data returned for a single query (by using the LIMIT keyword for example)",
33 | },
34 | schema: [],
35 | },
36 | create(context) {
37 | //list of limiting clauses to check against
38 | const limitingClauses = [
39 | "LIMIT",
40 | "TOP",
41 | "ROW_NUMBER",
42 | "FETCH FIRST",
43 | "WHERE",
44 | ];
45 |
46 | // List of known SQL client methods or functions
47 | const sqlClientMethods = ["query", "execute", "run"];
48 |
49 | return {
50 | // Detect SQL queries in string literals
51 | Literal: function (node) {
52 | if (typeof node.value == "string") {
53 | const query = node.value.toUpperCase();
54 | if (
55 | query.includes("SELECT") &&
56 | query.includes("FROM") &&
57 | !limitingClauses.some((clause) => query.includes(clause))
58 | ) {
59 | // Check if the query is used within a SQL client
60 | const parent = node.parent;
61 |
62 | if (
63 | parent?.type === "CallExpression" &&
64 | parent.callee.type === "MemberExpression" &&
65 | sqlClientMethods.includes(parent.callee.property.name)
66 | ) {
67 | context.report({ node, messageId: "LimitTheNumberOfReturns" });
68 | }
69 | }
70 | }
71 | },
72 | };
73 | },
74 | };
75 |
--------------------------------------------------------------------------------
/eslint-plugin/lib/rules/no-empty-image-src-attribute.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | /** @type {import('eslint').Rule.RuleModule} */
22 | module.exports = {
23 | meta: {
24 | type: "suggestion",
25 | docs: {
26 | description: "Disallow usage of image with empty source attribute",
27 | category: "eco-design",
28 | recommended: "warn",
29 | },
30 | messages: {
31 | SpecifySrcAttribute:
32 | "Make sure to specify src attribute when using
![]()
.",
33 | },
34 | schema: [],
35 | },
36 | create(context) {
37 | return {
38 | JSXOpeningElement(node) {
39 | if (node.name.name === "img") {
40 | const srcValue = node.attributes.find(
41 | (attr) => attr.name.name === "src",
42 | );
43 | if (srcValue?.value?.value === "") {
44 | //to prevent
![Empty image]()
45 | context.report({
46 | node: srcValue,
47 | messageId: "SpecifySrcAttribute",
48 | });
49 | } else if (!srcValue) {
50 | //to prevent
![]()
51 | context.report({
52 | node,
53 | messageId: "SpecifySrcAttribute",
54 | });
55 | }
56 | }
57 | },
58 | };
59 | },
60 | };
61 |
--------------------------------------------------------------------------------
/eslint-plugin/lib/rules/no-import-all-from-library.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | /** @type {import("eslint").Rule.RuleModule} */
22 | module.exports = {
23 | meta: {
24 | type: "suggestion",
25 | docs: {
26 | description: "Should not import all from library",
27 | category: "eco-design",
28 | recommended: "warn",
29 | },
30 | messages: {
31 | ShouldNotImportAllFromLibrary:
32 | "You should not import all from library {{library}}",
33 | },
34 | schema: [
35 | {
36 | type: "object",
37 | properties: {
38 | notAllowedLibraries: {
39 | type: "array",
40 | items: {
41 | type: "string",
42 | },
43 | },
44 | importByNamespaceNotAllowedLibraries: {
45 | type: "array",
46 | items: {
47 | type: "string",
48 | },
49 | },
50 | },
51 | additionalProperties: false,
52 | },
53 | ],
54 | },
55 | create: function (context) {
56 | const notAllowedLibraries = ["lodash", "underscore"];
57 | const importByNamespaceNotAllowedLibraries = ["lodash-es"];
58 |
59 | if (context.options?.length > 0) {
60 | const option = context.options[0];
61 |
62 | if (option.notAllowedLibraries) {
63 | notAllowedLibraries.push(...option.notAllowedLibraries);
64 | }
65 |
66 | if (option.importByNamespaceNotAllowedLibraries) {
67 | notAllowedLibraries.push(
68 | ...option.importByNamespaceNotAllowedLibraries,
69 | );
70 | }
71 | }
72 |
73 | return {
74 | ImportDeclaration(node) {
75 | const currentLibrary = node.source.value;
76 |
77 | const forbiddenByName = notAllowedLibraries.includes(currentLibrary);
78 | const forbiddenByNamespace =
79 | importByNamespaceNotAllowedLibraries.includes(currentLibrary) &&
80 | node.specifiers.some(
81 | (specifier) => specifier.type === "ImportNamespaceSpecifier",
82 | );
83 |
84 | if (forbiddenByName || forbiddenByNamespace) {
85 | context.report({
86 | node,
87 | messageId: "ShouldNotImportAllFromLibrary",
88 | data: { library: currentLibrary },
89 | });
90 | }
91 | },
92 | };
93 | },
94 | };
95 |
--------------------------------------------------------------------------------
/eslint-plugin/lib/rules/no-multiple-access-dom-element.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | /** @type {import("eslint").Rule.RuleModule} */
22 | module.exports = {
23 | meta: {
24 | type: "suggestion",
25 | docs: {
26 | description: "Disallow multiple access of same DOM element",
27 | category: "eco-design",
28 | recommended: "warn",
29 | },
30 | messages: {
31 | ShouldBeAssignToVariable:
32 | "'{{selector}}' selector is already used. Assign the result in a variable.",
33 | },
34 | schema: [],
35 | },
36 | create: function (context) {
37 | const map = {};
38 | const DOMAccessMethods = [
39 | "getElementById",
40 | "getElementsByTagName",
41 | "getElementsByClassName",
42 | "getElementsByName",
43 | "querySelector",
44 | "querySelectorAll",
45 | ];
46 |
47 | return {
48 | CallExpression(node) {
49 | if (
50 | node.callee.object?.name === "document" &&
51 | DOMAccessMethods.includes(node.callee.property.name) &&
52 | // We only accept string literals as arguments for now
53 | node.arguments[0].type === "Literal"
54 | ) {
55 | const selectorValue = node.arguments[0].value;
56 | const uniqueCallStr = node.callee.property.name + selectorValue;
57 | // todo: legacy support of context#getScope for eslint v7
58 | const scope =
59 | context.sourceCode?.getScope(node) ?? context.getScope();
60 |
61 | if (map[uniqueCallStr] === scope) {
62 | context.report({
63 | node,
64 | messageId: "ShouldBeAssignToVariable",
65 | data: { selector: selectorValue },
66 | });
67 | } else {
68 | map[uniqueCallStr] = scope;
69 | }
70 | }
71 | },
72 | };
73 | },
74 | };
75 |
--------------------------------------------------------------------------------
/eslint-plugin/lib/rules/no-multiple-style-changes.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | /** @type {import("eslint").Rule.RuleModule} */
22 | module.exports = {
23 | meta: {
24 | type: "suggestion",
25 | docs: {
26 | description: "Disallow multiple style changes at once",
27 | category: "eco-design",
28 | recommended: "warn",
29 | },
30 | messages: {
31 | UseClassInstead:
32 | "There are more than two style assignments for '{{elementName}}'. Use a class instead.",
33 | },
34 | schema: [],
35 | },
36 | create: function (context) {
37 | const isNodeUseStyleProperty = (node) =>
38 | node?.object?.property?.name === "style";
39 |
40 | const getNodeFullName = (node) => {
41 | let names = [];
42 | do {
43 | names.unshift(node.name ?? node.property?.name);
44 | node = node.object;
45 | } while (node);
46 | return names.join(".");
47 | };
48 |
49 | return {
50 | AssignmentExpression(node) {
51 | // Check if there is a literal assignation on a style property
52 | if (
53 | node.right.type === "Literal" &&
54 | isNodeUseStyleProperty(node.left)
55 | ) {
56 | const domElementName = getNodeFullName(node.left.object.object);
57 | const currentRangestart = node.left.object.object.range[0];
58 |
59 | /**
60 | * Store parent AST to check if there is more
61 | * than one assignation on the style of the same domElement
62 | */
63 | // todo: legacy support of context#getScope for eslint v7
64 | const scope =
65 | context.sourceCode?.getScope(node) ?? context.getScope();
66 | const currentScopeASTBody =
67 | scope.block.body.length != null
68 | ? scope.block.body
69 | : scope.block.body.body;
70 |
71 | const filtered = currentScopeASTBody.filter(
72 | (e) =>
73 | e.type === "ExpressionStatement" &&
74 | e.expression.type === "AssignmentExpression" &&
75 | isNodeUseStyleProperty(e.expression.left) &&
76 | getNodeFullName(e.expression.left.object.object) ===
77 | domElementName,
78 | );
79 |
80 | // De-duplication, prevents multiple alerts for each line involved
81 | const isCurrentNodeTheFirstAssignation =
82 | filtered.length > 1 &&
83 | currentRangestart <=
84 | filtered[0].expression.left.object.object.range[0];
85 |
86 | if (isCurrentNodeTheFirstAssignation) {
87 | context.report({
88 | node,
89 | messageId: "UseClassInstead",
90 | data: { elementName: domElementName },
91 | });
92 | }
93 | }
94 | },
95 | };
96 | },
97 | };
98 |
--------------------------------------------------------------------------------
/eslint-plugin/lib/rules/no-torch.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | /** @type {import("eslint").Rule.RuleModule} */
22 | module.exports = {
23 | meta: {
24 | type: "suggestion",
25 | docs: {
26 | description: "Should not programmatically enable torch mode",
27 | category: "eco-design",
28 | recommended: "warn",
29 | },
30 | messages: {
31 | ShouldNotProgrammaticallyEnablingTorchMode:
32 | "You should not programmatically enable torch mode",
33 | },
34 | schema: [],
35 | },
36 | create: function (context) {
37 | const reactNativeTorchLibrary = "react-native-torch";
38 |
39 | return {
40 | ImportDeclaration(node) {
41 | const currentLibrary = node.source.value;
42 | if (currentLibrary === reactNativeTorchLibrary) {
43 | context.report({
44 | node,
45 | messageId: "ShouldNotProgrammaticallyEnablingTorchMode",
46 | });
47 | }
48 | },
49 | };
50 | },
51 | };
52 |
--------------------------------------------------------------------------------
/eslint-plugin/lib/rules/prefer-collections-with-pagination.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | const PAGINATION_KEY_WORDS = ["page", "pagination", "paginated"];
22 |
23 | const isPaginationName = (name) => {
24 | return PAGINATION_KEY_WORDS.some((keyWord) =>
25 | name.toLowerCase().includes(keyWord),
26 | );
27 | };
28 |
29 | const isPaginated = (objectType) => {
30 | if (objectType.type === "TSTypeReference") {
31 | // Pagination object should be an object, for example, it can't be an array
32 |
33 | if (isPaginationName(objectType.typeName.name)) {
34 | return true;
35 | }
36 | } else if (objectType.type === "TSTypeLiteral") {
37 | if (
38 | objectType.members?.some(
39 | (member) => member.key != null && isPaginationName(member.key.name),
40 | )
41 | ) {
42 | return true;
43 | }
44 | }
45 |
46 | return false;
47 | };
48 |
49 | const isNestGetDecorator = (decorator) =>
50 | decorator.expression.callee.name.toLowerCase() === "get" &&
51 | (decorator.expression.arguments.length === 0 ||
52 | !decorator.expression.arguments[0].value.includes(":"));
53 |
54 | const isInNestControllerClass = (decorator) =>
55 | decorator.parent.parent.parent.type === "ClassDeclaration" &&
56 | decorator.parent.parent.parent.decorators.find(
57 | (decorator) =>
58 | decorator.expression.callee.name.toLowerCase() === "controller",
59 | );
60 |
61 | const report = (context, node) =>
62 | context.report({ node, messageId: "PreferReturnCollectionsWithPagination" });
63 |
64 | // Type: RuleModule<"uppercase", ...>
65 | module.exports = {
66 | name: "prefer-collections-with-pagination",
67 | meta: {
68 | docs: {
69 | description: "Prefer API collections with pagination",
70 | category: "eco-design",
71 | recommended: "warn",
72 | },
73 | messages: {
74 | PreferReturnCollectionsWithPagination:
75 | "Prefer return collections with pagination in HTTP GET",
76 | },
77 | type: "suggestion",
78 | schema: [],
79 | },
80 | defaultOptions: [],
81 | create(context) {
82 | return {
83 | Decorator(node) {
84 | if (isNestGetDecorator(node) && isInNestControllerClass(node)) {
85 | const getMethod = node.parent;
86 | const returnType = getMethod.value.returnType?.typeAnnotation;
87 |
88 | if (returnType != null) {
89 | if (
90 | returnType.type === "TSTypeReference" &&
91 | returnType.typeName.name === "Promise"
92 | ) {
93 | // todo: legacy support of typeParameters for eslint v7
94 | const params = (
95 | returnType.typeArguments ?? returnType.typeParameters
96 | ).params;
97 |
98 | if (params.length === 1 && !isPaginated(params[0])) {
99 | report(context, returnType);
100 | }
101 | } else if (
102 | returnType.type === "TSArrayType" ||
103 | !isPaginated(returnType)
104 | ) {
105 | report(context, returnType);
106 | }
107 | }
108 | }
109 | },
110 | };
111 | },
112 | };
113 |
--------------------------------------------------------------------------------
/eslint-plugin/lib/rules/prefer-lighter-formats-for-image-files.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | /** @type {import('eslint').Rule.RuleModule} */
22 | module.exports = {
23 | meta: {
24 | type: "suggestion",
25 | docs: {
26 | description: "Prefer lighter formats for image files",
27 | category: "eco-design",
28 | recommended: "warn",
29 | },
30 | messages: {
31 | PreferLighterFormatsForImageFiles:
32 | "You should use lighter formats for image files such as {{ eligibleExtensions }}",
33 | },
34 | schema: [],
35 | },
36 | create(context) {
37 | const eligibleExtensions = ["webp", "avif", "svg", "jxl"];
38 |
39 | return {
40 | JSXOpeningElement(node) {
41 | const tagName = node.name.name;
42 | if (tagName?.toLowerCase() !== "img") return;
43 |
44 | const parentTagName = node.parent?.parent?.openingElement?.name?.name;
45 | if (parentTagName?.toLowerCase() === "picture") return;
46 |
47 | const srcAttribut = node.attributes.find(
48 | (attr) => attr.name.name === "src",
49 | );
50 |
51 | let srcValue = srcAttribut?.value?.value;
52 |
53 | if (!srcValue) return;
54 |
55 | srcValue = srcValue.substring(srcValue.lastIndexOf("/") + 1);
56 | const dotIndex = srcValue.lastIndexOf(".");
57 |
58 | if (dotIndex === -1) return;
59 |
60 | const imgExtension = srcValue.substring(dotIndex + 1);
61 |
62 | if (eligibleExtensions.includes(imgExtension.toLowerCase())) return;
63 |
64 | context.report({
65 | node,
66 | messageId: "PreferLighterFormatsForImageFiles",
67 | data: { eligibleExtensions: eligibleExtensions.join(", ") },
68 | });
69 | },
70 | };
71 | },
72 | };
73 |
--------------------------------------------------------------------------------
/eslint-plugin/lib/rules/prefer-shorthand-css-notations.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | /** @type {import('eslint').Rule.RuleModule} */
22 | module.exports = {
23 | meta: {
24 | type: "suggestion",
25 | docs: {
26 | description: "Encourage usage of shorthand CSS notations",
27 | category: "eco-design",
28 | recommended: "warn",
29 | },
30 | messages: {
31 | PreferShorthandCSSNotation:
32 | "Prefer the shorthand CSS notation {{property}}",
33 | },
34 | schema: [
35 | {
36 | type: "object",
37 | properties: {
38 | disableProperties: {
39 | type: "array",
40 | items: {
41 | type: "string",
42 | },
43 | },
44 | },
45 | additionalProperties: false,
46 | },
47 | ],
48 | },
49 | create: function (context) {
50 | const shorthandProperties = {
51 | animation: ["animationName", "animationDuration"],
52 | background: [
53 | "backgroundColor",
54 | "backgroundImage",
55 | "backgroundPosition",
56 | "backgroundRepeat",
57 | ],
58 | border: ["borderColor", "borderStyle", "borderWidth"],
59 | column: ["columnCount", "columnWidth"],
60 | columnRule: ["columnRuleColor", "columnRuleStyle", "columnRuleWidth"],
61 | flex: ["flexBasis", "flexGrow", "flexShrink"],
62 | font: ["fontFamily", "fontSize", "fontStyle"],
63 | grid: ["gridAutoColumns", "gridAutoFlow", "gridAutoRows"],
64 | gridTemplate: ["gridTemplateColumns", "gridTemplateRows"],
65 | listStyle: ["listStyleImage", "listStylePosition", "listStyleType"],
66 | margin: ["marginTop", "marginRight", "marginBottom", "marginLeft"],
67 | offset: ["offsetPath", "offsetPosition"],
68 | outline: ["outlineStyle", "outlineWidth", "outlineColor"],
69 | overflow: ["overflowX", "overflowY"],
70 | padding: ["paddingTop", "paddingRight", "paddingBottom", "paddingLeft"],
71 | placeContent: ["alignContent", "justifyContent"],
72 | placeItems: ["alignItems", "justifyItems"],
73 | placeSelf: ["alignSelf", "justifySelf"],
74 | textDecoration: [
75 | "textDecorationColor",
76 | "textDecorationLine",
77 | "textDecorationStyle",
78 | ],
79 | transition: ["transitionProperty", "transitionDuration"],
80 | };
81 |
82 | const disabledProperties = context.options?.[0]?.disableProperties ?? [];
83 |
84 | return {
85 | JSXOpeningElement(node) {
86 | const styleAttribute = node.attributes.find(
87 | (attr) => attr.name?.name === "style",
88 | );
89 | if (styleAttribute?.value.expression?.properties) {
90 | const nodePropertyNames =
91 | styleAttribute.value.expression.properties.map(
92 | (property) => property.key.name,
93 | );
94 |
95 | for (const [shorthandProp, matchProperties] of Object.entries(
96 | shorthandProperties,
97 | )) {
98 | if (
99 | !disabledProperties.includes(shorthandProp) &&
100 | matchProperties.every((prop) => nodePropertyNames.includes(prop))
101 | ) {
102 | return context.report({
103 | node: styleAttribute,
104 | messageId: "PreferShorthandCSSNotation",
105 | data: { property: shorthandProp },
106 | });
107 | }
108 | }
109 | }
110 | },
111 | };
112 | },
113 | };
114 |
--------------------------------------------------------------------------------
/eslint-plugin/lib/rules/provide-print-css.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | /** @type {import("eslint").Rule.RuleModule} */
22 | module.exports = {
23 | meta: {
24 | type: "suggestion",
25 | docs: {
26 | description: "Enforce providing a print stylesheet",
27 | category: "eco-design",
28 | recommended: "warn",
29 | },
30 | messages: {
31 | noPrintCSSProvided: "Provide a print CSS",
32 | },
33 | schema: [],
34 | },
35 | create(context) {
36 | const isStyleWithPrintNode = (node) => {
37 | return (
38 | node.openingElement.name.name === "style" &&
39 | node.children.some((child) => {
40 | let element = null;
41 | if (child.value != null) {
42 | element = child.value;
43 | } else if (child.expression != null) {
44 | if (child.expression.value != null) {
45 | element = child.expression.value;
46 | } else if (child.expression.quasis?.length > 0) {
47 | element = child.expression.quasis[0].value.cooked;
48 | }
49 | }
50 | return element?.includes("@media print");
51 | })
52 | );
53 | };
54 |
55 | const isLinkForPrintNode = (node) =>
56 | node.openingElement.name.name === "link" &&
57 | node.openingElement.attributes.some(
58 | (attr) => attr.name.name === "media" && attr.value.value === "print",
59 | );
60 |
61 | return {
62 | JSXElement(node) {
63 | if (node.openingElement.name.name === "head") {
64 | const hasValidElement = node.children.some(
65 | (child) =>
66 | child.openingElement != null &&
67 | (isStyleWithPrintNode(child) || isLinkForPrintNode(child)),
68 | );
69 |
70 | if (!hasValidElement) {
71 | context.report({ node, messageId: "noPrintCSSProvided" });
72 | }
73 | }
74 | },
75 | };
76 | },
77 | };
78 |
--------------------------------------------------------------------------------
/eslint-plugin/lib/standalone.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | /**
20 | * @fileoverview JavaScript linter of Creedengo project (standalone mode)
21 | * @author Green Code Initiative
22 | */
23 | "use strict";
24 |
25 | const rules = require("./rule-list");
26 |
27 | const allRules = {};
28 | const recommendedRules = {};
29 |
30 | for (let { ruleName, ruleModule } of rules) {
31 | allRules[ruleName] = ruleModule;
32 | const { recommended } = ruleModule.meta.docs;
33 | const ruleConfiguration = recommended === false ? "off" : recommended;
34 | recommendedRules[`@creedengo/${ruleName}`] = ruleConfiguration;
35 | }
36 |
37 | const plugin = {
38 | meta: {
39 | name: "@creedengo/eslint-plugin",
40 | version: "2.1.0", // dynamically updated by the release workflow
41 | },
42 | rules: allRules,
43 | };
44 |
45 | plugin.configs = {
46 | recommended: {
47 | plugins: ["@creedengo"],
48 | rules: recommendedRules,
49 | },
50 | ["flat/recommended"]: {
51 | plugins: { "@creedengo": plugin },
52 | rules: recommendedRules,
53 | },
54 | };
55 |
56 | module.exports = plugin;
57 |
--------------------------------------------------------------------------------
/eslint-plugin/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@creedengo/eslint-plugin",
3 | "version": "2.1.0",
4 | "description": "JavaScript linter of creedengo project",
5 | "keywords": [
6 | "eslint",
7 | "eslintplugin",
8 | "eslint-plugin",
9 | "creedengo",
10 | "greenit"
11 | ],
12 | "repository": {
13 | "type": "git",
14 | "url": "git+https://github.com/green-code-initiative/creedengo-javascript.git",
15 | "directory": "eslint-plugin"
16 | },
17 | "license": "GPL-3.0",
18 | "author": "Green Code Initiative",
19 | "main": "./lib/standalone.js",
20 | "files": [
21 | "lib",
22 | "./dist/rules.js"
23 | ],
24 | "scripts": {
25 | "clean": "rimraf dist/pack",
26 | "lint": "yarn lint:eslint-docs && yarn lint:js",
27 | "lint:eslint-docs": "eslint-doc-generator --check",
28 | "lint:js": "eslint .",
29 | "lint:fix": "eslint . --fix",
30 | "pack:sonar": "npm pkg set main=\"./dist/rules.js\" && mkdirp dist/pack && yarn pack -o dist/pack/creedengo-eslint-plugin.tgz && npm pkg set main=\"./lib/standalone.js\"",
31 | "test": "mocha tests --recursive",
32 | "test:cov": "nyc --reporter=lcov --reporter=text mocha tests --recursive",
33 | "update:eslint-docs": "eslint-doc-generator"
34 | },
35 | "devDependencies": {
36 | "@typescript-eslint/eslint-plugin": "^6.4.1",
37 | "@typescript-eslint/parser": "^6.4.1",
38 | "eslint": "^8.57.1",
39 | "eslint-config-prettier": "^9.1.0",
40 | "eslint-doc-generator": "1.7.0",
41 | "eslint-plugin-eslint-plugin": "^6.4.0",
42 | "eslint-plugin-license-header": "^0.6.1",
43 | "eslint-plugin-node": "^11.1.0",
44 | "eslint-plugin-prettier": "^5.2.3",
45 | "mkdirp": "^3.0.1",
46 | "mocha": "^11.0.1",
47 | "nyc": "^17.1.0",
48 | "prettier": "^3.4.2",
49 | "rimraf": "^5.0.5",
50 | "typescript": "~5.3.3"
51 | },
52 | "engines": {
53 | "node": "^14.17.0 || ^16.0.0 || >= 18.0.0"
54 | },
55 | "peerDependencies": {
56 | "eslint": ">= 7 < 10"
57 | },
58 | "packageManager": "yarn@4.9.1"
59 | }
60 |
--------------------------------------------------------------------------------
/eslint-plugin/tests/dist/rules.test.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | const assert = require("assert");
20 |
21 | describe("rules.js", () => {
22 | it("should export all rules with a specific rule id pattern", () => {
23 | const { rules } = require("../../dist/rules");
24 | assert.notEqual(rules.length, 0);
25 | assert.match(rules[0].ruleId, /@creedengo\/.*/);
26 | assert.equal(rules[0].ruleConfig.length, 0);
27 | });
28 | });
29 |
--------------------------------------------------------------------------------
/eslint-plugin/tests/lib/files/logo.svg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/green-code-initiative/creedengo-javascript/e4ce6f18aab39048849ca53464b9dab17c7575e2/eslint-plugin/tests/lib/files/logo.svg
--------------------------------------------------------------------------------
/eslint-plugin/tests/lib/rule-list.test.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | const assert = require("assert");
20 |
21 | describe("rule-list.js", () => {
22 | it("should export list of valid rule modules", () => {
23 | const rules = require("../../lib/rule-list");
24 | assert.notEqual(rules.length, 0);
25 | const firstRule = rules[0];
26 | assert.notEqual(firstRule.ruleName, null);
27 | assert.notEqual(firstRule.ruleModule, null);
28 | });
29 | });
30 |
--------------------------------------------------------------------------------
/eslint-plugin/tests/lib/rules/avoid-autoplay.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | //------------------------------------------------------------------------------
22 | // Requirements
23 | //------------------------------------------------------------------------------
24 |
25 | const rule = require("../../../lib/rules/avoid-autoplay");
26 | const RuleTester = require("eslint").RuleTester;
27 |
28 | //------------------------------------------------------------------------------
29 | // Tests
30 | //------------------------------------------------------------------------------
31 |
32 | const ruleTester = new RuleTester({
33 | parserOptions: {
34 | ecmaVersion: 2021,
35 | sourceType: "module",
36 | ecmaFeatures: {
37 | jsx: true,
38 | },
39 | },
40 | });
41 |
42 | const noAutoplayError = {
43 | messageId: "NoAutoplay",
44 | type: "JSXAttribute",
45 | };
46 | const enforcePreloadNoneError = {
47 | messageId: "EnforcePreloadNone",
48 | type: "JSXAttribute",
49 | };
50 | const BothError = {
51 | messageId: "NoAutoplayAndEnforcePreloadNone",
52 | type: "JSXAttribute",
53 | };
54 |
55 | ruleTester.run("autoplay-audio-video-attribute-not-present", rule, {
56 | valid: [
57 | '
',
58 | '
',
59 | '
',
60 | ],
61 | invalid: [
62 | {
63 | code: "
",
64 | errors: [BothError],
65 | },
66 | {
67 | code: "
",
68 | errors: [BothError],
69 | },
70 | {
71 | code: "
",
72 | errors: [BothError],
73 | },
74 | {
75 | code: '
',
76 | errors: [BothError],
77 | },
78 | {
79 | code: '
',
80 | errors: [noAutoplayError],
81 | },
82 | {
83 | code: '
',
84 | errors: [enforcePreloadNoneError],
85 | },
86 | ],
87 | });
88 |
--------------------------------------------------------------------------------
/eslint-plugin/tests/lib/rules/avoid-brightness-override.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | //------------------------------------------------------------------------------
22 | // Requirements
23 | //------------------------------------------------------------------------------
24 |
25 | const rule = require("../../../lib/rules/avoid-brightness-override");
26 | const RuleTester = require("eslint").RuleTester;
27 |
28 | //------------------------------------------------------------------------------
29 | // Tests
30 | //------------------------------------------------------------------------------
31 |
32 | const ruleTester = new RuleTester({
33 | parserOptions: {
34 | ecmaVersion: 2021,
35 | sourceType: "module",
36 | ecmaFeatures: {
37 | jsx: true,
38 | },
39 | },
40 | });
41 | const expectedError = {
42 | messageId: "ShouldAvoidOverrideBrightness",
43 | type: "MemberExpression",
44 | };
45 |
46 | ruleTester.run("avoid-brightness-override", rule, {
47 | valid: [
48 | `
49 | import * as lodash from 'lodash';
50 | lodash.isEmpty('');
51 | `,
52 | `
53 | import { ScreenBrightness } from '@capacitor-community/screen-brightness';
54 |
55 | // Get the current brightness:
56 | const {brightness: currentBrightness} = ScreenBrightness.getBrightness();
57 | `,
58 | `
59 | import DeviceBrightness from 'react-native-device-brightness';
60 |
61 | DeviceBrightness.getBrightnessLevel()
62 | .then(function (luminous) {
63 | // Get current brightness level
64 | // 0 ~ 1
65 | console.log(luminous);
66 | });
67 | `,
68 | `
69 | import * as Brightness from 'expo-brightness';
70 |
71 | Brightness.requestPermissionsAsync();
72 | `,
73 | `
74 | import ScreenBrightness from 'react-native-screen-brightness';
75 |
76 | ScreenBrightness.getBrightness().then(brightness => {
77 | console.log('brightness', brightness);
78 | });
79 | `,
80 | ],
81 |
82 | invalid: [
83 | {
84 | code: `
85 | import { ScreenBrightness } from '@capacitor-community/screen-brightness';
86 |
87 | // Set the brightness:
88 | const brightness = 0.5;
89 | ScreenBrightness.setBrightness({ brightness });
90 | `,
91 | errors: [expectedError],
92 | },
93 | {
94 | code: `
95 | import DeviceBrightness from 'react-native-device-brightness';
96 |
97 | DeviceBrightness.setBrightnessLevel(0.5);
98 | `,
99 | errors: [expectedError],
100 | },
101 | {
102 | code: `
103 | import ScreenBrightness from 'react-native-screen-brightness';
104 |
105 | ScreenBrightness.setBrightness(0.5);
106 | `,
107 | errors: [expectedError],
108 | },
109 | {
110 | code: `
111 | import React, { useEffect } from 'react';
112 | import { StyleSheet, View, Text } from 'react-native';
113 | import * as Brightness from 'expo-brightness';
114 |
115 | export default function App() {
116 | useEffect(() => {
117 | (async () => {
118 | const { status } = await Brightness.requestPermissionsAsync();
119 | if (status === 'granted') {
120 | Brightness.setSystemBrightnessAsync(1);
121 | }
122 | })();
123 | }, []);
124 |
125 | return (
126 |
127 | Brightness Module Example
128 |
129 | );
130 | }
131 | `,
132 | errors: [expectedError],
133 | },
134 | ],
135 | });
136 |
--------------------------------------------------------------------------------
/eslint-plugin/tests/lib/rules/avoid-css-animations.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | //------------------------------------------------------------------------------
22 | // Requirements
23 | //------------------------------------------------------------------------------
24 |
25 | const rule = require("../../../lib/rules/avoid-css-animations");
26 | const RuleTester = require("eslint").RuleTester;
27 |
28 | //------------------------------------------------------------------------------
29 | // Tests
30 | //------------------------------------------------------------------------------
31 |
32 | const ruleTester = new RuleTester({
33 | parserOptions: {
34 | ecmaVersion: 2021,
35 | sourceType: "module",
36 | ecmaFeatures: {
37 | jsx: true,
38 | },
39 | },
40 | });
41 |
42 | ruleTester.run("avoid-css-animations", rule, {
43 | valid: [
44 | `
45 | import React from 'react';
46 | import './styles.css'; // External CSS file
47 |
48 | const MyComponent = () => {
49 | return
This content is styled using an external CSS file.
;
50 | };
51 |
52 | export default MyComponent;
53 | `,
54 | `
Hello world
`,
55 | `
My red element
`,
56 | // spread attributes should not throw an error (#49)
57 | "
",
58 | ],
59 |
60 | invalid: [
61 | {
62 | code: "
",
63 | errors: [
64 | {
65 | messageId: "AvoidCSSAnimations",
66 | data: {
67 | attribute: "transition",
68 | },
69 | type: "Property",
70 | },
71 | ],
72 | },
73 | {
74 | code: "
",
75 | errors: [
76 | {
77 | messageId: "AvoidCSSAnimations",
78 | data: {
79 | attribute: "animationName",
80 | },
81 | type: "Property",
82 | },
83 | ],
84 | },
85 | ],
86 | });
87 |
--------------------------------------------------------------------------------
/eslint-plugin/tests/lib/rules/avoid-high-accuracy-geolocation.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | //------------------------------------------------------------------------------
22 | // Requirements
23 | //------------------------------------------------------------------------------
24 |
25 | const rule = require("../../../lib/rules/avoid-high-accuracy-geolocation");
26 | const RuleTester = require("eslint").RuleTester;
27 |
28 | //------------------------------------------------------------------------------
29 | // Tests
30 | //------------------------------------------------------------------------------
31 |
32 | const ruleTester = new RuleTester({
33 | parserOptions: {
34 | ecmaVersion: 6,
35 | sourceType: "module",
36 | },
37 | });
38 | const expectedErrorOnProperty = {
39 | messageId: "AvoidUsingAccurateGeolocation",
40 | type: "Property",
41 | };
42 | const expectedErrorOnMemberExpression = {
43 | messageId: "AvoidUsingAccurateGeolocation",
44 | type: "MemberExpression",
45 | };
46 |
47 | ruleTester.run("avoid-high-accuracy-geolocation", rule, {
48 | valid: [
49 | `
50 | var opts = {enableHighAccuracy: false, timeout: 5000, maximumAge: 0};
51 |
52 | function success(pos) {
53 | console.log(pos.coords);
54 | }
55 |
56 | function error(err) {
57 | console.warn(err);
58 | }
59 |
60 | navigator.geolocation.getCurrentPosition(success, error, opts);
61 | `,
62 | `
63 | function success(pos) {
64 | console.log(pos.coords);
65 | }
66 |
67 | navigator.geolocation.getCurrentPosition(success);
68 | `,
69 | `
70 | navigator.geolocation.getCurrentPosition(success, error, {enableHighAccuracy: false});
71 | `,
72 |
73 | `
74 | import axios from 'axios';
75 | `,
76 | `
77 | import * as Location from 'expo-location';
78 |
79 | Location.requestPermissionsAsync();
80 | `,
81 | ],
82 |
83 | invalid: [
84 | {
85 | code: `
86 | var options = {enableHighAccuracy: true, timeout: 5000, maximumAge: 0};
87 |
88 | function success(pos) {
89 | console.log(pos.coords);
90 | }
91 |
92 | function error(err) {
93 | console.warn(err);
94 | }
95 |
96 | navigator.geolocation.getCurrentPosition(success, error, options);
97 | `,
98 | errors: [expectedErrorOnProperty],
99 | },
100 | {
101 | code: `
102 | navigator.geolocation.getCurrentPosition(success, error, {enableHighAccuracy: true});
103 | `,
104 | errors: [expectedErrorOnProperty],
105 | },
106 | {
107 | code: `
108 | import * as Location from 'expo-location';
109 |
110 | Location.enableNetworkProviderAsync();
111 | `,
112 | errors: [expectedErrorOnMemberExpression],
113 | },
114 | ],
115 | });
116 |
--------------------------------------------------------------------------------
/eslint-plugin/tests/lib/rules/avoid-keep-awake.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | //------------------------------------------------------------------------------
22 | // Requirements
23 | //------------------------------------------------------------------------------
24 |
25 | const rule = require("../../../lib/rules/avoid-keep-awake");
26 | const RuleTester = require("eslint").RuleTester;
27 |
28 | //------------------------------------------------------------------------------
29 | // Tests
30 | //------------------------------------------------------------------------------
31 |
32 | const ruleTester = new RuleTester({
33 | parserOptions: {
34 | ecmaVersion: 2022,
35 | sourceType: "module",
36 | ecmaFeatures: {
37 | jsx: true,
38 | },
39 | },
40 | });
41 |
42 | const expectedErrorHook = {
43 | messageId: "AvoidKeepAwake",
44 | type: "CallExpression",
45 | };
46 |
47 | const expectedErrorFunction = {
48 | messageId: "AvoidKeepAwake",
49 | type: "CallExpression",
50 | };
51 |
52 | ruleTester.run("avoid-keep-awake", rule, {
53 | valid: [
54 | {
55 | code: `
56 | import React from 'react';
57 | import { Text, View } from 'react-native';
58 |
59 | export default function ValidExample() {
60 | return (
61 |
62 | This screen will sleep!
63 |
64 | );
65 | }
66 | `,
67 | },
68 | {
69 | code: `
70 | import React from 'react';
71 | import { useKeepAwake } from 'other-library';
72 | import { Button, View } from 'react-native';
73 |
74 | export default class ValidExample extends React.Component {
75 | render() {
76 | useKeepAwake();
77 | return (
78 |
79 |
80 | );
81 | }
82 | }
83 | `,
84 | },
85 | ],
86 | invalid: [
87 | {
88 | code: `
89 | import { useKeepAwake } from 'expo-keep-awake';
90 | import React from 'react';
91 | import { Text, View } from 'react-native';
92 |
93 | export default function KeepAwakeExample() {
94 | useKeepAwake();
95 | return (
96 |
97 | This screen will never sleep!
98 |
99 | );
100 | }
101 | `,
102 | errors: [expectedErrorHook],
103 | },
104 | {
105 | code: `
106 | import { activateKeepAwake } from 'expo-keep-awake';
107 | import React from 'react';
108 | import { Button, View } from 'react-native';
109 |
110 | export default class KeepAwakeExample extends React.Component {
111 | render() {
112 | return (
113 |
114 |
115 |
116 | );
117 | }
118 |
119 | _activate = () => {
120 | activateKeepAwake();
121 | alert('Activated!');
122 | };
123 | }`,
124 | errors: [expectedErrorFunction],
125 | },
126 | ],
127 | });
128 |
--------------------------------------------------------------------------------
/eslint-plugin/tests/lib/rules/limit-db-query-results.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 | //------------------------------------------------------------------------------
21 | // Requirements
22 | //------------------------------------------------------------------------------
23 |
24 | const rule = require("../../../lib/rules/limit-db-query-results"),
25 | RuleTester = require("eslint").RuleTester;
26 |
27 | //------------------------------------------------------------------------------
28 | // Tests
29 | //------------------------------------------------------------------------------
30 |
31 | const ruleTester = new RuleTester({
32 | parserOptions: {
33 | ecmaVersion: 6,
34 | sourceType: "module",
35 | },
36 | });
37 |
38 | const expectedError = {
39 | messageId: "LimitTheNumberOfReturns",
40 | type: "Literal",
41 | };
42 |
43 | ruleTester.run("limit-db-query-results", rule, {
44 | valid: [
45 | `
46 | sqlClient.query("SELECT id, name, email FROM customers LIMIT 10;");
47 | `,
48 | `
49 | sqlClient.query("SELECT TOP 5 * FROM products;");
50 | `,
51 | `
52 | sqlClient.query("SELECT id, name, email FROM customers WHERE id = 1");
53 | `,
54 | `
55 | sqlClient.query("SELECT * FROM orders FETCH FIRST 20 ROWS ONLY");
56 | `,
57 | `
58 | sqlClient.query("WITH numbered_customers AS (SELECT *, ROW_NUMBER() OVER (ORDER BY customer_id) AS row_num FROM customers) SELECT * FROM numbered_customers WHERE row_num <= 50");
59 | `,
60 | `
61 | console.log("SELECT id, name, email FROM customers WHERE id = 1");
62 | `,
63 | ],
64 |
65 | invalid: [
66 | {
67 | code: `sqlClient.query("SELECT * FROM bikes");`,
68 | errors: [expectedError],
69 | },
70 | {
71 | code: `sqlClient.run("SELECT id, departure, arrival FROM flights");`,
72 | errors: [expectedError],
73 | },
74 | {
75 | code: `sqlClient.execute("SELECT * FROM cars");`,
76 | errors: [expectedError],
77 | },
78 | ],
79 | });
80 |
--------------------------------------------------------------------------------
/eslint-plugin/tests/lib/rules/no-empty-image-src-attribute.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | //------------------------------------------------------------------------------
22 | // Requirements
23 | //------------------------------------------------------------------------------
24 |
25 | const rule = require("../../../lib/rules/no-empty-image-src-attribute");
26 | const RuleTester = require("eslint").RuleTester;
27 |
28 | //------------------------------------------------------------------------------
29 | // Tests
30 | //------------------------------------------------------------------------------
31 |
32 | const ruleTester = new RuleTester({
33 | parserOptions: {
34 | ecmaVersion: 2021,
35 | sourceType: "module",
36 | ecmaFeatures: {
37 | jsx: true,
38 | },
39 | },
40 | });
41 | const expectedError1 = {
42 | messageId: "SpecifySrcAttribute",
43 | type: "JSXAttribute",
44 | };
45 | const expectedError2 = {
46 | messageId: "SpecifySrcAttribute",
47 | type: "JSXOpeningElement",
48 | };
49 |
50 | ruleTester.run("image-src-attribute-not-empty", rule, {
51 | valid: [
52 | `
53 |

54 | `,
55 | `
56 | import logoSvg from "../files/logo.svg";
57 |

58 | `,
59 | ],
60 |
61 | invalid: [
62 | {
63 | code: `
64 |
![]()
65 | `,
66 | errors: [expectedError1],
67 | },
68 | {
69 | code: `
70 |
![This is an empty image]()
71 | `,
72 | errors: [expectedError2],
73 | },
74 | ],
75 | });
76 |
--------------------------------------------------------------------------------
/eslint-plugin/tests/lib/rules/no-import-all-from-library.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | //------------------------------------------------------------------------------
22 | // Requirements
23 | //------------------------------------------------------------------------------
24 |
25 | const rule = require("../../../lib/rules/no-import-all-from-library");
26 | const RuleTester = require("eslint").RuleTester;
27 |
28 | //------------------------------------------------------------------------------
29 | // Tests
30 | //------------------------------------------------------------------------------
31 |
32 | const ruleTester = new RuleTester({
33 | parserOptions: {
34 | ecmaVersion: 6,
35 | sourceType: "module",
36 | },
37 | });
38 | const expectedError = {
39 | messageId: "ShouldNotImportAllFromLibrary",
40 | type: "ImportDeclaration",
41 | };
42 |
43 | ruleTester.run("no-import-all-from-library", rule, {
44 | valid: [
45 | `
46 | import isEmpty from 'lodash/isEmpty';
47 | `,
48 | `
49 | import orderBy from 'lodash/orderBy';
50 | `,
51 | `
52 | import { orderBy } from 'lodash-es';
53 | `,
54 | `
55 | import map from 'underscore/modules/map.js';
56 | `,
57 | ],
58 |
59 | invalid: [
60 | {
61 | code: "import lodash from 'lodash';",
62 | errors: [expectedError],
63 | },
64 | {
65 | code: "import * as lodash from 'lodash';",
66 | errors: [expectedError],
67 | },
68 | {
69 | code: "import * as lodash from 'lodash-es';",
70 | errors: [expectedError],
71 | },
72 | {
73 | code: "import someLib from 'some-lib';",
74 | options: [{ notAllowedLibraries: ["some-lib"] }],
75 | errors: [expectedError],
76 | },
77 | {
78 | code: "import * as someLib from 'some-lib';",
79 | options: [{ importByNamespaceNotAllowedLibraries: ["some-lib"] }],
80 | errors: [expectedError],
81 | },
82 | ],
83 | });
84 |
--------------------------------------------------------------------------------
/eslint-plugin/tests/lib/rules/no-multiple-access-dom-element.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | //------------------------------------------------------------------------------
22 | // Requirements
23 | //------------------------------------------------------------------------------
24 |
25 | const rule = require("../../../lib/rules/no-multiple-access-dom-element");
26 | const RuleTester = require("eslint").RuleTester;
27 |
28 | //------------------------------------------------------------------------------
29 | // Tests
30 | //------------------------------------------------------------------------------
31 |
32 | const ruleTester = new RuleTester();
33 | const expectedError = {
34 | messageId: "ShouldBeAssignToVariable",
35 | type: "CallExpression",
36 | };
37 |
38 | ruleTester.run("no-multiple-access-dom-element", rule, {
39 | valid: [
40 | `
41 | var el1 = document.getElementById('block1').test;
42 | var el2 = document.getElementById('block2').test
43 | `,
44 | `
45 | var el1 = document.getElementsByClassName('block1').test;
46 | var el2 = document.getElementsByClassName('block2').test
47 | `,
48 | `
49 | function test() { var link = document.getElementsByTagName('a'); }
50 | var link = document.getElementsByTagName('a');
51 | `,
52 | `
53 | for (var i = 0; i < 10; i++) {
54 | var test = document.getElementsByName("test" + i)[0].value;
55 | var test2 = document.getElementsByName("test2" + i)[0].value;
56 | }
57 | `,
58 | ],
59 |
60 | invalid: [
61 | {
62 | code: "var el1 = document.getElementById('block1').test1; var el2 = document.getElementById('block1').test2",
63 | errors: [expectedError],
64 | },
65 | {
66 | code: "function test() {var el1 = document.getElementById('block1').test1; if(toto) { var el2 = document.getElementById('block1').test2 }}",
67 | errors: [expectedError],
68 | },
69 | {
70 | code: "if (true) { var card = document.querySelector('.card'); } else { var card = document.querySelector('.card'); }",
71 | errors: [expectedError],
72 | },
73 | ],
74 | });
75 |
--------------------------------------------------------------------------------
/eslint-plugin/tests/lib/rules/no-multiple-style-changes.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | //------------------------------------------------------------------------------
22 | // Requirements
23 | //------------------------------------------------------------------------------
24 |
25 | const rule = require("../../../lib/rules/no-multiple-style-changes");
26 | const RuleTester = require("eslint").RuleTester;
27 |
28 | //------------------------------------------------------------------------------
29 | // Tests
30 | //------------------------------------------------------------------------------
31 |
32 | const ruleTester = new RuleTester({
33 | parserOptions: {
34 | ecmaVersion: 2021,
35 | sourceType: "module",
36 | },
37 | });
38 | const expectedError = {
39 | messageId: "UseClassInstead",
40 | type: "AssignmentExpression",
41 | };
42 |
43 | ruleTester.run("no-multiple-style-changes", rule, {
44 | valid: [
45 | {
46 | code: 'element.style.height = "800px";',
47 | },
48 | {
49 | code: `
50 | element.style.height = "800px";
51 | element2.style.width = "800px";
52 | `,
53 | },
54 | {
55 | code: `
56 | element.style.height = "800px";
57 | function a() { element.style.width = "800px"; }
58 | `,
59 | },
60 | {
61 | name: "should not report on different elements in same object",
62 | code: `
63 | var elements = { element1, element2 };
64 | elements.element1.style.height = "800px";
65 | elements.element2.style.height = "800px";
66 | `,
67 | },
68 | {
69 | code: `
70 | var offsetWidth = 5;
71 | var offsetLeft = 3;
72 | element.style.width = \`\${offsetWidth}px\`;
73 | element.style.left = \`\${offsetLeft}px\`;
74 | `,
75 | },
76 | ],
77 |
78 | invalid: [
79 | {
80 | code: `
81 | function a(element){
82 | element.style.height = "800px";
83 | element.style.width = "800px";
84 | }
85 | `,
86 | errors: [expectedError],
87 | },
88 | {
89 | code: `
90 | element.style.height = "800px";
91 | element.style.width = "800px";
92 | `,
93 | errors: [expectedError],
94 | },
95 | {
96 | code: `
97 | var elements = { element1 };
98 | elements.element1.style.height = "800px";
99 | elements.element1.style.height = "800px";
100 | `,
101 | errors: [expectedError],
102 | },
103 | {
104 | code: `
105 | function changeStyle()
106 | {
107 | var anyScopedVar;
108 | element.style.any = "800px";
109 | anotherChildElement.style.any = "800px";
110 | anyGlobalVar.assignation = "any";
111 | anyScopedVar = anyGlobalVar.assignation;
112 | element.style.anyOther = "800px";
113 | }
114 | `,
115 | errors: [expectedError],
116 | },
117 | ],
118 | });
119 |
--------------------------------------------------------------------------------
/eslint-plugin/tests/lib/rules/no-torch.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | //------------------------------------------------------------------------------
22 | // Requirements
23 | //------------------------------------------------------------------------------
24 |
25 | const rule = require("../../../lib/rules/no-torch");
26 | const RuleTester = require("eslint").RuleTester;
27 |
28 | //------------------------------------------------------------------------------
29 | // Tests
30 | //------------------------------------------------------------------------------
31 |
32 | const ruleTester = new RuleTester({
33 | parserOptions: {
34 | ecmaVersion: 6,
35 | sourceType: "module",
36 | },
37 | });
38 | const expectedError = {
39 | messageId: "ShouldNotProgrammaticallyEnablingTorchMode",
40 | type: "ImportDeclaration",
41 | };
42 |
43 | ruleTester.run("no-torch", rule, {
44 | valid: [
45 | `
46 | import axios from 'axios';
47 | `,
48 | ],
49 |
50 | invalid: [
51 | {
52 | code: "import Torch from 'react-native-torch';",
53 | errors: [expectedError],
54 | },
55 | ],
56 | });
57 |
--------------------------------------------------------------------------------
/eslint-plugin/tests/lib/rules/prefer-collections-with-pagination.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see
.
17 | */
18 |
19 | "use strict";
20 |
21 | //------------------------------------------------------------------------------
22 | // Requirements
23 | //------------------------------------------------------------------------------
24 |
25 | const rule = require("../../../lib/rules/prefer-collections-with-pagination");
26 | const RuleTester = require("eslint").RuleTester;
27 |
28 | //------------------------------------------------------------------------------
29 | // Tests
30 | //------------------------------------------------------------------------------
31 |
32 | const ruleTester = new RuleTester({
33 | // eslint-disable-next-line node/no-missing-require
34 | parser: require.resolve("@typescript-eslint/parser"),
35 | });
36 |
37 | const expectedArrayError = {
38 | messageId: "PreferReturnCollectionsWithPagination",
39 | type: "TSArrayType",
40 | };
41 | const expectedReferenceError = {
42 | messageId: "PreferReturnCollectionsWithPagination",
43 | type: "TSTypeReference",
44 | };
45 |
46 | ruleTester.run("prefer-collections-with-pagination", rule, {
47 | valid: [
48 | `
49 | @Controller()
50 | class Test {
51 | @Get()
52 | public find(): Page {}
53 | }
54 | `,
55 | `
56 | @Controller()
57 | class Test {
58 | @Get()
59 | public find(): Promise
{}
60 | }
61 | `,
62 | `
63 | @Controller()
64 | class Test {
65 | @Get()
66 | public find() {}
67 | }
68 | `,
69 | `
70 | @Controller()
71 | class Test {
72 | @Get(':id')
73 | public findOne(): Promise {}
74 | }
75 | `,
76 | `
77 | @Controller()
78 | class Test {
79 | @Get()
80 | public find(): Promise<{items: string[], currentPage: number, totalPages: number}> {}
81 | }
82 | `,
83 | ],
84 | invalid: [
85 | {
86 | code: `
87 | @Controller()
88 | class Test {
89 | @Get()
90 | public find(): Promise {}
91 | }
92 | `,
93 | errors: [expectedReferenceError],
94 | },
95 | {
96 | code: `
97 | @Controller()
98 | class Test {
99 | @Get()
100 | public find(): Promise {}
101 | }
102 | `,
103 | errors: [expectedReferenceError],
104 | },
105 | {
106 | code: `
107 | @Controller()
108 | class Test {
109 | @Get()
110 | public find(): string[] {}
111 | }
112 | `,
113 | errors: [expectedArrayError],
114 | },
115 | {
116 | code: `
117 | @Controller()
118 | class Test {
119 | @Get()
120 | public find(): Promise<{items: string[]}> {}
121 | }
122 | `,
123 | errors: [expectedReferenceError],
124 | },
125 | ],
126 | });
127 |
--------------------------------------------------------------------------------
/eslint-plugin/tests/lib/rules/prefer-lighter-formats-for-image-files.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 |
19 | "use strict";
20 |
21 | //------------------------------------------------------------------------------
22 | // Requirements
23 | //------------------------------------------------------------------------------
24 |
25 | const rule = require("../../../lib/rules/prefer-lighter-formats-for-image-files");
26 | const RuleTester = require("eslint").RuleTester;
27 |
28 | //------------------------------------------------------------------------------
29 | // Tests
30 | //------------------------------------------------------------------------------
31 |
32 | const ruleTester = new RuleTester({
33 | parserOptions: {
34 | ecmaVersion: 2021,
35 | sourceType: "module",
36 | ecmaFeatures: {
37 | jsx: true,
38 | },
39 | },
40 | });
41 |
42 | const preferLighterFormatsForImageFilesError = {
43 | messageId: "PreferLighterFormatsForImageFiles",
44 | type: "JSXOpeningElement",
45 | };
46 |
47 | ruleTester.run("prefer-lighter-formats-for-image-files", rule, {
48 | valid: [
49 | `
50 |
51 | `,
52 | `
53 |
54 | `,
55 | `
56 |
57 | `,
58 | `
59 |
60 |
61 |
62 |
63 | `,
64 | `
65 |
66 | `,
67 | `
68 |
69 | `,
70 | ],
71 |
72 | invalid: [
73 | {
74 | code: `
75 |
76 | `,
77 | errors: [preferLighterFormatsForImageFilesError],
78 | },
79 | {
80 | code: `
81 |
82 | `,
83 | errors: [preferLighterFormatsForImageFilesError],
84 | },
85 | ],
86 | });
87 |
--------------------------------------------------------------------------------
/eslint-plugin/tests/lib/rules/provide-print-css.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 |
19 | "use strict";
20 |
21 | //------------------------------------------------------------------------------
22 | // Requirements
23 | //------------------------------------------------------------------------------
24 |
25 | const rule = require("../../../lib/rules/provide-print-css");
26 | const RuleTester = require("eslint").RuleTester;
27 |
28 | //------------------------------------------------------------------------------
29 | // Tests
30 | //------------------------------------------------------------------------------
31 |
32 | const ruleTester = new RuleTester({
33 | parserOptions: {
34 | ecmaVersion: 6,
35 | sourceType: "module",
36 | ecmaFeatures: {
37 | jsx: true,
38 | },
39 | },
40 | });
41 |
42 | const expectedError = {
43 | messageId: "noPrintCSSProvided",
44 | type: "JSXElement",
45 | };
46 |
47 | ruleTester.run("provide-print-css", rule, {
48 | valid: [
49 | `
50 |
51 | Web Page
52 |
53 |
54 | `,
55 | `
56 |
57 | Web Page
58 |
59 |
60 | `,
61 | `
62 |
63 | Web Page
64 |
65 |
66 | `,
67 | `
68 |
69 | Web Page
70 | ,
71 |
72 |
73 | `,
74 | "",
75 | ``,
76 | ],
77 | invalid: [
78 | {
79 | code: `
80 |
81 | Web Page
82 |
83 |
84 | `,
85 | errors: [expectedError],
86 | },
87 | {
88 | code: `
89 |
90 | Web Page
91 |
92 |
93 | `,
94 | errors: [expectedError],
95 | },
96 | ],
97 | });
98 |
--------------------------------------------------------------------------------
/eslint-plugin/tests/lib/standalone.test.js:
--------------------------------------------------------------------------------
1 | /*
2 | * creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 |
19 | const assert = require("assert");
20 |
21 | describe("standalone.js", () => {
22 | it("should export list of rule modules", () => {
23 | const { rules } = require("../../lib/standalone");
24 | assert.notEqual(Object.keys(rules).length, 0);
25 | const firstRuleName = Object.keys(rules)[0];
26 | assert.notEqual(rules[firstRuleName].meta, null);
27 | });
28 |
29 | it("should export all rules in recommended configuration", () => {
30 | const { configs, rules } = require("../../lib/standalone");
31 | const recommended = configs.recommended;
32 | assert.notEqual(recommended, null);
33 | assert.equal(recommended.plugins.length, 1);
34 | assert.equal(recommended.plugins[0], "@creedengo");
35 | assert.equal(recommended.rules.length, rules.length);
36 | });
37 | });
38 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/CheckList.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript;
19 |
20 | import org.greencodeinitiative.creedengo.javascript.checks.*;
21 | import org.sonar.plugins.javascript.api.JavaScriptCheck;
22 | import org.sonar.plugins.javascript.api.JavaScriptRule;
23 | import org.sonar.plugins.javascript.api.TypeScriptRule;
24 |
25 | import java.lang.annotation.Annotation;
26 | import java.util.Arrays;
27 | import java.util.List;
28 | import java.util.stream.Collectors;
29 |
30 | public class CheckList {
31 |
32 | private CheckList() {
33 | }
34 |
35 | public static List> getAllChecks() {
36 | return Arrays.asList(
37 | AvoidAutoPlay.class,
38 | AvoidBrightnessOverride.class,
39 | AvoidCSSAnimations.class,
40 | AvoidHighAccuracyGeolocation.class,
41 | AvoidKeepAwake.class,
42 | LimitDbQueryResult.class,
43 | NoEmptyImageSrcAttribute.class,
44 | NoImportAllFromLibrary.class,
45 | NoMultipleAccessDomElement.class,
46 | NoMultipleStyleChanges.class,
47 | NoTorch.class,
48 | PreferCollectionsWithPagination.class,
49 | PreferLighterFormatsForImageFiles.class,
50 | PreferShorthandCSSNotations.class,
51 | ProvidePrintCSS.class
52 | );
53 | }
54 |
55 | public static List> getTypeScriptChecks() {
56 | return filterChecksByAnnotation(TypeScriptRule.class);
57 | }
58 |
59 | public static List> getJavaScriptChecks() {
60 | return filterChecksByAnnotation(JavaScriptRule.class);
61 | }
62 |
63 | private static List> filterChecksByAnnotation(Class extends Annotation> annotation) {
64 | return getAllChecks().stream().filter(check -> check.isAnnotationPresent(annotation)).collect(Collectors.toList());
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/DeprecatedEcoCodeRule.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript;
19 |
20 | import java.lang.annotation.ElementType;
21 | import java.lang.annotation.Retention;
22 | import java.lang.annotation.RetentionPolicy;
23 | import java.lang.annotation.Target;
24 | import java.util.List;
25 |
26 | import org.sonar.api.server.rule.RulesDefinition.NewRepository;
27 | import org.sonar.check.Rule;
28 |
29 | /**
30 | * Used to handle old ecoCode rule keys.
31 | */
32 | public class DeprecatedEcoCodeRule {
33 |
34 | @Retention(RetentionPolicy.RUNTIME)
35 | @Target({ ElementType.TYPE })
36 | public @interface Key {
37 | String value();
38 | }
39 |
40 | public static void addOnRepository(NewRepository repository, String oldRepositoryKey, List> checks) {
41 | checks.forEach(check -> {
42 | if (check.isAnnotationPresent(Key.class)) {
43 | Rule rule = check.getAnnotation(Rule.class);
44 | Key ecoCodeRuleKey = check.getAnnotation(Key.class);
45 | repository.rule(rule.key()).addDeprecatedRuleKey(oldRepositoryKey, ecoCodeRuleKey.value());
46 | }
47 | });
48 | }
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/ESLintRulesBundle.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript;
19 |
20 | import org.sonar.plugins.javascript.api.RulesBundle;
21 |
22 | public class ESLintRulesBundle implements RulesBundle {
23 |
24 | @Override
25 | public String bundlePath() {
26 | return "/creedengo-eslint-plugin.tgz";
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/JavaScriptPlugin.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript;
19 |
20 | import org.sonar.api.Plugin;
21 |
22 | public class JavaScriptPlugin implements Plugin {
23 |
24 | public static final String NAME = "Creedengo";
25 |
26 | @Override
27 | public void define(Context context) {
28 | context.addExtensions(
29 | ESLintRulesBundle.class,
30 | JavaScriptRulesDefinition.class,
31 | JavaScriptRuleRepository.class,
32 | TypeScriptRulesDefinition.class,
33 | TypeScriptRuleRepository.class
34 | );
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/JavaScriptRuleRepository.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript;
19 |
20 | import java.util.EnumSet;
21 | import java.util.List;
22 | import java.util.Set;
23 |
24 | import org.sonar.plugins.javascript.api.CustomRuleRepository;
25 | import org.sonar.plugins.javascript.api.JavaScriptCheck;
26 |
27 | @SuppressWarnings("deprecation")
28 | public class JavaScriptRuleRepository implements CustomRuleRepository {
29 |
30 | public static final String KEY = "creedengo-javascript";
31 |
32 | public static final String OLD_KEY = "ecocode-javascript";
33 |
34 | public static final String LANGUAGE = "js";
35 |
36 | @Override
37 | public Set languages() {
38 | return EnumSet.of(Language.JAVASCRIPT, Language.TYPESCRIPT);
39 | }
40 |
41 | @Override
42 | public String repositoryKey() {
43 | return KEY;
44 | }
45 |
46 | @Override
47 | public List> checkClasses() {
48 | return CheckList.getJavaScriptChecks();
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/JavaScriptRulesDefinition.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript;
19 |
20 | import java.util.Collections;
21 | import java.util.List;
22 |
23 | import org.sonar.api.SonarRuntime;
24 | import org.sonar.api.server.rule.RulesDefinition;
25 | import org.sonarsource.analyzer.commons.RuleMetadataLoader;
26 |
27 | public class JavaScriptRulesDefinition implements RulesDefinition {
28 |
29 | private static final String METADATA_LOCATION = "org/green-code-initiative/rules/javascript";
30 |
31 | private static final String PROFILE_PATH = "org/greencodeinitiative/creedengo/profiles/javascript_profile.json";
32 |
33 | private final SonarRuntime sonarRuntime;
34 |
35 | public JavaScriptRulesDefinition(SonarRuntime sonarRuntime) {
36 | this.sonarRuntime = sonarRuntime;
37 | }
38 |
39 | @Override
40 | public void define(Context context) {
41 | NewRepository repository = context
42 | .createRepository(JavaScriptRuleRepository.KEY, JavaScriptRuleRepository.LANGUAGE)
43 | .setName(JavaScriptPlugin.NAME);
44 |
45 | RuleMetadataLoader ruleMetadataLoader = new RuleMetadataLoader(METADATA_LOCATION, PROFILE_PATH, sonarRuntime);
46 |
47 | List> checks = Collections.unmodifiableList(CheckList.getJavaScriptChecks());
48 |
49 | ruleMetadataLoader.addRulesByAnnotatedClass(repository, checks);
50 | DeprecatedEcoCodeRule.addOnRepository(repository, JavaScriptRuleRepository.OLD_KEY, checks);
51 |
52 | repository.done();
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/TypeScriptRuleRepository.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript;
19 |
20 | import java.util.EnumSet;
21 | import java.util.List;
22 | import java.util.Set;
23 |
24 | import org.sonar.plugins.javascript.api.CustomRuleRepository;
25 | import org.sonar.plugins.javascript.api.JavaScriptCheck;
26 |
27 | @SuppressWarnings("deprecation")
28 | public class TypeScriptRuleRepository implements CustomRuleRepository {
29 |
30 | public static final String KEY = "creedengo-typescript";
31 |
32 | public static final String OLD_KEY = "ecocode-typescript";
33 |
34 | public static final String LANGUAGE = "ts";
35 |
36 | @Override
37 | public Set languages() {
38 | return EnumSet.of(Language.TYPESCRIPT);
39 | }
40 |
41 | @Override
42 | public String repositoryKey() {
43 | return KEY;
44 | }
45 |
46 | @Override
47 | public List> checkClasses() {
48 | return CheckList.getTypeScriptChecks();
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/TypeScriptRulesDefinition.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript;
19 |
20 | import java.util.Collections;
21 | import java.util.List;
22 |
23 | import org.sonar.api.SonarRuntime;
24 | import org.sonar.api.server.rule.RulesDefinition;
25 | import org.sonarsource.analyzer.commons.RuleMetadataLoader;
26 |
27 | public class TypeScriptRulesDefinition implements RulesDefinition {
28 |
29 | private static final String METADATA_LOCATION = "org/green-code-initiative/rules/javascript";
30 |
31 | private static final String PROFILE_PATH = "org/greencodeinitiative/creedengo/profiles/typescript_profile.json";
32 |
33 | private final SonarRuntime sonarRuntime;
34 |
35 | public TypeScriptRulesDefinition(SonarRuntime sonarRuntime) {
36 | this.sonarRuntime = sonarRuntime;
37 | }
38 |
39 | @Override
40 | public void define(Context context) {
41 | NewRepository repository = context
42 | .createRepository(TypeScriptRuleRepository.KEY, TypeScriptRuleRepository.LANGUAGE)
43 | .setName(JavaScriptPlugin.NAME);
44 |
45 | RuleMetadataLoader ruleMetadataLoader = new RuleMetadataLoader(METADATA_LOCATION, PROFILE_PATH, sonarRuntime);
46 |
47 | List> checks = Collections.unmodifiableList(CheckList.getTypeScriptChecks());
48 |
49 | ruleMetadataLoader.addRulesByAnnotatedClass(repository, checks);
50 | DeprecatedEcoCodeRule.addOnRepository(repository, TypeScriptRuleRepository.OLD_KEY, checks);
51 |
52 | repository.done();
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/checks/AvoidAutoPlay.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript.checks;
19 |
20 | import org.sonar.check.Rule;
21 | import org.sonar.plugins.javascript.api.EslintBasedCheck;
22 | import org.sonar.plugins.javascript.api.JavaScriptRule;
23 | import org.sonar.plugins.javascript.api.TypeScriptRule;
24 |
25 | @JavaScriptRule
26 | @TypeScriptRule
27 | @Rule(key = AvoidAutoPlay.RULE_KEY)
28 | public class AvoidAutoPlay implements EslintBasedCheck {
29 |
30 | public static final String RULE_KEY = "GCI36";
31 |
32 | @Override
33 | public String eslintKey() {
34 | return "@creedengo/avoid-autoplay";
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/checks/AvoidBrightnessOverride.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript.checks;
19 |
20 | import org.greencodeinitiative.creedengo.javascript.DeprecatedEcoCodeRule;
21 | import org.sonar.check.Rule;
22 | import org.sonar.plugins.javascript.api.EslintBasedCheck;
23 | import org.sonar.plugins.javascript.api.JavaScriptRule;
24 | import org.sonar.plugins.javascript.api.TypeScriptRule;
25 |
26 | @JavaScriptRule
27 | @TypeScriptRule
28 | @Rule(key = AvoidBrightnessOverride.RULE_KEY)
29 | @DeprecatedEcoCodeRule.Key("EC522")
30 | public class AvoidBrightnessOverride implements EslintBasedCheck {
31 |
32 | public static final String RULE_KEY = "GCI522";
33 |
34 | @Override
35 | public String eslintKey() {
36 | return "@creedengo/avoid-brightness-override";
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/checks/AvoidCSSAnimations.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript.checks;
19 |
20 | import org.greencodeinitiative.creedengo.javascript.DeprecatedEcoCodeRule;
21 | import org.sonar.check.Rule;
22 | import org.sonar.plugins.javascript.api.EslintBasedCheck;
23 | import org.sonar.plugins.javascript.api.JavaScriptRule;
24 | import org.sonar.plugins.javascript.api.TypeScriptRule;
25 |
26 | @JavaScriptRule
27 | @TypeScriptRule
28 | @Rule(key = AvoidCSSAnimations.RULE_KEY)
29 | @DeprecatedEcoCodeRule.Key("EC29")
30 | public class AvoidCSSAnimations implements EslintBasedCheck {
31 |
32 | public static final String RULE_KEY = "GCI29";
33 |
34 | @Override
35 | public String eslintKey() {
36 | return "@creedengo/avoid-css-animations";
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/checks/AvoidHighAccuracyGeolocation.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript.checks;
19 |
20 | import org.greencodeinitiative.creedengo.javascript.DeprecatedEcoCodeRule;
21 | import org.sonar.check.Rule;
22 | import org.sonar.plugins.javascript.api.EslintBasedCheck;
23 | import org.sonar.plugins.javascript.api.JavaScriptRule;
24 | import org.sonar.plugins.javascript.api.TypeScriptRule;
25 |
26 | @JavaScriptRule
27 | @TypeScriptRule
28 | @Rule(key = AvoidHighAccuracyGeolocation.RULE_KEY)
29 | @DeprecatedEcoCodeRule.Key("EC8")
30 | public class AvoidHighAccuracyGeolocation implements EslintBasedCheck {
31 |
32 | public static final String RULE_KEY = "GCI523";
33 |
34 | @Override
35 | public String eslintKey() {
36 | return "@creedengo/avoid-high-accuracy-geolocation";
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/checks/AvoidKeepAwake.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript.checks;
19 |
20 | import org.sonar.check.Rule;
21 | import org.sonar.plugins.javascript.api.EslintBasedCheck;
22 | import org.sonar.plugins.javascript.api.JavaScriptRule;
23 | import org.sonar.plugins.javascript.api.TypeScriptRule;
24 |
25 | @JavaScriptRule
26 | @TypeScriptRule
27 | @Rule(key = AvoidKeepAwake.RULE_KEY)
28 | public class AvoidKeepAwake implements EslintBasedCheck {
29 |
30 | public static final String RULE_KEY = "GCI505";
31 |
32 | @Override
33 | public String eslintKey() {
34 | return "@creedengo/avoid-keep-awake";
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/checks/LimitDbQueryResult.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript.checks;
19 |
20 | import org.greencodeinitiative.creedengo.javascript.DeprecatedEcoCodeRule;
21 | import org.sonar.check.Rule;
22 | import org.sonar.plugins.javascript.api.EslintBasedCheck;
23 | import org.sonar.plugins.javascript.api.JavaScriptRule;
24 | import org.sonar.plugins.javascript.api.TypeScriptRule;
25 |
26 | @JavaScriptRule
27 | @TypeScriptRule
28 | @Rule(key = LimitDbQueryResult.RULE_KEY)
29 | @DeprecatedEcoCodeRule.Key("EC24")
30 | public class LimitDbQueryResult implements EslintBasedCheck {
31 |
32 | public static final String RULE_KEY = "GCI24";
33 |
34 | @Override
35 | public String eslintKey() {
36 | return "@creedengo/limit-db-query-results";
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/checks/NoEmptyImageSrcAttribute.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript.checks;
19 |
20 | import org.greencodeinitiative.creedengo.javascript.DeprecatedEcoCodeRule;
21 | import org.sonar.check.Rule;
22 | import org.sonar.plugins.javascript.api.EslintBasedCheck;
23 | import org.sonar.plugins.javascript.api.JavaScriptRule;
24 | import org.sonar.plugins.javascript.api.TypeScriptRule;
25 |
26 | @JavaScriptRule
27 | @TypeScriptRule
28 | @Rule(key = NoEmptyImageSrcAttribute.RULE_KEY)
29 | @DeprecatedEcoCodeRule.Key("EC25")
30 | public class NoEmptyImageSrcAttribute implements EslintBasedCheck {
31 |
32 | public static final String RULE_KEY = "GCI25";
33 |
34 | @Override
35 | public String eslintKey() {
36 | return "@creedengo/no-empty-image-src-attribute";
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/checks/NoImportAllFromLibrary.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript.checks;
19 |
20 | import org.greencodeinitiative.creedengo.javascript.DeprecatedEcoCodeRule;
21 | import org.sonar.check.Rule;
22 | import org.sonar.plugins.javascript.api.EslintBasedCheck;
23 | import org.sonar.plugins.javascript.api.JavaScriptRule;
24 | import org.sonar.plugins.javascript.api.TypeScriptRule;
25 |
26 | @JavaScriptRule
27 | @TypeScriptRule
28 | @Rule(key = NoImportAllFromLibrary.RULE_KEY)
29 | @DeprecatedEcoCodeRule.Key("EC9")
30 | public class NoImportAllFromLibrary implements EslintBasedCheck {
31 |
32 | public static final String RULE_KEY = "GCI9";
33 |
34 | @Override
35 | public String eslintKey() {
36 | return "@creedengo/no-import-all-from-library";
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/checks/NoMultipleAccessDomElement.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript.checks;
19 |
20 | import org.greencodeinitiative.creedengo.javascript.DeprecatedEcoCodeRule;
21 | import org.sonar.check.Rule;
22 | import org.sonar.plugins.javascript.api.EslintBasedCheck;
23 | import org.sonar.plugins.javascript.api.JavaScriptRule;
24 | import org.sonar.plugins.javascript.api.TypeScriptRule;
25 |
26 | @JavaScriptRule
27 | @TypeScriptRule
28 | @Rule(key = NoMultipleAccessDomElement.RULE_KEY)
29 | @DeprecatedEcoCodeRule.Key("EC11")
30 | public class NoMultipleAccessDomElement implements EslintBasedCheck {
31 |
32 | public static final String RULE_KEY = "GCI11";
33 |
34 | @Override
35 | public String eslintKey() {
36 | return "@creedengo/no-multiple-access-dom-element";
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/checks/NoMultipleStyleChanges.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript.checks;
19 |
20 | import org.greencodeinitiative.creedengo.javascript.DeprecatedEcoCodeRule;
21 | import org.sonar.check.Rule;
22 | import org.sonar.plugins.javascript.api.EslintBasedCheck;
23 | import org.sonar.plugins.javascript.api.JavaScriptRule;
24 | import org.sonar.plugins.javascript.api.TypeScriptRule;
25 |
26 | @JavaScriptRule
27 | @TypeScriptRule
28 | @Rule(key = NoMultipleStyleChanges.RULE_KEY)
29 | @DeprecatedEcoCodeRule.Key("EC12")
30 | public class NoMultipleStyleChanges implements EslintBasedCheck {
31 |
32 | public static final String RULE_KEY = "GCI12";
33 |
34 | @Override
35 | public String eslintKey() {
36 | return "@creedengo/no-multiple-style-changes";
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/checks/NoTorch.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript.checks;
19 |
20 | import org.greencodeinitiative.creedengo.javascript.DeprecatedEcoCodeRule;
21 | import org.sonar.check.Rule;
22 | import org.sonar.plugins.javascript.api.EslintBasedCheck;
23 | import org.sonar.plugins.javascript.api.JavaScriptRule;
24 | import org.sonar.plugins.javascript.api.TypeScriptRule;
25 |
26 | @JavaScriptRule
27 | @TypeScriptRule
28 | @Rule(key = NoTorch.RULE_KEY)
29 | @DeprecatedEcoCodeRule.Key("EC530")
30 | public class NoTorch implements EslintBasedCheck {
31 |
32 | public static final String RULE_KEY = "GCI530";
33 |
34 | @Override
35 | public String eslintKey() {
36 | return "@creedengo/no-torch";
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/checks/PreferCollectionsWithPagination.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript.checks;
19 |
20 | import org.greencodeinitiative.creedengo.javascript.DeprecatedEcoCodeRule;
21 | import org.sonar.check.Rule;
22 | import org.sonar.plugins.javascript.api.EslintBasedCheck;
23 | import org.sonar.plugins.javascript.api.TypeScriptRule;
24 |
25 | @TypeScriptRule
26 | @Rule(key = PreferCollectionsWithPagination.RULE_KEY)
27 | @DeprecatedEcoCodeRule.Key("EC13")
28 | public class PreferCollectionsWithPagination implements EslintBasedCheck {
29 |
30 | public static final String RULE_KEY = "GCI13";
31 |
32 | @Override
33 | public String eslintKey() {
34 | return "@creedengo/prefer-collections-with-pagination";
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/checks/PreferLighterFormatsForImageFiles.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript.checks;
19 |
20 | import org.sonar.check.Rule;
21 | import org.sonar.plugins.javascript.api.EslintBasedCheck;
22 | import org.sonar.plugins.javascript.api.JavaScriptRule;
23 | import org.sonar.plugins.javascript.api.TypeScriptRule;
24 |
25 | @JavaScriptRule
26 | @TypeScriptRule
27 | @Rule(key = PreferLighterFormatsForImageFiles.RULE_KEY)
28 | public class PreferLighterFormatsForImageFiles implements EslintBasedCheck {
29 |
30 | public static final String RULE_KEY = "GCI31";
31 |
32 | @Override
33 | public String eslintKey() {
34 | return "@creedengo/prefer-lighter-formats-for-image-files";
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/checks/PreferShorthandCSSNotations.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript.checks;
19 |
20 | import org.greencodeinitiative.creedengo.javascript.DeprecatedEcoCodeRule;
21 | import org.sonar.check.Rule;
22 | import org.sonar.plugins.javascript.api.EslintBasedCheck;
23 | import org.sonar.plugins.javascript.api.JavaScriptRule;
24 | import org.sonar.plugins.javascript.api.TypeScriptRule;
25 |
26 | @JavaScriptRule
27 | @TypeScriptRule
28 | @Rule(key = PreferShorthandCSSNotations.RULE_KEY)
29 | @DeprecatedEcoCodeRule.Key("EC26")
30 | public class PreferShorthandCSSNotations implements EslintBasedCheck {
31 |
32 | public static final String RULE_KEY = "GCI26";
33 |
34 | @Override
35 | public String eslintKey() {
36 | return "@creedengo/prefer-shorthand-css-notations";
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/java/org/greencodeinitiative/creedengo/javascript/checks/ProvidePrintCSS.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript.checks;
19 |
20 | import org.greencodeinitiative.creedengo.javascript.DeprecatedEcoCodeRule;
21 | import org.sonar.check.Rule;
22 | import org.sonar.plugins.javascript.api.EslintBasedCheck;
23 | import org.sonar.plugins.javascript.api.JavaScriptRule;
24 | import org.sonar.plugins.javascript.api.TypeScriptRule;
25 |
26 | @JavaScriptRule
27 | @TypeScriptRule
28 | @Rule(key = ProvidePrintCSS.RULE_KEY)
29 | @DeprecatedEcoCodeRule.Key("EC30")
30 | public class ProvidePrintCSS implements EslintBasedCheck {
31 |
32 | public static final String RULE_KEY = "GCI30";
33 |
34 | @Override
35 | public String eslintKey() {
36 | return "@creedengo/provide-print-css";
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/resources/org/greencodeinitiative/creedengo/profiles/javascript_profile.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Creedengo",
3 | "ruleKeys": [
4 | "GCI9",
5 | "GCI11",
6 | "GCI12",
7 | "GCI24",
8 | "GCI25",
9 | "GCI26",
10 | "GCI29",
11 | "GCI30",
12 | "GCI31",
13 | "GCI36",
14 | "GCI505",
15 | "GCI523",
16 | "GCI530"
17 | ]
18 | }
19 |
--------------------------------------------------------------------------------
/sonar-plugin/src/main/resources/org/greencodeinitiative/creedengo/profiles/typescript_profile.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Creedengo",
3 | "ruleKeys": ["GCI13"]
4 | }
5 |
--------------------------------------------------------------------------------
/sonar-plugin/src/test/java/org/greencodeinitiative/creedengo/javascript/CheckListTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript;
19 |
20 | import org.junit.jupiter.api.Test;
21 | import org.sonar.check.Rule;
22 | import org.sonar.plugins.javascript.api.EslintBasedCheck;
23 | import org.sonar.plugins.javascript.api.JavaScriptCheck;
24 |
25 | import static org.assertj.core.api.Assertions.assertThat;
26 |
27 | public class CheckListTest {
28 |
29 | @Test
30 | public void check() throws ReflectiveOperationException {
31 | for (Class extends JavaScriptCheck> checkClass : CheckList.getAllChecks()) {
32 | assertThat(checkClass).isAssignableTo(EslintBasedCheck.class);
33 | assertThat(checkClass).hasAnnotation(Rule.class);
34 | EslintBasedCheck check = (EslintBasedCheck) checkClass.getDeclaredConstructor().newInstance();
35 | assertThat(check.eslintKey()).startsWith("@creedengo/");
36 | }
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/sonar-plugin/src/test/java/org/greencodeinitiative/creedengo/javascript/ESLintRulesBundleTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript;
19 |
20 | import org.junit.jupiter.api.Test;
21 |
22 | import static org.assertj.core.api.Assertions.assertThat;
23 |
24 | public class ESLintRulesBundleTest {
25 |
26 | @Test
27 | public void create() {
28 | ESLintRulesBundle bundle = new ESLintRulesBundle();
29 | assertThat(bundle.bundlePath()).isEqualTo("/creedengo-eslint-plugin.tgz");
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/sonar-plugin/src/test/java/org/greencodeinitiative/creedengo/javascript/JavaScriptPluginTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript;
19 |
20 | import org.junit.jupiter.api.Test;
21 | import org.sonar.api.Plugin;
22 | import org.sonar.api.SonarRuntime;
23 |
24 | import static org.assertj.core.api.Assertions.assertThat;
25 | import static org.mockito.Mockito.mock;
26 |
27 | class JavaScriptPluginTest {
28 |
29 | @Test
30 | void extensions() {
31 | SonarRuntime sonarRuntime = mock(SonarRuntime.class);
32 | Plugin.Context context = new Plugin.Context(sonarRuntime);
33 | new JavaScriptPlugin().define(context);
34 | assertThat(context.getExtensions()).hasSize(5);
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/sonar-plugin/src/test/java/org/greencodeinitiative/creedengo/javascript/JavaScriptRuleRepositoryTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript;
19 |
20 | import org.junit.jupiter.api.Test;
21 | import org.sonar.plugins.javascript.api.CustomRuleRepository;
22 |
23 | import static org.assertj.core.api.Assertions.assertThat;
24 |
25 | public class JavaScriptRuleRepositoryTest {
26 |
27 | @Test
28 | public void create() {
29 | JavaScriptRuleRepository repository = new JavaScriptRuleRepository();
30 | assertThat(repository.languages()).containsExactlyInAnyOrder(CustomRuleRepository.Language.JAVASCRIPT, CustomRuleRepository.Language.TYPESCRIPT);
31 | assertThat(repository.repositoryKey()).isEqualTo("creedengo-javascript");
32 | assertThat(repository.checkClasses()).isNotEmpty();
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/sonar-plugin/src/test/java/org/greencodeinitiative/creedengo/javascript/JavaScriptRulesDefinitionTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript;
19 |
20 | import org.junit.jupiter.api.Test;
21 | import org.sonar.api.SonarRuntime;
22 | import org.sonar.api.server.rule.RulesDefinition;
23 | import org.sonar.api.utils.Version;
24 |
25 | import static org.assertj.core.api.Assertions.assertThat;
26 | import static org.mockito.Mockito.mock;
27 | import static org.mockito.Mockito.when;
28 |
29 | class JavaScriptRulesDefinitionTest {
30 |
31 | @Test
32 | void createRepository() {
33 | SonarRuntime sonarRuntime = mock(SonarRuntime.class);
34 | when(sonarRuntime.getApiVersion()).thenReturn(Version.create(0, 0));
35 |
36 | RulesDefinition.Context context = new RulesDefinition.Context();
37 | new JavaScriptRulesDefinition(sonarRuntime).define(context);
38 | assertThat(context.repositories()).hasSize(1);
39 |
40 | RulesDefinition.Repository repository = context.repositories().get(0);
41 | assertThat(repository.isExternal()).isFalse();
42 | assertThat(repository.language()).isEqualTo("js");
43 | assertThat(repository.key()).isEqualTo("creedengo-javascript");
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/sonar-plugin/src/test/java/org/greencodeinitiative/creedengo/javascript/TypeScriptRuleRepositoryTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript;
19 |
20 | import org.junit.jupiter.api.Test;
21 | import org.sonar.plugins.javascript.api.CustomRuleRepository;
22 |
23 | import static org.assertj.core.api.Assertions.assertThat;
24 |
25 | public class TypeScriptRuleRepositoryTest {
26 |
27 | @Test
28 | public void create() {
29 | TypeScriptRuleRepository repository = new TypeScriptRuleRepository();
30 | assertThat(repository.languages()).containsExactlyInAnyOrder(CustomRuleRepository.Language.TYPESCRIPT);
31 | assertThat(repository.repositoryKey()).isEqualTo("creedengo-typescript");
32 | assertThat(repository.checkClasses()).isNotEmpty();
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/sonar-plugin/src/test/java/org/greencodeinitiative/creedengo/javascript/TypeScriptRulesDefinitionTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Creedengo JavaScript plugin - Provides rules to reduce the environmental footprint of your JavaScript programs
3 | * Copyright © 2023 Green Code Initiative (https://green-code-initiative.org)
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package org.greencodeinitiative.creedengo.javascript;
19 |
20 | import org.junit.jupiter.api.Test;
21 | import org.sonar.api.SonarRuntime;
22 | import org.sonar.api.server.rule.RulesDefinition;
23 | import org.sonar.api.utils.Version;
24 |
25 | import static org.assertj.core.api.Assertions.assertThat;
26 | import static org.mockito.Mockito.mock;
27 | import static org.mockito.Mockito.when;
28 |
29 | class TypeScriptRulesDefinitionTest {
30 |
31 | @Test
32 | void createRepository() {
33 | SonarRuntime sonarRuntime = mock(SonarRuntime.class);
34 | when(sonarRuntime.getApiVersion()).thenReturn(Version.create(0, 0));
35 |
36 | RulesDefinition.Context context = new RulesDefinition.Context();
37 | new TypeScriptRulesDefinition(sonarRuntime).define(context);
38 | assertThat(context.repositories()).hasSize(1);
39 |
40 | RulesDefinition.Repository repository = context.repositories().get(0);
41 | assertThat(repository.isExternal()).isFalse();
42 | assertThat(repository.language()).isEqualTo("ts");
43 | assertThat(repository.key()).isEqualTo("creedengo-typescript");
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/sonar-project.properties:
--------------------------------------------------------------------------------
1 | sonar.organization=green-code-initiative
2 | sonar.projectKey=green-code-initiative_ecoCode-linter
3 | sonar.projectName=creedengo - JavaScript language
4 | sonar.sources=eslint-plugin/lib/,eslint-plugin/dist/rules.js,sonar-plugin/src/main/java/
5 | sonar.tests=eslint-plugin/tests/,sonar-plugin/src/test/java/
6 | sonar.javascript.lcov.reportPaths=eslint-plugin/coverage/lcov.info
7 | sonar.java.binaries=sonar-plugin/target/
8 | sonar.coverage.jacoco.xmlReportPaths=sonar-plugin/target/site/jacoco/jacoco.xml
9 |
--------------------------------------------------------------------------------
/test-project/.gitignore:
--------------------------------------------------------------------------------
1 | # Yarn
2 | .pnp.*
3 | .yarn/*
4 | !.yarn/patches
5 | !.yarn/plugins
6 | !.yarn/releases
7 | !.yarn/sdks
8 | !.yarn/versions
9 | node_modules
10 |
11 | # Auto-generated files
12 | *-report.json
13 | .nyc_output
14 | .scannerwork
15 |
--------------------------------------------------------------------------------
/test-project/.yarnrc.yml:
--------------------------------------------------------------------------------
1 | nodeLinker: node-modules
2 |
3 | yarnPath: .yarn/releases/yarn-4.9.1.cjs
4 |
--------------------------------------------------------------------------------
/test-project/README.md:
--------------------------------------------------------------------------------
1 | A sample project to test SonarQube and ESLint plugins of **creedengo-javascript**.
2 |
3 | 👉 See [creedengo-javascript README](../README.md) to have more information.
4 |
5 | ## Purpose of this project
6 |
7 | This project allows to test the rules edited by the ecoCode project for the JavaScript language.\
8 | The files in this repository contain both compliant and non-compliant code.
9 |
10 | ### 1. Setup local environment
11 |
12 | First, follow [this complete guide](https://github.com/green-code-initiative/creedengo-common/blob/main/doc/HOWTO.md#installing-local-environment-local-sonarqube) to install your local SonarQube development environment. \
13 | Then, check that _creedengo_ rules are enabled in the quality profile that will be used during the analysis.
14 |
15 | You will also need some JavaScript tools installed on your computer:
16 |
17 | - A supported version of Node.js
18 | - Yarn (install it globally with `npm install -g yarn`)
19 |
20 | ### 2. Send Sonar metrics to local SonarQube
21 |
22 | Use the following Shell script which will do the job for you:
23 |
24 | ```sh
25 | ./tool_send_to_sonar.sh MY_SONAR_TOKEN
26 | ```
27 |
28 | Or you can manually run these commands:
29 |
30 | - Install dependencies: `yarn install`
31 | - Start Sonar Scanner: `yarn sonar -Dsonar.token=MY_SONAR_TOKEN`
32 |
33 | ### 3. Check errors
34 |
35 | On your SonarQube instance, check if each JavaScript file contains the rule error defined for this class (you can search for tag `eco-design` rule on a special file).
36 |
--------------------------------------------------------------------------------
/test-project/eslint.config.mjs:
--------------------------------------------------------------------------------
1 | import creedengo from "@creedengo/eslint-plugin";
2 | import eslint from "@eslint/js";
3 | import globals from "globals";
4 | import tseslint from "typescript-eslint";
5 |
6 | export default tseslint.config(
7 | eslint.configs.recommended,
8 | tseslint.configs.recommended,
9 | creedengo.configs["flat/recommended"],
10 | {
11 | languageOptions: {
12 | globals: {
13 | ...globals.browser,
14 | ...globals.node,
15 | },
16 | },
17 | }
18 | );
19 |
--------------------------------------------------------------------------------
/test-project/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "creedengo-javascript-test-project",
3 | "version": "1.0.0",
4 | "description": "JavaScript project to test ESLint and SonarQube plugins of creedengo",
5 | "repository": {
6 | "type": "git",
7 | "url": "git+https://github.com/green-code-initiative/creedengo-javascript-test-project.git"
8 | },
9 | "license": "GPL-3.0",
10 | "author": "Green Code Initiative",
11 | "scripts": {
12 | "lint": "eslint src/.",
13 | "lint:report": "eslint src/. -f json -o eslint-report.json",
14 | "sonar": "sonar-scanner"
15 | },
16 | "devDependencies": {
17 | "@creedengo/eslint-plugin": "../eslint-plugin",
18 | "@eslint/js": "^9.25.0",
19 | "@nestjs/common": "^11.0.20",
20 | "eslint": "^9.25.0",
21 | "globals": "^16.0.0",
22 | "sonarqube-scanner": "^4.3.0",
23 | "typescript": "~5.8.3",
24 | "typescript-eslint": "^8.30.1"
25 | },
26 | "packageManager": "yarn@4.9.1"
27 | }
28 |
--------------------------------------------------------------------------------
/test-project/sonar-project.properties:
--------------------------------------------------------------------------------
1 | sonar.exclusions=node_modules
2 | sonar.sources=src
3 | sonar.projectKey=creedengo-javascript-test-project
4 |
--------------------------------------------------------------------------------
/test-project/src/avoid-autoplay.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 |
3 | function AudioComponent() {
4 | return (
5 |
6 | {/* Compliant */}
7 |
8 | {/* Non-compliant */}
9 |
10 | {/* Non-compliant */}
11 |
12 |
13 | );
14 | }
15 |
16 | export default AudioComponent;
17 |
--------------------------------------------------------------------------------
/test-project/src/avoid-brightness-override.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect } from 'react';
2 | import { StyleSheet, View, Text } from 'react-native';
3 | import * as Brightness from 'expo-brightness';
4 |
5 | export default function App() {
6 | useEffect(() => {
7 | (async () => {
8 | const { status } = await Brightness.requestPermissionsAsync();
9 | if (status === 'granted') {
10 | Brightness.setSystemBrightnessAsync(1);
11 | }
12 | })();
13 | }, []);
14 |
15 | return (
16 |
17 | Brightness Module Example
18 |
19 | );
20 | }
21 |
22 | const styles = StyleSheet.create({
23 | container: {
24 | flex: 1,
25 | backgroundColor: '#fff',
26 | alignItems: 'center',
27 | justifyContent: 'center',
28 | },
29 | });
--------------------------------------------------------------------------------
/test-project/src/avoid-high-accuracy-geolocation.js:
--------------------------------------------------------------------------------
1 | import * as Location from 'expo-location';
2 |
3 | // Web
4 | function success(pos) {
5 | console.log(pos.coords);
6 | }
7 |
8 | function error(err) {
9 | console.warn(err);
10 | }
11 |
12 | // Non-compliant: enableHighAccuracy set to true
13 | const invalidOptions = { enableHighAccuracy: true, timeout: 5000 };
14 | navigator.geolocation.getCurrentPosition(success, error, invalidOptions);
15 |
16 | // Compliant: enableHighAccuracy is false by default, so its valid
17 | navigator.geolocation.getCurrentPosition(success);
18 |
19 | // Compliant: explicit enableHighAccuracy set to false
20 | const validOptions = { enableHighAccuracy: false, maximumAge: 0 };
21 | navigator.geolocation.getCurrentPosition(success, error, validOptions);
22 |
23 | // React Native
24 | Location.enableNetworkProviderAsync(); // Non-compliant
25 |
26 | Location.requestPermissionsAsync(); // Compliant
27 |
--------------------------------------------------------------------------------
/test-project/src/avoid-keep-awake-react-native-fn.js:
--------------------------------------------------------------------------------
1 | import { activateKeepAwake, deactivateKeepAwake } from 'expo-keep-awake';
2 | import React from 'react';
3 | import { Button, View } from 'react-native';
4 |
5 | export default class KeepAwakeExample extends React.Component {
6 | render() {
7 | return (
8 |
9 |
10 |
11 |
12 | );
13 | }
14 |
15 | _activate = () => {
16 | // Non-compliant
17 | activateKeepAwake();
18 | alert('Activated!');
19 | };
20 |
21 | _deactivate = () => {
22 | deactivateKeepAwake();
23 | alert('Deactivated!');
24 | };
25 | }
--------------------------------------------------------------------------------
/test-project/src/avoid-keep-awake-react-native-hook.js:
--------------------------------------------------------------------------------
1 | import { useKeepAwake } from 'expo-keep-awake';
2 | import React from 'react';
3 | import { Text, View } from 'react-native';
4 |
5 | export default function KeepAwakeExample() {
6 | // Non-compliant
7 | useKeepAwake();
8 | return (
9 |
10 | This screen will never sleep!
11 |
12 | );
13 | }
--------------------------------------------------------------------------------
/test-project/src/import-all-from-library.js:
--------------------------------------------------------------------------------
1 | import lodash from "lodash"; // Non-compliant: lodash is entirely loaded
2 | import * as _ from "underscore"; // Non-compliant: underscore is entirely loaded
3 |
4 | lodash.isEmpty("");
5 | _.isEmpty("");
6 |
--------------------------------------------------------------------------------
/test-project/src/limit-db-query-results.js:
--------------------------------------------------------------------------------
1 | import mysql from "mysql2";
2 |
3 | // Compliant
4 | let query = "SELECT * FROM customers LIMIT 10";
5 | query = "SELECT TOP 5 * FROM products";
6 | query = "SELECT * FROM orders FETCH FIRST 20 ROWS ONLY";
7 | query =
8 | "WITH numbered_customers AS (SELECT *, ROW_NUMBER() OVER (ORDER BY customer_id) AS row_num FROM customers) SELECT * FROM numbered_customers WHERE row_num <= 50";
9 |
10 | // Non-compliant
11 | query = "SELECT id FROM bikes";
12 |
13 | // Sample to execute the query
14 | const connection = mysql.createConnection({
15 | host: "localhost",
16 | user: "root",
17 | database: "test",
18 | });
19 | connection.query(query, function (_, results, fields) {
20 | console.log(results);
21 | console.log(fields);
22 | });
23 |
--------------------------------------------------------------------------------
/test-project/src/modular-import-from-library.js:
--------------------------------------------------------------------------------
1 | import isEmpty from "lodash/isEmpty"; // Compliant
2 |
3 | isEmpty("");
4 |
--------------------------------------------------------------------------------
/test-project/src/no-css-animations.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 |
3 | function AnimatedComponent() {
4 | return (
5 |
6 | {/* Compliant */}
7 |
8 |
9 |
10 | {/* Non-compliant */}
11 |
12 |
13 | );
14 | }
15 |
16 | export default AnimatedComponent;
17 |
--------------------------------------------------------------------------------
/test-project/src/no-empty-image-src-attribute.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 |
3 | function ImageComponent() {
4 | return (
5 |
6 | {/* Compliant */}
7 |

8 |
9 | {/* Non-compliant */}
10 |
![This is an empty image]()
11 |
12 | );
13 | }
14 |
15 | export default ImageComponent;
16 |
--------------------------------------------------------------------------------
/test-project/src/no-multiple-access-dom-element.js:
--------------------------------------------------------------------------------
1 | // Non-compliant: same dom element accessed multiple times
2 | function invalidShowCard() {
3 | document.querySelector("#card").style.backgroundColor = "red";
4 | document.querySelector("#card").innerHTML = "Hello world!";
5 | }
6 |
7 | // Compliant: dom element is stored in a variable
8 | function validShowCard() {
9 | const card = document.querySelector("#card");
10 | card.style.backgroundColor = "red";
11 | card.innerHTML = "Hello world!";
12 | }
13 |
14 | invalidShowCard();
15 | validShowCard();
16 |
--------------------------------------------------------------------------------
/test-project/src/no-torch.js:
--------------------------------------------------------------------------------
1 | import Torch from "react-native-torch"; // Non-compliant: torch should not be enabled
2 |
3 | Torch.switchState(true);
4 |
--------------------------------------------------------------------------------
/test-project/src/prefer-collections-with-pagination.ts:
--------------------------------------------------------------------------------
1 | import { Controller, Get } from "@nestjs/common";
2 |
3 | interface Pagination {
4 | items: string[];
5 | currentPage: number;
6 | totalPages: number;
7 | }
8 |
9 | @Controller("cats")
10 | export class CatsController {
11 | @Get("raw") // Non-compliant: raw collection is not paginated
12 | public getRawCollection(): Promise {
13 | return new Promise((resolve) => {
14 | setTimeout(() => {
15 | resolve(["Siamese", "Maine Coon", "Chartreux"]);
16 | }, 300);
17 | });
18 | }
19 |
20 | @Get(":id") // Compliant: find a specific item of a collection
21 | public getSpecificItem(): Promise {
22 | return null;
23 | }
24 |
25 | @Get("page") // Compliant: collection is paginated
26 | public getPaginatedCollection(): Promise {
27 | return new Promise((resolve) => {
28 | setTimeout(() => {
29 | resolve({
30 | items: ["Siamese", "Maine Coon", "Chartreux"],
31 | currentPage: 0,
32 | totalPages: 1,
33 | });
34 | }, 300);
35 | });
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/test-project/src/prefer-lighter-formats-for-image-files.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 |
3 | function ImageFilesComponent() {
4 | return (
5 |
6 | {/* Compliant: WEBP */}
7 |

8 |
9 | {/* Compliant: AVIF */}
10 |

11 |
12 | {/* Compliant: JPEG XL */}
13 |

14 |
15 | {/* Compliant: JPG inside a picture */}
16 |
17 |
18 |
19 |
20 |
21 | {/* Compliant: not handled */}
22 |

23 |
24 | {/* Non-compliant: JPG*/}
25 |

26 |
27 | {/* Non-compliant: PNG*/}
28 |

29 |
30 | );
31 | }
32 |
33 | export default ImageFilesComponent;
34 |
--------------------------------------------------------------------------------
/test-project/src/provide-print-css.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 |
3 | function ProvidePrintCSSComponent() {
4 | return (
5 | <>
6 | {/* Non-compliant: head does not contain a link with type print */}
7 |
8 | Web Page
9 |
10 |
11 |
12 | {/* Non-compliant: head does not contain styles dedicated to print media */}
13 |
14 | Web Page
15 |
16 |
17 |
18 | {/* Compliant: head contain a seperate styles file dedicated to print media */}
19 |
20 | Web Page
21 |
22 |
23 |
24 | {/* Compliant: head contain a dedicated print style */}
25 |
26 | Web Page
27 |
28 |
29 | >
30 | );
31 | }
32 |
33 | export default ProvidePrintCSSComponent;
34 |
--------------------------------------------------------------------------------
/test-project/src/rule-no-multiple-style-changes.js:
--------------------------------------------------------------------------------
1 | const element = document.getElementById("#element");
2 |
3 | function invalidStyleChanges() {
4 | element.style.height = "800px"; // Non-compliant: multiple properties assignments
5 | element.style.width = "600px";
6 | element.style.color = "red";
7 | }
8 |
9 | function validStyleChanges() {
10 | element.style.width = "500px"; // Compliant: only one property assignment
11 | element.classList.add("red-color"); // Compliant: use a class to apply multiple styles
12 | }
13 |
14 | invalidStyleChanges();
15 | validStyleChanges();
16 |
--------------------------------------------------------------------------------
/test-project/tool_send_to_sonar.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | # "sonar.token" variable : private TOKEN generated in your local SonarQube during installation
4 | # (input paramater of this script)
5 |
6 | # building phase
7 | yarn install
8 |
9 | # sending to Sonar phase
10 | yarn sonar -Dsonar.host.url=http://0.0.0.0:9000 -Dsonar.token=$1
11 |
--------------------------------------------------------------------------------
/test-project/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "rootDir": ".",
4 | "sourceMap": true,
5 | "declaration": false,
6 | "moduleResolution": "node",
7 | "emitDecoratorMetadata": true,
8 | "experimentalDecorators": true,
9 | "importHelpers": true,
10 | "target": "es2015",
11 | "module": "esnext",
12 | "lib": ["es2017", "dom"],
13 | "skipLibCheck": true,
14 | "skipDefaultLibCheck": true
15 | },
16 | "exclude": ["node_modules"]
17 | }
18 |
--------------------------------------------------------------------------------