|
| 1 | +/** |
| 2 | + * refer: https://github.com/mysticatea/eslint-plugin-node/blob/f45c6149be7235c0f7422d1179c25726afeecd83/lib/util/get-package-json.js |
| 3 | + */ |
| 4 | + |
| 5 | +import fs from "fs" |
| 6 | +import path from "path" |
| 7 | +import { createCache } from "./cache" |
| 8 | + |
| 9 | +type PackageJson = Record<string, any> & { filePath: string } |
| 10 | + |
| 11 | +const isRunOnBrowser = !fs.readFileSync |
| 12 | +const cache = createCache<PackageJson | null>() |
| 13 | + |
| 14 | +/** |
| 15 | + * Reads the `package.json` data in a given path. |
| 16 | + * |
| 17 | + * Don't cache the data. |
| 18 | + * |
| 19 | + * @param dir The path to a directory to read. |
| 20 | + * @returns The read `package.json` data, or null. |
| 21 | + */ |
| 22 | +function readPackageJson(dir: string): PackageJson | null { |
| 23 | + if (isRunOnBrowser) return null |
| 24 | + const filePath = path.join(dir, "package.json") |
| 25 | + try { |
| 26 | + const text = fs.readFileSync(filePath, "utf8") |
| 27 | + const data = JSON.parse(text) |
| 28 | + |
| 29 | + if (typeof data === "object" && data !== null) { |
| 30 | + data.filePath = filePath |
| 31 | + return data |
| 32 | + } |
| 33 | + } catch (_err) { |
| 34 | + // do nothing. |
| 35 | + } |
| 36 | + |
| 37 | + return null |
| 38 | +} |
| 39 | + |
| 40 | +/** |
| 41 | + * Gets a `package.json` data. |
| 42 | + * The data is cached if found, then it's used after. |
| 43 | + * @param startPath A file path to lookup. |
| 44 | + * @returns A found `package.json` data or `null`. |
| 45 | + * This object have additional property `filePath`. |
| 46 | + */ |
| 47 | +export function getPackageJson(startPath = "a.js"): PackageJson | null { |
| 48 | + if (isRunOnBrowser) return null |
| 49 | + const startDir = path.dirname(path.resolve(startPath)) |
| 50 | + let dir = startDir |
| 51 | + let prevDir = "" |
| 52 | + let data = null |
| 53 | + |
| 54 | + do { |
| 55 | + data = cache.get(dir) |
| 56 | + if (data) { |
| 57 | + if (dir !== startDir) { |
| 58 | + cache.set(startDir, data) |
| 59 | + } |
| 60 | + return data |
| 61 | + } |
| 62 | + |
| 63 | + data = readPackageJson(dir) |
| 64 | + if (data) { |
| 65 | + cache.set(dir, data) |
| 66 | + cache.set(startDir, data) |
| 67 | + return data |
| 68 | + } |
| 69 | + |
| 70 | + // Go to next. |
| 71 | + prevDir = dir |
| 72 | + dir = path.resolve(dir, "..") |
| 73 | + } while (dir !== prevDir) |
| 74 | + |
| 75 | + cache.set(startDir, null) |
| 76 | + return null |
| 77 | +} |
0 commit comments