Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion packages/get-db/src/lib/utils/validate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,22 @@ describe("validateEnvPath", () => {
expect(validateEnvPath("env-local")).toBeUndefined();
});

it("returns undefined for valid relative paths", () => {
expect(validateEnvPath("./.env")).toBeUndefined();
expect(validateEnvPath("./.env.local")).toBeUndefined();
expect(validateEnvPath("./config/.env")).toBeUndefined();
expect(validateEnvPath("config/.env")).toBeUndefined();
expect(validateEnvPath("src/config/.env.local")).toBeUndefined();
});

it("returns undefined for empty string", () => {
expect(validateEnvPath("")).toBeUndefined();
});

it("returns error for invalid paths", () => {
expect(validateEnvPath(".env/local")).toBeInstanceOf(Error);
expect(validateEnvPath("../.env")).toBeInstanceOf(Error);
expect(validateEnvPath("/etc/.env")).toBeInstanceOf(Error);
expect(validateEnvPath(".env/")).toBeInstanceOf(Error);
expect(validateEnvPath("..env")).toBeInstanceOf(Error);
expect(validateEnvPath(".env..local")).toBeInstanceOf(Error);
});
Expand Down
10 changes: 7 additions & 3 deletions packages/get-db/src/lib/utils/validate.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
/**
* Validates the path to the .env file - it can be dotfile or not.
* Validates the path to the .env file - accepts filenames and relative paths.
* @param value - The path to the .env file
* @returns An error if the path is invalid, otherwise undefined
*/
function validateEnvPath(value: string) {
if (!value) return undefined;

if (!/^\.?[\w-]+(?:\.[\w-]+)*$/.test(value)) {
if (
!/^(?:\.\/)?(?:[\w-]+(?:\.[\w-]+)*\/)*\.?[\w-]+(?:\.[\w-]+)*$/.test(
value,
)
) {
return new Error(
"Please enter a valid file name (e.g.: .env or .env.local)",
"Please enter a valid file path (e.g.: .env, .env.local, or ./config/.env)",
);
}

Expand Down