diff options
Diffstat (limited to 'packages/turbo-utils/src/searchUp.ts')
| -rw-r--r-- | packages/turbo-utils/src/searchUp.ts | 44 |
1 files changed, 44 insertions, 0 deletions
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; |
