From dd84b9d64fb98746a230cd24233ff50a562c39c9 Mon Sep 17 00:00:00 2001 From: 简律纯 Date: Fri, 28 Apr 2023 01:36:44 +0800 Subject: --- packages/turbo-utils/src/searchUp.ts | 44 ++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 packages/turbo-utils/src/searchUp.ts (limited to 'packages/turbo-utils/src/searchUp.ts') diff --git a/packages/turbo-utils/src/searchUp.ts b/packages/turbo-utils/src/searchUp.ts new file mode 100644 index 0000000..57f92e4 --- /dev/null +++ b/packages/turbo-utils/src/searchUp.ts @@ -0,0 +1,44 @@ +import fs from "fs"; +import path from "path"; + +function searchUp({ + target, + cwd, + contentCheck, +}: { + target: string; + cwd: string; + contentCheck?: (content: string) => boolean; +}): string | null { + const root = path.parse(cwd).root; + + let found = false; + while (!found && cwd !== root) { + if (contentCheck) { + try { + const content = fs.readFileSync(path.join(cwd, target)).toString(); + if (contentCheck(content)) { + found = true; + break; + } + } catch { + // keep looking + } + } else { + if (fs.existsSync(path.join(cwd, target))) { + found = true; + break; + } + } + + cwd = path.dirname(cwd); + } + + if (found) { + return cwd; + } + + return null; +} + +export default searchUp; -- cgit v1.2.3-70-g09d2