Fix Sonar warnings

Fix a bunch of Sonar warnings that somehow appear as "New warnings"
although they are a few years old.
This commit is contained in:
Fred Tingaud 2023-09-22 16:41:56 +02:00 committed by GitHub
parent 4d9f53d097
commit e261bd4b21
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 31 additions and 31 deletions

View File

@ -11,7 +11,7 @@ import Highlight from 'react-highlight';
import { Link as RouterLink, useHistory } from 'react-router-dom';
import { RULE_STATE, useRuleCoverage } from './utils/useRuleCoverage';
import { useFetch } from './utils/useFetch';
import { RuleMetadata } from './types';
import RuleMetadata, { Version, Coverage } from './types/RuleMetadata';
import parse, { attributesToProps, domToReact, DOMNode, Element } from 'html-react-parser';
import './hljs-humanoid-light.css';
@ -242,7 +242,7 @@ function ticketsAndImplementationPRsLinks(ruleNumber: string, title: string, lan
}
}
function RuleThemeProvider({ children }: any) {
const RuleThemeProvider: React.FC = ({ children }) => {
useStyles();
return <ThemeProvider theme={theme}>{children}</ThemeProvider>;
}
@ -253,7 +253,7 @@ interface PageMetadata {
avoid: boolean;
prUrl: string | undefined;
branch: string;
coverage: any;
coverage: Coverage;
jsonString: string | undefined;
}
@ -261,7 +261,7 @@ function usePageMetadata(ruleid: string, language: string, classes: UsedStyles):
const metadataUrl = `${process.env.PUBLIC_URL}/rules/${ruleid}/${language ?? 'default'}-metadata.json`;
let [metadataJSON, metadataError, metadataIsLoading] = useFetch<RuleMetadata>(metadataUrl);
let coverage: any = 'Loading...';
let coverage: Coverage = 'Loading...';
let title = 'Loading...';
let avoid = false;
let metadataJSONString;
@ -287,14 +287,14 @@ function usePageMetadata(ruleid: string, language: string, classes: UsedStyles):
avoid = !ruleStates.some(({ ruleState }) => ruleState === 'covered' || ruleState === 'targeted');
metadataJSONString = JSON.stringify(metadataJSON, null, 2);
const coverageMapper = (key: any, range: any) => {
const coverageMapper = (key: string, range: Version ): JSX.Element => {
if (typeof range === 'string') {
return (
<li key={key} >{key}: {range}</li>
);
} else {
return (
<li>Not covered for {key} anymore. Was covered from {range['since']} to {range['until']}.</li>
<li key={key} >Not covered for {key} anymore. Was covered from {range.since} to {range.until}.</li>
);
}
};

View File

@ -71,7 +71,7 @@ export function generateOneRuleMetadata(srcDir: string, dstDir: string, branch:
// Needed to fetch the sqKey, that might be overridden with a legacy key in each language
const genericMetadata = getRuleMetadata(srcDir);
let metadatasWithAllKeys = [...allMetadata];
const metadatasWithAllKeys = [...allMetadata];
// The rule directory might contain an empty metadata.json
if ('sqKey' in genericMetadata) {

View File

@ -48,7 +48,7 @@ export function fetchMockObject(mockUrls: Record<string, FetchResult>): FetchMoc
}}));
}
} else {
return keeping(Promise.reject(`unexpected url ${url}`));
return keeping(Promise.reject(new Error(`unexpected url ${url}`)));
}
};
return {mock, finished, reset};

View File

@ -5,6 +5,12 @@ export interface LanguageSupport {
status: Status
}
export type Version = string | { since: string, until: string };
export type Mapper = ((key: string, value: Version) => JSX.Element);
export type Coverage = string | JSX.Element[];
export default interface RuleMetadata {
title: string,
languagesSupport: LanguageSupport[],

View File

@ -1,7 +1,6 @@
import { useFetch } from './useFetch';
import { Status } from '../types/RuleMetadata';
import { Status, Version, Mapper, Coverage } from '../types/RuleMetadata';
type Version = string | { since: string, until: string };
type RuleCoverage = Record<string, Record<string, Version>>;
const languageToSonarpedia = new Map<string, string[]>(Object.entries({
@ -43,7 +42,7 @@ export function useRuleCoverage() {
const coveredRulesUrl = `${process.env.PUBLIC_URL}/covered_rules.json`;
const [coveredRules, coveredRulesError, coveredRulesIsLoading] = useFetch<RuleCoverage>(coveredRulesUrl);
function ruleCoverageForSonarpediaKeys(languageKeys: string[], ruleKeys: string[], mapper: any) {
function ruleCoverageForSonarpediaKeys(languageKeys: string[], ruleKeys: string[], mapper: Mapper): Coverage {
if (coveredRulesError) {
return 'Failed Loading';
}
@ -53,7 +52,7 @@ export function useRuleCoverage() {
if (!coveredRules) {
throw new Error('coveredRules is empty');
}
const result: any[] = [];
const result: JSX.Element[] = [];
languageKeys.forEach(language => {
ruleKeys.forEach(ruleKey => {
if (language in coveredRules && ruleKey in coveredRules[language]) {
@ -68,7 +67,7 @@ export function useRuleCoverage() {
}
}
function ruleCoverage(language: string, ruleKeys: string[], mapper: any) {
function ruleCoverage(language: string, ruleKeys: string[], mapper: Mapper): Coverage {
const languageKeys = languageToSonarpedia.get(language);
if (!languageKeys) {
return 'Nonsupported language';
@ -76,7 +75,7 @@ export function useRuleCoverage() {
return ruleCoverageForSonarpediaKeys(languageKeys, ruleKeys, mapper);
}
function allLangsRuleCoverage(ruleKeys: string[], mapper: any) {
function allLangsRuleCoverage(ruleKeys: string[], mapper: Mapper): Coverage {
const allLanguageKeys = Array.from(languageToSonarpedia.values()).flat();
return ruleCoverageForSonarpediaKeys(allLanguageKeys, ruleKeys, mapper);
}

View File

@ -15,12 +15,8 @@ PROBING_SPREAD = 100 # minutes
link_probes_history = {}
# These links consistently fail in CI, but work-on-my-machine
EXCEPTIONS = ['https://blogs.oracle.com/java-platform-group/diagnosing-tls,-ssl,-and-https',
'https://blogs.oracle.com/oraclemagazine/oracle-10g-adds-more-to-forall',
# FIXME: RULEAPI-763 - investigate why these live links respond with 403
'https://medium.com/@cowtowncoder/on-jackson-cves-dont-panic-here-is-what-you-need-to-know-54cd0d6e8062',
'https://medium.com/@nyomanpradipta120/ssti-in-flask-jinja2-20b068fdaeee',
'https://elizarov.medium.com/coroutine-context-and-scope-c8b255d59055']
EXCEPTIONS = [
]
def show_files(filenames):
for filename in filenames:

View File

@ -1,4 +1,3 @@
from rspec_tools.errors import InvalidArgumentError
from pathlib import Path
from typing import List
from contextlib import contextmanager
@ -6,8 +5,8 @@ import shutil
import re
import tempfile
import json
import contextlib
import os
from rspec_tools.errors import InvalidArgumentError
SUPPORTED_LANGUAGES_FILENAME = '../supported_languages.adoc'
LANG_TO_LABEL = {'abap': 'abap',
@ -105,11 +104,11 @@ def swap_metadata_files(dir1:Path, dir2:Path):
shutil.copy2(tmp, meta2)
def is_empty_metadata(rule_dir:Path):
with open(rule_dir.joinpath(METADATA_FILE), 'r') as meta:
with open(rule_dir.joinpath(METADATA_FILE), 'r', encoding='utf8') as meta:
return not json.load(meta)
def load_valid_languages():
with open(SUPPORTED_LANGUAGES_FILENAME, 'r') as supported_langs_file:
with open(SUPPORTED_LANGUAGES_FILENAME, 'r', encoding='utf8') as supported_langs_file:
supported_langs = supported_langs_file.read()
supported_langs = supported_langs.replace(' or', '')
supported_langs = supported_langs.replace('`', '')
@ -147,14 +146,14 @@ def get_label_for_language(language: str) -> str:
return LANG_TO_LABEL[language]
def resolve_rule(rule_id: str) -> int:
m = re.search('^S([0-9]{3,4})$', rule_id)
m = re.search(r'^S(\d{3,4})$', rule_id)
if not m:
raise InvalidArgumentError(f"Unrecognized rule id format: \"{rule_id}\". Rule id must start with an \"S\" followed by 3 or 4 digits.")
else:
return int(m.group(1))
def load_json(file):
with open(file) as json_file:
with open(file, encoding='utf8') as json_file:
return json.load(json_file)
@contextmanager

View File

@ -1,4 +1,3 @@
import collections
from bs4 import BeautifulSoup
from pathlib import Path
from typing import Final
@ -31,13 +30,14 @@ ACCEPTED_FRAMEWORK_NAMES: Final[list[str]] = parse_names('docs/header_names/allo
# This needs to be kept in sync with the [headers list in docs/descriptions.adoc](https://github.com/SonarSource/rspec/blob/master/docs/description.adoc#2-education-format)
MANDATORY_SECTIONS = ['Why is this an issue?']
CODE_EXAMPLES='Code examples'
OPTIONAL_SECTIONS = {
# Also covers 'How to fix it in {Framework Display Name}'
'How to fix it': ['Code examples', 'How does this work?', 'Pitfalls', 'Going the extra mile'],
'How to fix it': [CODE_EXAMPLES, 'How does this work?', 'Pitfalls', 'Going the extra mile'],
'Resources': ['Documentation', 'Articles & blog posts', 'Conference presentations', 'Standards', 'External coding guidelines', 'Benchmarks', 'Related rules']
}
SUBSECTIONS = {
'Code examples': ['Noncompliant code example', 'Compliant solution']
CODE_EXAMPLES: ['Noncompliant code example', 'Compliant solution']
}
def validate_duplications(h2_titles, rule_language):
@ -173,7 +173,7 @@ def validate_subsections(rule_language: LanguageSpecificRule):
else:
validate_subsections_for_section(rule_language, optional_section, OPTIONAL_SECTIONS[optional_section])
for subsection_with_sub_subsection in list(SUBSECTIONS.keys()):
if subsection_with_sub_subsection == 'Code examples':
if subsection_with_sub_subsection == CODE_EXAMPLES:
validate_subsections_for_section(rule_language, subsection_with_sub_subsection, SUBSECTIONS[subsection_with_sub_subsection], level=4, is_duplicate_allowed=True)
else:
validate_subsections_for_section(rule_language, subsection_with_sub_subsection, SUBSECTIONS[subsection_with_sub_subsection], level=4)

View File

@ -26,7 +26,7 @@ FORALL i IN INDICES OF l_tab
== Resources
* https://blogs.oracle.com/oraclemagazine/oracle-10g-adds-more-to-forall[Oracle 10g Adds More to FORALL]
* https://asktom.oracle.com/Misc/oramag/oracle-10g-adds-more-to-forall.html[Oracle 10g Adds More to FORALL]
* https://stevenfeuersteinonplsql.blogspot.com/2019/03/using-sparse-collections-with-forall.html[Using sparse collections with FORALL] - Steven Feuerstein
ifdef::env-github,rspecator-view[]