Skip to content

Commit

Permalink
refactor: corrected sonar warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
rH4rtinger committed Oct 10, 2024
1 parent 7b964df commit 0a70d8f
Show file tree
Hide file tree
Showing 23 changed files with 96 additions and 175 deletions.
1 change: 0 additions & 1 deletion .github/workflows/nodejs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -170,4 +170,3 @@ jobs:
-Dsonar.organization=aditosoftware
-Dsonar.eslint.reportPaths=eslint-results.json
-Dsonar.javascript.lcov.reportPaths=coverage/lcov.info
-Dsonar.tests=src/test
4 changes: 2 additions & 2 deletions src/cache/CacheHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ export class CacheHandler {
readContexts(connectionLocation: string, changelogLocation: string): ContextSelection {
const existingChangelog = this.getChangelog(connectionLocation, changelogLocation).existingChangelog;

if (existingChangelog && existingChangelog.contexts) {
if (existingChangelog?.contexts) {
// sort any loaded contexts
existingChangelog.contexts.loadedContexts?.sort((a, b) => a.localeCompare(b));

Expand All @@ -287,7 +287,7 @@ export class CacheHandler {
readChangelogs(connectionLocation: string): string[] {
const cache = this.readCache();

if (cache[connectionLocation] && cache[connectionLocation].changelogs) {
if (cache[connectionLocation]?.changelogs) {
return cache[connectionLocation].changelogs
.toSorted((a, b) => b.lastUsed - a.lastUsed)
.map((pChangelog) => pChangelog.path);
Expand Down
8 changes: 4 additions & 4 deletions src/cache/CacheRemover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export class CacheRemover {

const toRemove = result.inputValues.get(CacheRemover.removeOption);

if (toRemove && toRemove[0]) {
if (toRemove?.[0]) {
this.handleRemoval(toRemove[0], result);
}
}
Expand Down Expand Up @@ -170,9 +170,9 @@ export class CacheRemover {

// Build the details
let detail = "";
if (toRemove && toRemove[0]) {
if (toRemove?.[0]) {
// add information about the remove option
detail = CacheRemover.removeOptions.get(toRemove[0]) || "";
detail = CacheRemover.removeOptions.get(toRemove[0]) ?? "";
}

if (propertyFiles) {
Expand All @@ -193,7 +193,7 @@ export class CacheRemover {
private shouldShowPropertyFileSelection(currentResults: DialogValues): boolean {
const toRemove = currentResults.inputValues.get(CacheRemover.removeOption);

if (toRemove && toRemove[0]) {
if (toRemove?.[0]) {
return toRemove[0] !== RemoveCacheOptions.WHOLE_CACHE;
} else {
return false;
Expand Down
6 changes: 3 additions & 3 deletions src/configuration/data/DatabaseConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export class DatabaseConnection {
if (driver) {
// and extract the url parts
return driver.extractUrlParts(this.url);
} else if (customDriver && customDriver[this.databaseType]) {
} else if (customDriver?.[this.databaseType]) {
return new CustomDriver(customDriver[this.databaseType]).extractUrlParts(this.url);
}

Expand All @@ -89,7 +89,7 @@ export class DatabaseConnection {
*/
getValue(pName: keyof DatabaseConnection): string | undefined {
if (typeof this[pName] === "string") {
return this[pName] as string;
return this[pName];
}
}

Expand All @@ -100,7 +100,7 @@ export class DatabaseConnection {
* @param pValue - the value that should be set
* @returns the updated element
*/
setValue(pName: keyof DatabaseConnection, pValue: string): DatabaseConnection {
setValue(pName: keyof DatabaseConnection, pValue: string): this {
if (typeof this[pName] === "string") {
(this[pName] as string) = pValue;
}
Expand Down
2 changes: 1 addition & 1 deletion src/configuration/data/LiquibaseConfigurationData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ export class LiquibaseConfigurationData {
}

// and write the reference properties
if (this.referenceDatabaseConnection && this.referenceDatabaseConnection.hasData()) {
if (this.referenceDatabaseConnection?.hasData()) {
this.referenceDatabaseConnection.writeDataForConnection(properties, true, pDisguisePassword);
}

Expand Down
2 changes: 1 addition & 1 deletion src/configuration/handleChangelogSelection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export async function chooseFileForChangelog(data: LiquibaseConfigurationData):
},
});

if (result && result[0]) {
if (result?.[0]) {
const chosenFile = result[0].fsPath;

// find out relative path
Expand Down
6 changes: 3 additions & 3 deletions src/executeJar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ export function executeJarAsync<ErrorCode extends number>(
}
});

childProcess.on("error", (error) => {
childProcess.on("error", (error: Error) => {
Logger.getLogger().error({ message: "Child process encountered an error", error });
reject(error);
});
Expand Down Expand Up @@ -233,11 +233,11 @@ export async function loadContextsFromChangelogFile(
error: { stack: result.stderr },
notifyUser: true,
});
reject(`Error ${result.status}, ${result.error?.message}\n ${result.stderr}`);
reject(new Error(`Error ${result.status}, ${result.error?.message}\n ${result.stderr}`));
}
} catch (error) {
Logger.getLogger().error({ message: "Error loading contexts", error, notifyUser: true });
reject(error);
reject(error as Error);
}
});
}
Expand Down
22 changes: 2 additions & 20 deletions src/handleChangelogFileInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export class HandleChangelogFileInput {
*/
private static getChangelogFileFromProperties(dialogValues: DialogValues): string | undefined {
const propertyFile = dialogValues.inputValues.get(PROPERTY_FILE);
if (propertyFile && propertyFile[0]) {
if (propertyFile?.[0]) {
const changelog = readChangelog(propertyFile[0]);
if (changelog) {
// if there is a changelog in in property-file, return it, so we can show it in the dialog
Expand All @@ -114,24 +114,6 @@ export class HandleChangelogFileInput {
}
}

/**
* Checks if the changelog needs to be put into by an extra open dialog.
*
* @param dialogValues - the current dialog values
* @returns `true` if an OpenDialog is needed for selecting the changelog
*/
private static isChangelogFromOpenDialogNeeded(dialogValues: DialogValues): boolean {
if (this.isExtraQueryForChangelogNeeded(dialogValues)) {
const changelogPreSelection = dialogValues.inputValues.get(this.CHANGELOG_QUICK_PICK_NAME);
if (changelogPreSelection && changelogPreSelection[0]) {
// check, if the correct option was selected
return changelogPreSelection[0] === CHOOSE_CHANGELOG_OPTION;
}
}

return false;
}

/**
* Sets the changelog file from the current dialog correctly as uri (exactly as context menu).
* This will mimic the behavior from a context menu, which is correct in this case.
Expand All @@ -145,7 +127,7 @@ export class HandleChangelogFileInput {

let changelogPath: string | undefined;

if (fileSelection && fileSelection[0]) {
if (fileSelection?.[0]) {
if (fileSelection[0] === CHOOSE_CHANGELOG_OPTION) {
// we are not having a correct values selected, but instead a dialog progression value
// => we do not need to save anything
Expand Down
14 changes: 4 additions & 10 deletions src/handleContexts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,7 @@ export function generateContextInputs(): PickPanelConfig[] {
export function generateItemsForContextPreDialog(contextCacheInfo?: ContextCacheInformation): vscode.QuickPickItem[] {
const items: vscode.QuickPickItem[] = [];

if (
contextCacheInfo &&
contextCacheInfo.contexts.loadedContexts &&
contextCacheInfo.contexts.loadedContexts.length !== 0
) {
if (contextCacheInfo?.contexts.loadedContexts && contextCacheInfo?.contexts.loadedContexts.length !== 0) {
const cachedContexts = contextCacheInfo.contexts.loadedContexts.join(", ");
items.push({
label: ContextOptions.USE_RECENTLY_LOADED,
Expand Down Expand Up @@ -132,10 +128,8 @@ export function saveSelectedContexts(dialogValues: DialogValues, contextCacheInf
*/
function generateCmdArgsForPreContextSelection(dialogValues: DialogValues): string[] | undefined {
const selected = dialogValues.inputValues.get(contextPreDialog);
if (selected && selected[0]) {
if (selected[0] === ContextOptions.NO_CONTEXT) {
return [`--contexts=${NO_CONTEXT_USED}`];
}
if (selected?.[0] === ContextOptions.NO_CONTEXT) {
return [`--contexts=${NO_CONTEXT_USED}`];
}
}

Expand Down Expand Up @@ -189,7 +183,7 @@ export function loadCacheForPropertyFile(currentResults: DialogValues): ContextC
function showContextSelection(dialogValues: DialogValues): boolean {
const result = dialogValues.inputValues.get(contextPreDialog);

if (result && result[0]) {
if (result?.[0]) {
return result[0] !== ContextOptions.NO_CONTEXT;
}

Expand Down
2 changes: 1 addition & 1 deletion src/handleLiquibaseSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export function getDefaultDatabaseForConfiguration(): string {
NO_PRE_CONFIGURED_DRIVER
);

return defaultDatabaseForConfiguration ? defaultDatabaseForConfiguration : NO_PRE_CONFIGURED_DRIVER;
return defaultDatabaseForConfiguration || NO_PRE_CONFIGURED_DRIVER;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/liquibaseCommandsUtilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ export async function openIndexHtmlAfterCommandExecution(dialogValues: DialogVal
export async function changeAndEmptyOutputDirectory(dialogValues: DialogValues): Promise<void> {
const folder = dialogValues.inputValues.get(folderSelectionName)?.[0];

if (folder && folder.includes(os.tmpdir())) {
if (folder?.includes(os.tmpdir())) {
const propertyFile = dialogValues.inputValues.get(PROPERTY_FILE)?.[0];

let configurationName = "db-doc";
Expand Down
31 changes: 14 additions & 17 deletions src/panels/LiquibaseConfigurationPanel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ import path from "path";
* - Setting message listeners so data can be passed between the webview and extension
*/
export class LiquibaseConfigurationPanel {
public static currentPanel: LiquibaseConfigurationPanel | undefined;
private static currentPanel: LiquibaseConfigurationPanel | undefined;
private readonly _panel: WebviewPanel;
private _disposables: Disposable[] = [];
private readonly _disposables: Disposable[] = [];

/**
* The LiquibaseConfigurationPanel class private constructor (called only from the render method).
Expand Down Expand Up @@ -84,16 +84,15 @@ export class LiquibaseConfigurationPanel {
// In all cases, transfer a message with the current data
this.transferMessage(
MessageType.INIT,
data
? data
: LiquibaseConfigurationData.createDefaultData(
{
defaultDatabaseForConfiguration: getDefaultDatabaseForConfiguration(),
liquibaseDirectoryInProject: getLiquibaseFolder(),
customDrivers: getCustomDrivers(),
},
ConfigurationStatus.NEW
)
data ||
LiquibaseConfigurationData.createDefaultData(
{
defaultDatabaseForConfiguration: getDefaultDatabaseForConfiguration(),
liquibaseDirectoryInProject: getLiquibaseFolder(),
customDrivers: getCustomDrivers(),
},
ConfigurationStatus.NEW
)
);
}

Expand Down Expand Up @@ -212,12 +211,10 @@ export class LiquibaseConfigurationPanel {
default:
throw new Error(`Handling for command ${messageType} not found.`);
}
} else if (messageData.messageType === MessageType.LOG_MESSAGE) {
Logger.getLogger().log(data);
} else {
if (messageData.messageType === MessageType.LOG_MESSAGE) {
Logger.getLogger().log(data);
} else {
throw new Error(`Handling for command ${messageType} not found.`);
}
throw new Error(`Handling for command ${messageType} not found.`);
}
},
undefined,
Expand Down
2 changes: 1 addition & 1 deletion src/prerequisites.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ async function downloadLiquibaseFiles(pathToResources: string, downloadUrls: str
return new Promise<void>((resolve, reject) => {
Promise.all(downloadUrls.map((url) => download(url, path.join(pathToResources))))
.then(() => resolve())
.catch((error) => {
.catch((error: Error) => {
Logger.getLogger().error({ message: "downloadLiquibaseFiles threw an error", error });
reject(error);
});
Expand Down
2 changes: 1 addition & 1 deletion src/settings/removeConfiguration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ export function generateDetailMessageForDeleteConfiguration(dialogValues: Dialog
whatDeleted
.get(deletionMode)
?.map((pElement) => "- " + pElement)
.join("\n") || "";
.join("\n") ?? "";
}

return `This will remove the configuration from the following:\n${deletedDetail}`;
Expand Down
23 changes: 9 additions & 14 deletions src/test/e2e/commands/update.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,25 +42,20 @@ suite("Update", function () {
"SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'person'"
);

if (option === ContextOptions.NO_CONTEXT) {
if (
option !== ContextOptions.NO_CONTEXT &&
(key === "all available contexts" || key === "the first available context")
) {
assert.ok(
databaseInformation?.length >= 1,
`Table 'person' DOES NOT exist, while it should: ${databaseInformation}`
);
} else {
assert.strictEqual(
databaseInformation.length,
0,
`Table 'person' DOES exist, while it shouldn't: ${databaseInformation}`
);
} else {
if (key === "all available contexts" || key === "the first available context") {
assert.ok(
databaseInformation?.length >= 1,
`Table 'person' DOES NOT exist, while it should: ${databaseInformation}`
);
} else {
assert.strictEqual(
databaseInformation.length,
0,
`Table 'person' DOES exist, while it shouldn't: ${databaseInformation}`
);
}
}
});
});
Expand Down
4 changes: 2 additions & 2 deletions src/test/suite/DockerTestUtils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { exec } from "child_process";
import { exec, ExecException } from "child_process";
import { isWindows } from "../../utilities/osUtilities";
import mariadb from "mariadb";

Expand Down Expand Up @@ -186,7 +186,7 @@ export class DockerTestUtils {
*/
private static async executeCommand(command: string): Promise<string> {
return new Promise((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
exec(command, (error: ExecException | null, stdout, stderr) => {
if (error) {
reject(error);
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,20 +99,20 @@ suite("configurationCommands", () => {
Sinon.stub(handleLiquibaseFolder, "getLiquibaseConfigurationPath").resolves("myFolder");
Sinon.stub(ConnectionType, "suggestCreationOfConfiguration").resolves();

assert.ok(!LiquibaseConfigurationPanel.currentPanel, "no current panel created");
assert.ok(!LiquibaseConfigurationPanel["currentPanel"], "no current panel created");

configurationCommand
.editExistingLiquibaseConfiguration(undefined, extensionContext)
.then(() => {
const currentPanel = LiquibaseConfigurationPanel.currentPanel;
const currentPanel = LiquibaseConfigurationPanel["currentPanel"];
assert.ok(!currentPanel, "panel is not created");

done();
})
.catch(done)
.finally(() => {
// dispose manually after the tests
LiquibaseConfigurationPanel.currentPanel?.dispose();
LiquibaseConfigurationPanel["currentPanel"]?.dispose();
});
});
});
Expand Down Expand Up @@ -448,12 +448,12 @@ function assertEditExistingLiquibaseConfiguration(
): void {
Sinon.stub(handleLiquibaseFolder, "getLiquibaseFolder").returns("myFolder");

assert.ok(!LiquibaseConfigurationPanel.currentPanel, "no current panel created");
assert.ok(!LiquibaseConfigurationPanel["currentPanel"], "no current panel created");

configurationCommand
.editExistingLiquibaseConfiguration(uri, extensionContext)
.then(() => {
const currentPanel = LiquibaseConfigurationPanel.currentPanel;
const currentPanel = LiquibaseConfigurationPanel["currentPanel"];
assert.ok(currentPanel, "panel was created");
const webviewPanel = currentPanel["_panel"];
assert.ok(webviewPanel.visible, "panel is visible");
Expand All @@ -462,15 +462,15 @@ function assertEditExistingLiquibaseConfiguration(
if (uri) {
LiquibaseConfigurationPanel.render(uri);

assert.ok(LiquibaseConfigurationPanel.currentPanel?.["_panel"], "panel is still visible");
assert.ok(LiquibaseConfigurationPanel["currentPanel"]?.["_panel"], "panel is still visible");
}

done();
})
.catch(done)
.finally(() => {
// dispose manually after the tests
LiquibaseConfigurationPanel.currentPanel?.dispose();
LiquibaseConfigurationPanel["currentPanel"]?.dispose();
});
}

Expand Down
Loading

0 comments on commit 0a70d8f

Please sign in to comment.