Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: eslint max depth warnings #1255

Merged
merged 16 commits into from
Oct 31, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"complexity": ["warn", { "max": 10 }],
"consistent-this": "warn",
"eqeqeq": "error",
"max-depth": ["warn", { "max": 3 }],
"max-depth": ["error", { "max": 3 }],
"max-nested-callbacks": ["warn", { "max": 4 }],
"max-params": ["warn", { "max": 4 }],
"max-statements": ["warn", { "max": 20 }, { "ignoreTopLevelFunctions": true }],
Expand Down
63 changes: 31 additions & 32 deletions src/cli/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@
.choices(["admin", "scoped"])
.default("admin"),
)
.action(async opts => {

Check warning on line 73 in src/cli/build.ts

View workflow job for this annotation

GitHub Actions / format

Async arrow function has too many statements (52). Maximum allowed is 20

Check warning on line 73 in src/cli/build.ts

View workflow job for this annotation

GitHub Actions / format

Async arrow function has a complexity of 15. Maximum allowed is 10
// assign custom output directory if provided
if (opts.outputDir) {
outputDir = opts.outputDir;
Expand All @@ -81,7 +81,7 @@
}

// Build the module
const { cfg, path, uuid } = await buildModule(undefined, opts.entryPoint, opts.embed);

Check failure on line 84 in src/cli/build.ts

View workflow job for this annotation

GitHub Actions / container-scans

Property 'cfg' does not exist on type '{ ctx: BuildContext<BuildOptions>; path: string; cfg: any; uuid: any; } | undefined'.

Check failure on line 84 in src/cli/build.ts

View workflow job for this annotation

GitHub Actions / container-scans

Property 'path' does not exist on type '{ ctx: BuildContext<BuildOptions>; path: string; cfg: any; uuid: any; } | undefined'.

Check failure on line 84 in src/cli/build.ts

View workflow job for this annotation

GitHub Actions / container-scans

Property 'uuid' does not exist on type '{ ctx: BuildContext<BuildOptions>; path: string; cfg: any; uuid: any; } | undefined'.

Check failure on line 84 in src/cli/build.ts

View workflow job for this annotation

GitHub Actions / journey

Property 'cfg' does not exist on type '{ ctx: BuildContext<BuildOptions>; path: string; cfg: any; uuid: any; } | undefined'.

Check failure on line 84 in src/cli/build.ts

View workflow job for this annotation

GitHub Actions / journey

Property 'path' does not exist on type '{ ctx: BuildContext<BuildOptions>; path: string; cfg: any; uuid: any; } | undefined'.

Check failure on line 84 in src/cli/build.ts

View workflow job for this annotation

GitHub Actions / journey

Property 'uuid' does not exist on type '{ ctx: BuildContext<BuildOptions>; path: string; cfg: any; uuid: any; } | undefined'.

// Files to include in controller image for WASM support
const { includedFiles } = cfg.pepr;
Expand Down Expand Up @@ -241,7 +241,7 @@
};
}

export async function buildModule(reloader?: Reloader, entryPoint = peprTS, embed = true) {

Check warning on line 244 in src/cli/build.ts

View workflow job for this annotation

GitHub Actions / format

Async function 'buildModule' has too many statements (35). Maximum allowed is 20
try {
const { cfg, modulePath, path, uuid } = await loadModule(entryPoint);

Expand Down Expand Up @@ -330,41 +330,40 @@
} catch (e) {
console.error(`Error building module:`, e);

if (e.stdout) {
const out = e.stdout.toString() as string;
const err = e.stderr.toString();

console.log(out);
console.error(err);

// Check for version conflicts
if (out.includes("Types have separate declarations of a private property '_name'.")) {
// Try to find the conflicting package
const pgkErrMatch = /error TS2322: .*? 'import\("\/.*?\/node_modules\/(.*?)\/node_modules/g;
out.matchAll(pgkErrMatch);

// Look for package conflict errors
const conflicts = [...out.matchAll(pgkErrMatch)];

// If the regex didn't match, leave a generic error
if (conflicts.length < 1) {
console.info(
`\n\tOne or more imported Pepr Capabilities seem to be using an incompatible version of Pepr.\n\tTry updating your Pepr Capabilities to their latest versions.`,
"Version Conflict",
);
}

// Otherwise, loop through each conflicting package and print an error
conflicts.forEach(match => {
console.info(
`\n\tPackage '${match[1]}' seems to be incompatible with your current version of Pepr.\n\tTry updating to the latest version.`,
"Version Conflict",
);
});
if (!e.stdout) process.exit(1); // Exit with a non-zero exit code on any other error

const out = e.stdout.toString() as string;
const err = e.stderr.toString();

console.log(out);
console.error(err);

// Check for version conflicts
if (out.includes("Types have separate declarations of a private property '_name'.")) {
// Try to find the conflicting package
const pgkErrMatch = /error TS2322: .*? 'import\("\/.*?\/node_modules\/(.*?)\/node_modules/g;
out.matchAll(pgkErrMatch);

// Look for package conflict errors
const conflicts = [...out.matchAll(pgkErrMatch)];

// If the regex didn't match, leave a generic error
if (conflicts.length < 1) {
console.info(
`\n\tOne or more imported Pepr Capabilities seem to be using an incompatible version of Pepr.\n\tTry updating your Pepr Capabilities to their latest versions.`,
"Version Conflict",
);
}

// Otherwise, loop through each conflicting package and print an error
conflicts.forEach(match => {
console.info(
`\n\tPackage '${match[1]}' seems to be incompatible with your current version of Pepr.\n\tTry updating to the latest version.`,
"Version Conflict",
);
});
}

// On any other error, exit with a non-zero exit code
process.exit(1);
}
}
9 changes: 3 additions & 6 deletions src/cli/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
* @param validateOnly
* @returns success
*/
export async function peprFormat(validateOnly: boolean) {

Check warning on line 31 in src/cli/format.ts

View workflow job for this annotation

GitHub Actions / format

Async function 'peprFormat' has too many statements (23). Maximum allowed is 20
{
try {
const eslint = new ESLint();
Expand Down Expand Up @@ -63,13 +63,10 @@
const formatted = await format(content, { filepath: filePath, ...cfg });

// If in validate-only mode, check if the file is formatted correctly
if (validateOnly) {
if (formatted !== content) {
hasFailure = true;
console.error(`File ${filePath} is not formatted correctly`);
}
if (validateOnly && formatted !== content) {
hasFailure = true;
console.error(`File ${filePath} is not formatted correctly`);
} else {
// Otherwise, write the formatted file
await fs.writeFile(filePath, formatted);
}
}
Expand Down
14 changes: 7 additions & 7 deletions src/cli/init/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
Object.entries(response).map(([key, value]) => thisCommand.setOptionValue(key, value));
}
})
.action(async opts => {

Check warning on line 49 in src/cli/init/index.ts

View workflow job for this annotation

GitHub Actions / format

Async arrow function has too many statements (31). Maximum allowed is 20
const dirName = sanitizeName(response.name);
const packageJSON = genPkgJSON(response, pkgOverride);
const peprTS = genPeprTS();
Expand Down Expand Up @@ -86,13 +86,13 @@
});

// try to open vscode
try {
execSync("code .", {
stdio: "inherit",
});
} catch (e) {
// vscode not found, do nothing
}
// try {
execSync("code .", {
stdio: "inherit",
});
// } catch (e) {
// vscode not found, do nothing
// }
samayer12 marked this conversation as resolved.
Show resolved Hide resolved
}

console.log(`New Pepr module created at ${dirName}`);
Expand Down
70 changes: 34 additions & 36 deletions src/cli/monitor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,50 +42,48 @@
const log = new K8sLog(kc);

const logStream = new stream.PassThrough();
logStream.on("data", async chunk => {

Check warning on line 45 in src/cli/monitor.ts

View workflow job for this annotation

GitHub Actions / format

Async arrow function has a complexity of 16. Maximum allowed is 10
const respMsg = `"msg":"Check response"`;
// Split the chunk into lines
const lines = await chunk.toString().split("\n");

for (const line of lines) {
// Check for `"msg":"Hello Pepr"`
if (line.includes(respMsg)) {
try {
const payload = JSON.parse(line.trim());
const isMutate = payload.res.patchType || payload.res.warnings;

const name = `${payload.namespace}${payload.name}`;
const uid = payload.res.uid;

if (isMutate) {
const plainPatch =
payload.res?.patch !== undefined && payload.res?.patch !== null
? atob(payload.res.patch)
: "";

const patch = plainPatch !== "" && JSON.stringify(JSON.parse(plainPatch), null, 2);
const patchType = payload.res.patchType || payload.res.warnings || "";
const allowOrDeny = payload.res.allowed ? "🔀" : "🚫";
console.log(`\n${allowOrDeny} MUTATE ${name} (${uid})`);
if (patchType.length > 0) {
console.log(`\n\u001b[1;34m${patch}\u001b[0m`);
}
} else {
const failures = Array.isArray(payload.res) ? payload.res : [payload.res];

const filteredFailures = failures
.filter((r: ResponseItem) => !r.allowed)
.map((r: ResponseItem) => r.status.message);
if (filteredFailures.length > 0) {
console.log(`\n❌ VALIDATE ${name} (${uid})`);
console.log(`\u001b[1;31m${filteredFailures}\u001b[0m`);
} else {
console.log(`\n✅ VALIDATE ${name} (${uid})`);
}
}
} catch {
// Do nothing
if (!line.includes(respMsg)) continue;
try {
const payload = JSON.parse(line.trim());
const isMutate = payload.res.patchType || payload.res.warnings;

const name = `${payload.namespace}${payload.name}`;
const uid = payload.res.uid;

if (isMutate) {
const plainPatch =
payload.res?.patch !== undefined && payload.res?.patch !== null
? atob(payload.res.patch)
: "";

const patch = plainPatch !== "" && JSON.stringify(JSON.parse(plainPatch), null, 2);
const patchType = payload.res.patchType || payload.res.warnings || "";
const allowOrDeny = payload.res.allowed ? "🔀" : "🚫";
console.log(`\n${allowOrDeny} MUTATE ${name} (${uid})`);
patchType.length > 0 && console.log(`\n\u001b[1;34m${patch}\u001b[0m`);
} else {
const failures = Array.isArray(payload.res) ? payload.res : [payload.res];

const filteredFailures = failures
.filter((r: ResponseItem) => !r.allowed)
.map((r: ResponseItem) => r.status.message);

console.log(
`\n${filteredFailures.length > 0 ? "❌" : "✅"} VALIDATE ${name} (${uid})`,
);
console.log(
filteredFailures.length > 0 ? `\u001b[1;31m${filteredFailures}\u001b[0m` : "",
);
}
} catch {
// Do nothing
}
}
});
Expand Down
44 changes: 22 additions & 22 deletions src/lib/mutate-processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,33 +89,14 @@ export async function mutateProcessor(
updateStatus("warning");
response.warnings = response.warnings || [];

let errorMessage = "";

try {
if (e.message && e.message !== "[object Object]") {
errorMessage = e.message;
} else {
throw new Error("An error occurred in the mutate action.");
}
} catch (e) {
errorMessage = "An error occurred with the mutate action.";
}
const errorMessage =
e.message && e.message !== "[object Object]" ? e.message : "An error occurred in the mutate action.";

// Log on failure
Log.error(actionMetadata, `Action failed: ${errorMessage}`);
response.warnings.push(`Action failed: ${errorMessage}`);

switch (config.onError) {
case Errors.reject:
Log.error(actionMetadata, `Action failed: ${errorMessage}`);
response.result = "Pepr module configured to reject on error";
return response;

case Errors.audit:
response.auditAnnotations = response.auditAnnotations || {};
response.auditAnnotations[Date.now()] = `Action failed: ${errorMessage}`;
break;
}
handleMutationError(errorMessage, actionMetadata, response, config);
}
}
}
Expand Down Expand Up @@ -161,3 +142,22 @@ export async function mutateProcessor(

return response;
}

function handleMutationError(
errorMessage: string,
actionMetadata: Record<string, string>,
response: MutateResponse,
config: ModuleConfig,
) {
switch (config.onError) {
case Errors.reject:
Log.error(actionMetadata, `Action failed: ${errorMessage}`);
response.result = "Pepr module configured to reject on error";
break;

case Errors.audit:
response.auditAnnotations = response.auditAnnotations || {};
response.auditAnnotations[Date.now()] = `Action failed: ${errorMessage}`;
break;
}
}
10 changes: 4 additions & 6 deletions src/lib/validate-processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,10 @@ export async function validateProcessor(
localResponse.allowed = resp.allowed;

// If the validation callback returned a status code or message, set it in the Response
if (resp.statusCode || resp.statusMessage) {
localResponse.status = {
code: resp.statusCode || 400,
message: resp.statusMessage || `Validation failed for ${name}`,
};
}
localResponse.status = {
code: resp.statusCode || 400,
message: resp.statusMessage || `Validation failed for ${name}`,
};
samayer12 marked this conversation as resolved.
Show resolved Hide resolved

Log.info(actionMetadata, `Validation action complete (${label}): ${resp.allowed ? "allowed" : "denied"}`);
} catch (e) {
Expand Down
31 changes: 15 additions & 16 deletions src/lib/watch-processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,23 +101,22 @@
try {
// Then, check if the object matches the filter
const filterMatch = filterNoMatchReason(binding, obj, capabilityNamespaces, ignoredNamespaces);
if (filterMatch === "") {
if (binding.isFinalize) {
if (!obj.metadata?.deletionTimestamp) {
return;
}
try {
await binding.finalizeCallback?.(obj);

// irrespective of callback success / failure, remove pepr finalizer
} finally {
await removeFinalizer(binding, obj);
}
} else {
await binding.watchCallback?.(obj, phase);
}
} else {
if (filterMatch !== "") {
Log.debug(filterMatch);
return;

Check warning on line 106 in src/lib/watch-processor.ts

View check run for this annotation

Codecov / codecov/patch

src/lib/watch-processor.ts#L106

Added line #L106 was not covered by tests
}

if (!binding.isFinalize) {
await binding.watchCallback?.(obj, phase);
return;
}

if (!obj.metadata?.deletionTimestamp) return;

try {
await binding.finalizeCallback?.(obj);

Check warning on line 117 in src/lib/watch-processor.ts

View check run for this annotation

Codecov / codecov/patch

src/lib/watch-processor.ts#L116-L117

Added lines #L116 - L117 were not covered by tests
} finally {
await removeFinalizer(binding, obj);

Check warning on line 119 in src/lib/watch-processor.ts

View check run for this annotation

Codecov / codecov/patch

src/lib/watch-processor.ts#L119

Added line #L119 was not covered by tests
}
} catch (e) {
// Errors in the watch callback should not crash the controller
Expand Down
Loading