Skip to content

Commit

Permalink
Merge pull request #147 from wlewis-formative/fix/146
Browse files Browse the repository at this point in the history
Stop `find` as soon as match is discovered
  • Loading branch information
marcocesarato authored Apr 17, 2024
2 parents de47d3f + 4352c61 commit e7a6670
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
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

0 comments on commit e7a6670

Please sign in to comment.