Skip to content

Commit

Permalink
Corrected linter
Browse files Browse the repository at this point in the history
  • Loading branch information
GermanBluefox committed Jan 21, 2025
1 parent 720ea2d commit 21ced3d
Show file tree
Hide file tree
Showing 19 changed files with 322 additions and 238 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
PLACEHOLDER for the next version:
## **WORK IN PROGRESS**
-->
## 5.0.1 (2025-01-21)
## **WORK IN PROGRESS**
* Packages were updated

## 5.0.0 (2024-09-14)
Expand Down
102 changes: 23 additions & 79 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -1,93 +1,37 @@
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import js from '@eslint/js';
import { FlatCompat } from '@eslint/eslintrc';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
recommendedConfig: js.configs.recommended,
allConfig: js.configs.all,
});
import config from '@iobroker/eslint-config';

export default [
...config,
{
ignores: ['**/build/', '**/node_modules/'],
},
...compat.extends('plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended'),
{
plugins: {},

files: ['src/**/*.ts'],
linterOptions: {
reportUnusedDisableDirectives: true,
},

rules: {
'@typescript-eslint/no-unsafe-declaration-merging': 'off',
'@typescript-eslint/no-parameter-properties': 'off',
'@typescript-eslint/no-explicit-any': 'off',

'@typescript-eslint/no-use-before-define': [
'error',
{
functions: false,
typedefs: false,
classes: false,
},
],

'@typescript-eslint/no-unused-vars': [
'error',
{
ignoreRestSiblings: true,
argsIgnorePattern: '^_',
languageOptions: {
parserOptions: {
projectService: {
allowDefaultProject: ['*.mjs'],
},
],

'@typescript-eslint/explicit-function-return-type': [
'warn',
{
allowExpressions: true,
allowTypedFunctionExpressions: true,
},
],

'@typescript-eslint/no-object-literal-type-assertion': 'off',
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/no-non-null-assertion': 'off',

'@typescript-eslint/no-inferrable-types': [
'error',
{
ignoreParameters: true,
ignoreProperties: true,
},
],
tsconfigRootDir: import.meta.dirname,
project: './tsconfig.json',
},
},
},
{
files: ['**/*.test.ts'],

rules: {
'@typescript-eslint/explicit-function-return-type': 'off',
},
ignores: [
'src-admin/**/*',
'admin/**/*',
'node_modules/**/*',
'test/**/*',
'build/**/*',
'tasks.js',
'tmp/**/*',
'.**/*',
],
},
{
files: ['**/*.js'],
// disable temporary the rule 'jsdoc/require-param' and enable 'jsdoc/require-jsdoc'
rules: {
// Disable all TypeScript-specific rules for JavaScript files
'jsdoc/require-jsdoc': 'off',
'jsdoc/require-param': 'off',

'@typescript-eslint/no-require-imports': 'off',
'@typescript-eslint/no-parameter-properties': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-use-before-define': 'off',
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-object-literal-type-assertion': 'off',
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-inferrable-types': 'off',
},
},
];
15 changes: 10 additions & 5 deletions src/lib/adapterTools.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// Add debug logging for tests
// @ts-expect-error no types
import { isArray, isObject } from 'alcalzone-shared/typeguards';
import debugModule from 'debug';
import { pathExists } from 'fs-extra';
Expand All @@ -8,19 +7,19 @@ const debug = debugModule('testing:unit:adapterTools');

/**
* Loads an adapter's package.json
*
* @param adapterDir The directory the adapter resides in
*/
export function loadNpmPackage(adapterDir: string): Record<string, any> {
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require(path.join(adapterDir, 'package.json'));
}

/**
* Loads an adapter's io-package.json
*
* @param adapterDir The directory the adapter resides in
*/
export function loadIoPackage(adapterDir: string): Record<string, any> {
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require(path.join(adapterDir, 'io-package.json'));
}

Expand All @@ -31,6 +30,7 @@ export function getAdapterExecutionMode(adapterDir: string): ioBroker.AdapterCom

/**
* Locates an adapter's main file
*
* @param adapterDir The directory the adapter resides in
*/
export async function locateAdapterMainFile(adapterDir: string): Promise<string> {
Expand All @@ -54,7 +54,7 @@ export async function locateAdapterMainFile(adapterDir: string): Promise<string>
}

// If both don't exist, JS-Controller uses <adapter name>.js as another fallback
ret = path.join(adapterDir, ioPackage.common.name + '.js');
ret = path.join(adapterDir, `${ioPackage.common.name}.js`);
debug(` => trying ${ret}`);
if (await pathExists(ret)) {
debug(` => found ${mainFile}`);
Expand All @@ -66,6 +66,7 @@ export async function locateAdapterMainFile(adapterDir: string): Promise<string>

/**
* Locates an adapter's config to populate the `adapter.config` object with
*
* @param adapterDir The directory the adapter resides in
*/
export function loadAdapterConfig(adapterDir: string): Record<string, any> {
Expand All @@ -75,6 +76,7 @@ export function loadAdapterConfig(adapterDir: string): Record<string, any> {

/**
* Loads the adapter's common configuration from `io-package.json`
*
* @param adapterDir The directory the adapter resides in
*/
export function loadAdapterCommon(adapterDir: string): Record<string, any> {
Expand All @@ -84,6 +86,7 @@ export function loadAdapterCommon(adapterDir: string): Record<string, any> {

/**
* Loads the instanceObjects for an adapter from its `io-package.json`
*
* @param adapterDir The directory the adapter resides in
*/
export function loadInstanceObjects(adapterDir: string): ioBroker.Object[] {
Expand Down Expand Up @@ -119,7 +122,9 @@ export function getAdapterDependencies(adapterDir: string): Record<string, strin
ret[dep] = 'latest';
} else if (isObject(dep)) {
const key = Object.keys(dep)[0];
if (key) ret[key] = (dep as Record<string, string>)[key] || 'latest';
if (key) {
ret[key] = (dep as Record<string, string>)[key] || 'latest';
}
}
}
}
Expand Down
31 changes: 22 additions & 9 deletions src/lib/executeCommand.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { SpawnOptions, spawn } from 'child_process';
import { type SpawnOptions, spawn } from 'child_process';

const isWindows = /^win/.test(process.platform);

Expand Down Expand Up @@ -32,6 +32,7 @@ export function executeCommand(
): Promise<ExecuteCommandResult>;
/**
* Executes a command and returns the exit code and (if requested) the stdout
*
* @param command The command to execute
* @param args The command line arguments for the command
* @param options (optional) Some options for the command execution
Expand All @@ -49,19 +50,25 @@ export function executeCommand(
return new Promise(resolve => {
let args: string[] | undefined;
if (Array.isArray(argsOrOptions)) {
args = argsOrOptions as string[];
args = argsOrOptions;
} else if (argsOrOptions && typeof argsOrOptions === 'object') {
// no args were given
options = argsOrOptions;
}
if (options == null) options = {};
if (args == null) args = [];
if (options == null) {
options = {};
}
if (args == null) {
args = [];
}

const spawnOptions: SpawnOptions = {
stdio: [options.stdin || process.stdin, options.stdout || process.stdout, options.stderr || process.stderr],
windowsHide: true,
};
if (options.cwd != null) spawnOptions.cwd = options.cwd;
if (options.cwd != null) {
spawnOptions.cwd = options.cwd;
}

// Fix npm / node executable paths on Windows
if (isWindows) {
Expand All @@ -75,9 +82,11 @@ export function executeCommand(
}
}

if (options.logCommandExecution == null) options.logCommandExecution = false;
if (options.logCommandExecution == null) {
options.logCommandExecution = false;
}
if (options.logCommandExecution) {
console.log('executing: ' + `${command} ${args.join(' ')}`);
console.log(`executing: ${command} ${args.join(' ')}`);
}

// Now execute the npm process and avoid throwing errors
Expand All @@ -96,14 +105,18 @@ export function executeCommand(
if (options.stdout === 'pipe') {
bufferedStdout = '';
cmd.stdout!.on('data', (chunk: Buffer | string) => {
if (Buffer.isBuffer(chunk)) chunk = chunk.toString('utf8');
if (Buffer.isBuffer(chunk)) {
chunk = chunk.toString('utf8');
}
bufferedStdout! += chunk;
});
}
if (options.stderr === 'pipe') {
bufferedStderr = '';
cmd.stderr!.on('data', (chunk: Buffer | string) => {
if (Buffer.isBuffer(chunk)) chunk = chunk.toString('utf8');
if (Buffer.isBuffer(chunk)) {
chunk = chunk.toString('utf8');
}
bufferedStderr! += chunk;
});
}
Expand Down
4 changes: 2 additions & 2 deletions src/tests/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { createMocks } from './unit/harness/createMocks';
import { createAsserts } from './unit/mocks/mockDatabase';

export { TestHarness as IntegrationTestHarness } from './integration/lib/harness';
export { MockAdapter } from './unit/mocks/mockAdapter';
export type { MockAdapter } from './unit/mocks/mockAdapter';
export { MockDatabase } from './unit/mocks/mockDatabase';

/** Predefined test sets */
Expand All @@ -22,6 +22,6 @@ export const utils = {
createMocks,
createAsserts,
/** @deprecated Adapter startup unit tests are no longer supported */
startMockAdapter: () => ({}),
startMockAdapter: (): any => ({}),
},
};
7 changes: 6 additions & 1 deletion src/tests/integration/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,10 +150,15 @@ export function testAdapter(adapterDir: string, options: TestAdapterOptions = {}
// Adapters with these modes are allowed to "immediately" exit with code 0
switch (harness.getAdapterExecutionMode()) {
case 'schedule':
allowedExitCodes.add(0);
break;
case 'once':
allowedExitCodes.add(0);
break;
// @ts-expect-error subscribe was deprecated
case 'subscribe':
allowedExitCodes.add(0);
break;
}

return new Promise<string>((resolve, reject) => {
Expand Down Expand Up @@ -191,7 +196,7 @@ export function testAdapter(adapterDir: string, options: TestAdapterOptions = {}
);
}
});
harness.startAdapter();
void harness.startAdapter();
}).then(msg => console.log(msg));
});
});
Expand Down
17 changes: 12 additions & 5 deletions src/tests/integration/lib/adapterSetup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,9 @@ export class AdapterSetup {
const packResult = await executeCommand('npm', ['pack', '--loglevel', 'silent'], {
stdout: 'pipe',
});
if (packResult.exitCode !== 0 || typeof packResult.stdout !== 'string')
if (packResult.exitCode !== 0 || typeof packResult.stdout !== 'string') {
throw new Error(`Packing the adapter tarball failed!`);
}

// The last non-empty line of `npm pack`s STDOUT contains the tarball path
const stdoutLines = packResult.stdout.trim().split(/[\r\n]+/);
Expand All @@ -79,13 +80,17 @@ export class AdapterSetup {
packageJson.dependencies[this.adapterFullName] = `file:./${tarballName}`;
for (const [dep, version] of entries(getAdapterDependencies(this.adapterDir))) {
// Don't overwrite the js-controller GitHub dependency with a probably lower one
if (dep === 'js-controller') continue;
if (dep === 'js-controller') {
continue;
}
packageJson.dependencies[`${this.appName}.${dep}`] = version;
}
await writeJSON(packageJsonPath, packageJson, { spaces: 2 });

debug('Deleting old remains of this adapter');
if (await pathExists(this.testAdapterDir)) await remove(this.testAdapterDir);
if (await pathExists(this.testAdapterDir)) {
await remove(this.testAdapterDir);
}

debug('Installing adapter');
// Defer to npm to install the controller (if it wasn't already)
Expand All @@ -111,7 +116,9 @@ export class AdapterSetup {
stdout: 'ignore',
},
);
if (addResult.exitCode !== 0) throw new Error(`Adding the adapter instance failed!`);
if (addResult.exitCode !== 0) {
throw new Error(`Adding the adapter instance failed!`);
}
debug(' => done!');
}

Expand All @@ -121,7 +128,7 @@ export class AdapterSetup {
const allKeys = new Set([...(await dbConnection.getObjectIDs()), ...(await dbConnection.getStateIDs())]);

const instanceRegex = new RegExp(`^system\\.adapter\\.${this.adapterName}\\.\\d+`);
const instanceObjsRegex = new RegExp(`^${this.adapterName}\\.\\d+\.`);
const instanceObjsRegex = new RegExp(`^${this.adapterName}\\.\\d+\\.`);

const belongsToAdapter = (id: string): boolean => {
return (
Expand Down
Loading

0 comments on commit 21ced3d

Please sign in to comment.