From a74c7fb36cbf4cae650e1e3bb0666eb7834710aa Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Wed, 20 Dec 2023 15:04:19 -0800 Subject: [PATCH] Pull findUp out of findHerebyfile, fixes a silly bug nobody should hit --- .changeset/nice-turkeys-wonder.md | 5 +++++ src/cli/loadHerebyfile.ts | 14 +++++++------- src/cli/utils.ts | 13 +++++++++++++ 3 files changed, 25 insertions(+), 7 deletions(-) create mode 100644 .changeset/nice-turkeys-wonder.md diff --git a/.changeset/nice-turkeys-wonder.md b/.changeset/nice-turkeys-wonder.md new file mode 100644 index 0000000..e323099 --- /dev/null +++ b/.changeset/nice-turkeys-wonder.md @@ -0,0 +1,5 @@ +--- +"hereby": patch +--- + +Fix the (unlikely) case of a Herebyfile at the FS root diff --git a/src/cli/loadHerebyfile.ts b/src/cli/loadHerebyfile.ts index c815ca7..6c4eb6a 100644 --- a/src/cli/loadHerebyfile.ts +++ b/src/cli/loadHerebyfile.ts @@ -5,14 +5,12 @@ import { pathToFileURL } from "node:url"; import pc from "picocolors"; import { Task } from "../index.js"; -import { UserError } from "./utils.js"; +import { findUp, UserError } from "./utils.js"; const herebyfileRegExp = /^herebyfile\.m?js$/i; export function findHerebyfile(dir: string): string { - const root = path.parse(dir).root; - - while (true) { + const result = findUp(dir, (dir) => { const entries = fs.readdirSync(dir); const matching = entries.filter((e) => herebyfileRegExp.test(e)); if (matching.length > 1) { @@ -27,11 +25,13 @@ export function findHerebyfile(dir: string): string { return candidate; } if (entries.includes("package.json")) { - break; // TODO: Is this actually desirable? What about monorepos? + return false; // TODO: Is this actually desirable? What about monorepos? } + return undefined; + }); - if (dir === root) break; - dir = path.dirname(dir); + if (result) { + return result; } throw new UserError("Unable to find Herebyfile."); diff --git a/src/cli/utils.ts b/src/cli/utils.ts index 5d73999..4454c43 100644 --- a/src/cli/utils.ts +++ b/src/cli/utils.ts @@ -25,6 +25,19 @@ export function simplifyPath(p: string) { return p; } +export function findUp(p: string, predicate: (dir: string) => T | undefined): T | undefined { + const root = path.parse(p).root; + + while (true) { + const result = predicate(p); + if (result !== undefined) return result; + if (p === root) break; + p = path.dirname(p); + } + + return undefined; +} + /** * UserError is a special error that, when caught in the CLI will be printed * as a message only, without stacktrace. Use this instead of process.exit.