Fix the following SonarQube code smells:

1) Use the "RegExp.exec()" method instead.
2) Remove parameter form or provide default value.
3) Extract this nested ternary operation into an independent statement.
4) Replace this character class by the character itself.
5) Unnecessary use of conditional expression for default assignment.
6) Prefer using an optional chain expression instead, as it's more concise and easier to read.
This commit is contained in:
Akshay Joshi 2024-06-11 18:07:22 +05:30
parent bdf4f39b2b
commit df2f3460f0
17 changed files with 102 additions and 69 deletions

View File

@ -41,7 +41,7 @@ class BaseAuthentication(metaclass=AuthSourceRegistry):
pass
@abstractmethod
def authenticate(self):
def authenticate(self, form):
pass
def validate(self, form):

View File

@ -27,7 +27,6 @@ from pgadmin.utils.constants import KERBEROS, MessageType
from pgadmin.utils import PgAdminModule
from pgadmin.utils.ajax import make_json_response, internal_server_error
from pgadmin.authenticate.internal import BaseAuthentication
from pgadmin.authenticate import get_auth_sources
from pgadmin.utils.csrf import pgCSRFProtect

View File

@ -275,6 +275,6 @@ class OAuth2Authentication(BaseAuthentication):
authorized_claims = [authorized_claims]
if any(item in authorized_claims for item in claim):
reason = "Claim match found. Authorized access."
return (True, reason)
reason = f"No match was found."
return (False, reason)
return True, reason
reason = "No match was found."
return False, reason

View File

@ -18,7 +18,7 @@ class PPAS(ServerType):
" programs (pg_dump, pg_restore etc)."
)
def instance_of(self, ver):
def instance_of(self, ver=None):
return "EnterpriseDB" in ver

View File

@ -390,7 +390,34 @@ export function StorageWrapper(props) {
},
};
return (
function getLabel(item, index) {
if (item.mount_point !== '')
return item.mount_point;
return item.drive_letter !== '' ? item.drive_letter : 'disk' + index;
}
function getChartContainerTitle(type) {
if (type.endsWith('_bytes_rw'))
return gettext('Data transfer');
if (type.endsWith('_total_rw'))
return gettext('I/O operations count');
if (type.endsWith('_time_rw'))
return gettext('Time spent in I/O operations');
return '';
}
function getValue(type, v) {
if (type.endsWith('_time_rw'))
return toPrettySize(v, 'ms');
if (type.endsWith('_total_rw'))
return toPrettySize(v, '');
return toPrettySize(v);
}
return (
<Root>
<div className='Storage-tableContainer'>
<div className='Storage-containerHeaderText'>{gettext('Disk information')}</div>
@ -403,12 +430,12 @@ export function StorageWrapper(props) {
title={''}
datasets={props.diskStats.map((item, index) => ({
borderColor: colors[(index + 2) % colors.length],
label: item.mount_point !== '' ? item.mount_point : item.drive_letter !== '' ? item.drive_letter : 'disk' + index,
label: getLabel(item, index),
}))}
errorMsg={props.errorMsg}
isTest={props.isTest}>
<PieChart data={{
labels: props.diskStats.map((item, index) => item.mount_point!=''?item.mount_point:item.drive_letter!=''?item.drive_letter:'disk'+index),
labels: props.diskStats.map((item, index) => getLabel(item, index)),
datasets: [
{
data: props.diskStats.map((item) => item.total_space_actual?item.total_space_actual:0),
@ -426,7 +453,7 @@ export function StorageWrapper(props) {
<Grid item md={6} sm={12}>
<ChartContainer id='ua-space-graph' title={''} datasets={[{borderColor: '#FF6384', label: 'Used space'}, {borderColor: '#36a2eb', label: 'Available space'}]} errorMsg={props.errorMsg} isTest={props.isTest}>
<BarChart data={{
labels: props.diskStats.map((item, index) => item.mount_point!=''?item.mount_point:item.drive_letter!=''?item.drive_letter:'disk'+index),
labels: props.diskStats.map((item, index) => getLabel(item, index)),
datasets: [
{
label: 'Used space',
@ -476,10 +503,10 @@ export function StorageWrapper(props) {
<Grid container spacing={0.5} p={0.5}>
{Object.keys(props.ioInfo[drive]).map((type, innerKeyIndex) => (
<Grid key={`${type}-${innerKeyIndex}`} item md={4} sm={6}>
<ChartContainer id={`io-graph-${type}`} title={type.endsWith('_bytes_rw') ? gettext('Data transfer'): type.endsWith('_total_rw') ? gettext('I/O operations count'): type.endsWith('_time_rw') ? gettext('Time spent in I/O operations'):''} datasets={transformData(props.ioInfo[drive][type], props.ioRefreshRate).datasets} errorMsg={props.errorMsg} isTest={props.isTest}>
<ChartContainer id={`io-graph-${type}`} title={getChartContainerTitle(type)} datasets={transformData(props.ioInfo[drive][type], props.ioRefreshRate).datasets} errorMsg={props.errorMsg} isTest={props.isTest}>
<StreamingChart data={transformData(props.ioInfo[drive][type], props.ioRefreshRate)} dataPointSize={DATA_POINT_SIZE} xRange={X_AXIS_LENGTH} options={options}
valueFormatter={(v)=>{
return type.endsWith('_time_rw') ? toPrettySize(v, 'ms') : type.endsWith('_total_rw') ? toPrettySize(v, ''): toPrettySize(v);
return getValue(type, v);
}} />
</ChartContainer>
</Grid>

View File

@ -124,7 +124,11 @@ export function checkMasterPassword(data, masterpass_callback_queue, cancel_call
// This functions is used to show the master password dialog.
export function showMasterPassword(isPWDPresent, errmsg, masterpass_callback_queue, cancel_callback, keyring_name='') {
const api = getApiInstance();
let title = keyring_name.length > 0 ? gettext('Migrate Saved Passwords') : isPWDPresent ? gettext('Unlock Saved Passwords') : gettext('Set Master Password');
let title = gettext('Set Master Password');
if (keyring_name.length > 0)
title = gettext('Migrate Saved Passwords');
else if (isPWDPresent)
title = gettext('Unlock Saved Passwords');
pgAdmin.Browser.notifier.showModal(title, (onClose)=> {
return (

View File

@ -65,7 +65,7 @@ export class FileTreeItem extends React.Component<IItemRendererXProps & IItemRen
? 'file'
: 'directory';
if (this.props.item.parent && this.props.item.parent.path) {
if (this.props.item.parent?.path) {
this.props.item.resolvedPathCache = this.props.item.parent.path + '/' + this.props.item._metadata.data.id;
}
@ -98,8 +98,8 @@ export class FileTreeItem extends React.Component<IItemRendererXProps & IItemRen
<span className='file-label'>
{
item._metadata && item._metadata.data.icon ?
<i className={cn('file-icon', item._metadata && item._metadata.data.icon ? item._metadata.data.icon : fileOrDir)} /> : null
item._metadata?.data?.icon ?
<i className={cn('file-icon', item._metadata?.data?.icon ? item._metadata.data.icon : fileOrDir)} /> : null
}
<span className='file-name'>
{ _.unescape(this.props.item.getMetadata('data')._label)}

View File

@ -51,7 +51,7 @@ export class FileTreeX extends React.Component<IFileTreeXProps> {
onScroll={this.props.onScroll}
ref={this.wrapperRef}
style={{
height: height ? height : 'calc(100vh - 60px)',
height: height || 'calc(100vh - 60px)',
width: '100%',
display: 'flex',
flexDirection: 'column',
@ -66,7 +66,7 @@ export class FileTreeX extends React.Component<IFileTreeXProps> {
model={model}
itemHeight={FileTreeItem.renderHeight}
onReady={this.handleTreeReady}
disableCache={disableCache ? disableCache : false}
disableCache={disableCache || false}
>
{(props: IItemRendererProps) => <FileTreeItem
item={props.item}
@ -267,7 +267,7 @@ export class FileTreeX extends React.Component<IFileTreeXProps> {
} else {
await this.fileTreeHandle.openDirectory(parentDir as Directory);
maybeFile = await create(parentDir.path, itemData);
if (maybeFile && maybeFile.type && maybeFile.name) {
if (maybeFile?.type && maybeFile?.name) {
model.root.inotify({
type: WatchEvent.Added,
directory: parentDir.path,
@ -378,7 +378,7 @@ export class FileTreeX extends React.Component<IFileTreeXProps> {
: fileOrDirOrPath;
if (fileH === FileType.Directory || fileH === FileType.File) {
return fileH.parent ? true : false;
return fileH.parent;
}
return false;
@ -608,8 +608,8 @@ export class FileTreeX extends React.Component<IFileTreeXProps> {
};
private resize = (scrollX, scrollY) => {
const scrollXPos = scrollX ? scrollX : 0;
const scrollYPos = scrollY ? scrollY : this.props.model.state.scrollOffset;
const scrollXPos = scrollX || 0;
const scrollYPos = scrollY || this.props.model.state.scrollOffset;
const div = this.wrapperRef.current.querySelector('div').querySelector('div') as HTMLDivElement;
div.scroll(scrollXPos, scrollYPos);

View File

@ -46,7 +46,7 @@ export default function GotoDialog({editor, show, onClose}) {
const onKeyPress = (e) => {
if (e.key === 'Enter') {
e.preventDefault();
if(!/^[ ]*[1-9][0-9]*[ ]*(,[ ]*[1-9][0-9]*[ ]*){0,1}$/.test(gotoVal)) {
if(!/^ *[1-9]\d* *(, *[1-9]\d* *)?$/.test(gotoVal)) {
return;
}
const v = gotoVal.split(',').map(Number);

View File

@ -29,13 +29,13 @@ export function getBrowserAccesskey() {
/* Ref: https://www.w3schools.com/tags/att_accesskey.asp */
let ua = window.navigator.userAgent;
// macOS
if (ua.match(/macintosh/i)) {
if ((/macintosh/i).exec(ua)) {
return ['Ctrl', 'Option'];
}
// Windows / Linux
if (ua.match(/windows/i) || ua.match(/linux/i)) {
if(ua.match(/firefox/i)) {
if ((/windows/i).exec(ua) || (/linux/i).exec(ua)) {
if((/firefox/i).exec(ua)) {
return ['Alt', 'Shift'];
}
return ['Alt'];

View File

@ -17,7 +17,7 @@ define([], function() {
options = options || {};
let re = /(^-?\d+(\.?\d*)[df]?e?\d?$|^0x[0-9a-f]+$|\d+)/gi,
sre = /(^[ ]*|[ ]*$)/g,
sre = /(^ *| *$)/g,
dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
hre = /^0x[0-9a-f]+$/i,
ore = /^0/,
@ -31,8 +31,8 @@ define([], function() {
xN = x.replace(re, '\0$1\0').replace(/\0$/, '').replace(/^\0/, '').split('\0'),
yN = y.replace(re, '\0$1\0').replace(/\0$/, '').replace(/^\0/, '').split('\0'),
// numeric, hex or date detection
xD = parseInt(x.match(hre)) || (xN.length !== 1 && x.match(dre) && Date.parse(x)),
yD = parseInt(y.match(hre)) || xD && y.match(dre) && Date.parse(y) || null,
xD = parseInt(hre.exec(x)) || (xN.length !== 1 && dre.exec(x) && Date.parse(x)),
yD = parseInt(hre.exec(y)) || xD && dre.exec(y) && Date.parse(y) || null,
oFxNcL, oFyNcL,
mult = options.desc ? -1 : 1;
@ -44,8 +44,8 @@ define([], function() {
// natural sorting through split numeric strings and default strings
for (let cLoc = 0, numS = Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
// find floats not starting with '0', string or 0 if not defined (Clint Priest)
oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
oFxNcL = !ore.exec(xN[cLoc] || '') && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
oFyNcL = !ore.exec(yN[cLoc] || '') && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
// handle numeric vs string comparison - number < string - (Kyle Adams)
if (isNaN(oFxNcL) !== isNaN(oFyNcL)) {
return (isNaN(oFxNcL) ? 1 : -1) * mult;

View File

@ -14,7 +14,7 @@ let testElem = document.createElement('test'),
defaultView = document.defaultView,
getComputedStyle = defaultView?.getComputedStyle,
computedValueBug,
runit = /^(-?[\d+\.\-]+)([a-z]+|%)$/i,
runit = /^(-?[\d+.-]+)([a-z]+|%)$/i,
convert = {},
conversions = [1 / 25.4, 1 / 2.54, 1 / 72, 1 / 6],
units = ['mm', 'cm', 'pt', 'pc', 'in', 'mozmm'],
@ -53,7 +53,7 @@ export default function toPx(value, prop, force, el) {
// use width as the default property, or specify your own
prop = prop || 'width';
var style,
let style,
inlineValue,
ret,
unit = (value.match(runit) || [])[2],
@ -63,7 +63,10 @@ export default function toPx(value, prop, force, el) {
if (conversion || rem.test(unit) && !force) {
// calculate known conversions immediately
// find the correct element for absolute units or rem or fontSize + em or em
elem = conversion ? elem : unit === 'rem' ? docElement : prop === 'fontSize' ? elem.parentNode || elem : elem;
if (unit === 'rem')
elem = docElement;
else if (prop === 'fontSize')
elem = elem.parentNode || elem;
// use the pre-calculated conversion or fontSize of the element for rem and em
conversion = conversion || parseFloat(curCSS(elem, 'fontSize'));
@ -101,7 +104,7 @@ export default function toPx(value, prop, force, el) {
// return the computed value of a CSS property
function curCSS(elem, prop) {
var value,
let value,
pixel,
unit,
rvpos = /^(top|bottom)/,
@ -132,7 +135,8 @@ function curCSS(elem, prop) {
// WebKit won't convert percentages for top, bottom, left, right, margin and text-indent
if (rvpos.test(prop)) {
// Top and bottom require measuring the innerHeight of the parent.
innerHeight = (parent = elem.parentNode || elem).offsetHeight;
parent = elem.parentNode || elem;
innerHeight = parent.offsetHeight;
while (i--) {
innerHeight -= parseFloat(curCSS(parent, outerProp[i]));
}

View File

@ -39,7 +39,7 @@ export class ManagePreferenceTreeNodes {
public removeNode = async (_path) => {
const item = this.findNode(_path);
if (item && item.parentNode) {
if (item?.parentNode) {
item.children = [];
item.parentNode.children.splice(item.parentNode.children.indexOf(item), 1);
}
@ -77,10 +77,10 @@ export class ManagePreferenceTreeNodes {
if (node && node.children.length > 0) {
if (!node.type === FileType.File) {
rej('It\'s a leaf node');
rej(new Error('It\'s a leaf node'));
}
else {
if (node?.children.length != 0) res(node.children);
else if (node?.children.length != 0) {
res(node.children);
}
}
@ -131,7 +131,7 @@ export class TreeNode {
this.domNode = domNode;
this.metadata = metadata;
this.name = metadata ? metadata.data.label : '';
this.type = type ? type : undefined;
this.type = type || undefined;
}
hasParent() {
@ -159,7 +159,7 @@ export class TreeNode {
} else if (this.data === null) {
return null;
}
return Object.assign({}, this.data);
return {...this.data};
}
getHtmlIdentifier() {
@ -220,7 +220,7 @@ export class TreeNode {
resolve(true);
},
() => {
reject();
reject(new Error());
});
});
}
@ -233,7 +233,7 @@ export class TreeNode {
} else if (tree.isOpen(this.domNode)) {
resolve(true);
} else {
tree.open(this.domNode).then(() => resolve(true), () => reject(true));
tree.open(this.domNode).then(() => resolve(true), () => reject(new Error(true)));
}
});
}

View File

@ -44,7 +44,7 @@ export class ManageTreeNodes {
public removeNode = async (_path) => {
const item = this.findNode(_path);
if (item && item.parentNode) {
if (item?.parentNode) {
item.children = [];
item.parentNode.children.splice(item.parentNode.children.indexOf(item), 1);
}
@ -85,8 +85,8 @@ export class ManageTreeNodes {
console.error(node, 'It\'s a leaf node');
return [];
}
else {
if (node.children.length != 0) return node.children;
else if (node.children.length != 0) {
return node.children;
}
}
@ -99,14 +99,12 @@ export class ManageTreeNodes {
if (node.metadata.data._pid == null ) {
url = node.metadata.data._type + '/children/' + node.metadata.data._id;
}
else if (node.metadata.data._type.includes('coll-')) {
const _type = node.metadata.data._type.replace('coll-', '');
url = _type + '/nodes/' + _parent_url + '/';
}
else {
if (node.metadata.data._type.includes('coll-')) {
const _type = node.metadata.data._type.replace('coll-', '');
url = _type + '/nodes/' + _parent_url + '/';
}
else {
url = node.metadata.data._type + '/children/' + _parent_url + '/' + node.metadata.data._id;
}
url = node.metadata.data._type + '/children/' + _parent_url + '/' + node.metadata.data._id;
}
url = base_url + url;
@ -168,7 +166,8 @@ export class ManageTreeNodes {
// Replace the table with the last partition as in reality partition node is not child of the table
if(_partitions.length > 0) _parent_path[0] = _partitions[_partitions.length-1];
return _parent_path.reverse().join('/');
_parent_path.reverse();
return _parent_path.join('/');
};
}
@ -183,7 +182,7 @@ export class TreeNode {
this.domNode = domNode;
this.metadata = metadata;
this.name = metadata ? metadata.data.label : '';
this.type = type ? type : undefined;
this.type = type || undefined;
}
hasParent() {
@ -211,7 +210,7 @@ export class TreeNode {
} else if (this.data === null) {
return null;
}
return Object.assign({}, this.data);
return {...this.data};
}
getHtmlIdentifier() {
@ -272,7 +271,7 @@ export class TreeNode {
resolve(true);
},
()=>{
reject();
reject(new Error());
});
});
}
@ -285,7 +284,7 @@ export class TreeNode {
} else if(tree.isOpen(this.domNode)) {
resolve(true);
} else {
tree.open(this.domNode).then(() => resolve(true), () => reject(true));
tree.open(this.domNode).then(() => resolve(true), () => reject(new Error(true)));
}
});
}

View File

@ -13,7 +13,7 @@ module.exports = function(endpoint, substitutions) {
let rawURL = endpoints[endpoint];
// captures things of the form <path:substitutionName>
let substitutionGroupsRegExp = /([<])([^:^>]*:)?([^>]+)([>])/g,
let substitutionGroupsRegExp = /(<)([^:^>]*:)?([^>]+)(>)/g,
interpolated = rawURL;
if (!rawURL)

View File

@ -363,7 +363,7 @@ export function evalFunc(obj, func, ...param) {
}
export function getBrowser() {
let ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
let ua=navigator.userAgent,tem,M=(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i).exec(ua) || [];
if(/trident/i.test(M[1])) {
tem=/\brv[ :]+(\d+)/g.exec(ua) || [];
return {name:'IE', version:(tem[1]||'')};
@ -374,12 +374,12 @@ export function getBrowser() {
}
if(M[1]==='Chrome') {
tem=ua.match(/\bOPR|Edge\/(\d+)/);
tem=(/\bOPR|Edge\/(\d+)/).exec(ua);
if(tem!=null) {return {name:tem[0], version:tem[1]};}
}
M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);}
if((tem=(/version\/(\d+)/i).exec(ua))!=null) {M.splice(1,1,tem[1]);}
return {
name: M[0],
version: M[1],
@ -659,4 +659,4 @@ export function getChartColor(index, theme='standard', colorPalette=CHART_THEME_
const palette = colorPalette[theme];
// loop back if out of index;
return palette[index % palette.length];
}
}

View File

@ -32,7 +32,7 @@ class ConnectionLost(HTTPException):
def name(self):
return HTTP_STATUS_CODES.get(503, SERVICE_UNAVAILABLE)
def get_response(self, environ=None):
def get_response(self, environ=None, scope=None):
return service_unavailable(
_("Connection to the server has been lost."),
info="CONNECTION_LOST",
@ -65,7 +65,7 @@ class SSHTunnelConnectionLost(HTTPException):
def name(self):
return HTTP_STATUS_CODES.get(503, SERVICE_UNAVAILABLE)
def get_response(self, environ=None):
def get_response(self, environ=None, scope=None):
return service_unavailable(
_("Connection to the SSH Tunnel for host '{0}' has been lost. "
"Reconnect to the database server.").format(self.tunnel_host),
@ -97,7 +97,7 @@ class CryptKeyMissing(HTTPException):
def name(self):
return HTTP_STATUS_CODES.get(503, SERVICE_UNAVAILABLE)
def get_response(self, environ=None):
def get_response(self, environ=None, scope=None):
return service_unavailable(
_(self.CRYPT_KEY_MISSING),
info="CRYPTKEY_MISSING",
@ -123,7 +123,7 @@ class ObjectGone(HTTPException):
def name(self):
return HTTP_STATUS_CODES.get(410, 'Gone')
def get_response(self, environ=None):
def get_response(self, environ=None, scope=None):
return gone(self.error_msg)
def __str__(self):
@ -146,7 +146,7 @@ class ExecuteError(HTTPException):
def name(self):
return HTTP_STATUS_CODES.get(500, 'Internal server error')
def get_response(self, environ=None):
def get_response(self, environ=None, scope=None):
return internal_server_error(self.error_msg)
def __str__(self):