Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stop find as soon as match is discovered #147

Merged
merged 2 commits into from
Apr 17, 2024
Merged
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
16 changes: 16 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ describe("Dotenv Mono", () => {
malformedWithEol: "TEST_MALFORMED_ENV\r\n",
defaults: "TEST_DEFAULT_ENV=1",
webTest: "TEST_WEB_ENV=1",
parent: "PARENT_ENV=1",
child: "CHILD_ENV=1",
};

beforeEach(() => {
Expand All @@ -35,6 +37,12 @@ describe("Dotenv Mono", () => {
},
},
},
"/parent": {
".env": mockEnv.parent,
"child": {
".env": mockEnv.child,
},
},
});
jest.spyOn(process, "cwd").mockReturnValue("/root/apps");
instance = new Dotenv({
Expand Down Expand Up @@ -124,6 +132,14 @@ describe("Dotenv Mono", () => {
expect(process.env).toEqual(expect.objectContaining(expected));
});

it("should prefer the nearer of two .env files with the same priority", () => {
jest.spyOn(process, "cwd").mockReturnValue("/parent/child");
expect(() => instance.load()).not.toThrow();
const expected = {"CHILD_ENV": "1"};
expect(instance.env).toEqual(expected);
expect(process.env).toEqual(expect.objectContaining(expected));
});

it("should load returns an empty output when none dotenv been found", () => {
jest.spyOn(process, "cwd").mockReturnValue("/empty");
instance.cwd = process.cwd();
Expand Down
9 changes: 4 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,7 @@ export class Dotenv {
})
: {
parsed: this.parse(plain),
ignoreProcessEnv: true,
processEnv: {},
};

if (this.expand) dotenvExpand.expand(config);
Expand Down Expand Up @@ -405,14 +405,13 @@ export class Dotenv {
let directory = path.resolve(this.cwd);
const {root} = path.parse(directory);
let depth = 0;
let match = false;
while (depth < this.depth) {
depth++;
const {foundPath, foundDotenv} = matcher(dotenv, directory);
dotenv = foundDotenv;
if (match) break;
if (foundPath) match = true;
if (directory === root) break;
if (foundPath || directory === root) {
break;
}
directory = path.dirname(directory);
}
return dotenv;
Expand Down
Loading