Skip to content

Commit 6a38073

Browse files
committed
adds more error handling for file read and parsing
1 parent ce55b7d commit 6a38073

File tree

1 file changed

+26
-13
lines changed

1 file changed

+26
-13
lines changed

packages/eslint-plugin-turbo/lib/rules/no-undeclared-env-vars.ts

+26-13
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import path from "node:path";
22
import { readFileSync } from "node:fs";
33
import type { Rule } from "eslint";
44
import type { Node, MemberExpression } from "estree";
5-
import { logger, searchUp } from "@turbo/utils";
5+
import { type PackageJson, logger, searchUp } from "@turbo/utils";
66
import { frameworks } from "@turbo/types";
77
import { RULES } from "../constants";
88
import { Project, getWorkspaceFromFilePath } from "../utils/calculate-inputs";
@@ -80,18 +80,31 @@ function normalizeCwd(
8080
/** for a given `package.json` file path, this will compile a Set of that package's listed dependencies */
8181
const packageJsonDependencies = (filePath: string): Set<string> => {
8282
// get the contents of the package.json
83-
const packageJsonString = readFileSync(filePath, "utf-8");
84-
const packageJson = JSON.parse(packageJsonString) as Record<
85-
string,
86-
undefined | Record<string, string>
87-
>;
88-
89-
return [
90-
"dependencies",
91-
"devDependencies",
92-
"peerDependencies",
93-
// intentionally not including `optionalDependencies` or `bundleDependencies` because at the time of writing they are not used for any of the frameworks we support
94-
]
83+
let packageJsonString;
84+
85+
try {
86+
packageJsonString = readFileSync(filePath, "utf-8");
87+
} catch (e) {
88+
logger.error(`Could not read package.json at ${filePath}`);
89+
return new Set();
90+
}
91+
92+
let packageJson: PackageJson;
93+
try {
94+
packageJson = JSON.parse(packageJsonString) as PackageJson;
95+
} catch (e) {
96+
logger.error(`Could not parse package.json at ${filePath}`);
97+
return new Set();
98+
}
99+
100+
return (
101+
[
102+
"dependencies",
103+
"devDependencies",
104+
"peerDependencies",
105+
// intentionally not including `optionalDependencies` or `bundleDependencies` because at the time of writing they are not used for any of the frameworks we support
106+
] as const
107+
)
95108
.flatMap((key) => Object.keys(packageJson[key] ?? {}))
96109
.reduce((acc, dependency) => acc.add(dependency), new Set<string>());
97110
};

0 commit comments

Comments
 (0)