Skip to content

Commit

Permalink
adds more error handling for file read and parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
dimitropoulos committed Sep 9, 2024
1 parent ce55b7d commit 6a38073
Showing 1 changed file with 26 additions and 13 deletions.
39 changes: 26 additions & 13 deletions packages/eslint-plugin-turbo/lib/rules/no-undeclared-env-vars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import path from "node:path";
import { readFileSync } from "node:fs";
import type { Rule } from "eslint";
import type { Node, MemberExpression } from "estree";
import { logger, searchUp } from "@turbo/utils";
import { type PackageJson, logger, searchUp } from "@turbo/utils";
import { frameworks } from "@turbo/types";
import { RULES } from "../constants";
import { Project, getWorkspaceFromFilePath } from "../utils/calculate-inputs";
Expand Down Expand Up @@ -80,18 +80,31 @@ function normalizeCwd(
/** for a given `package.json` file path, this will compile a Set of that package's listed dependencies */
const packageJsonDependencies = (filePath: string): Set<string> => {
// get the contents of the package.json
const packageJsonString = readFileSync(filePath, "utf-8");
const packageJson = JSON.parse(packageJsonString) as Record<
string,
undefined | Record<string, string>
>;

return [
"dependencies",
"devDependencies",
"peerDependencies",
// intentionally not including `optionalDependencies` or `bundleDependencies` because at the time of writing they are not used for any of the frameworks we support
]
let packageJsonString;

try {
packageJsonString = readFileSync(filePath, "utf-8");
} catch (e) {
logger.error(`Could not read package.json at ${filePath}`);
return new Set();
}

let packageJson: PackageJson;
try {
packageJson = JSON.parse(packageJsonString) as PackageJson;
} catch (e) {
logger.error(`Could not parse package.json at ${filePath}`);
return new Set();
}

return (
[
"dependencies",
"devDependencies",
"peerDependencies",
// intentionally not including `optionalDependencies` or `bundleDependencies` because at the time of writing they are not used for any of the frameworks we support
] as const
)
.flatMap((key) => Object.keys(packageJson[key] ?? {}))
.reduce((acc, dependency) => acc.add(dependency), new Set<string>());
};
Expand Down

0 comments on commit 6a38073

Please sign in to comment.