Skip to content
Merged
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
37 changes: 29 additions & 8 deletions packages/core/test/dotenv.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,24 @@ describe('dotenv', () => {
expect(content).toContain('KEY2=value2');
});

it('rewrites only the last duplicate assignment (dotenv last-wins)', () => {
// Windows CI seed 599909404: two identical `export W_=...` lines. The
// writer updates lastIndex only; an oracle that exempts only findIndex
// (the first hit) treats the rewritten last line as a non-surgical edit.
const paths = projectPaths(tmpDir);
writeFileSync(
paths.dotenv,
'export W_="value with spaces"\nexport W_="value with spaces"\n',
'utf8',
);

setDotenvValue(paths, 'W_', ' ', { allowUnsafe: true });

const content = readFileSync(paths.dotenv, 'utf8');
expect(content).toBe('export W_="value with spaces"\nexport W_=" "\n');
expect(readDotenv(paths).W_).toBe(' ');
});

it('preserves CRLF line endings', () => {
const paths = projectPaths(tmpDir);
writeFileSync(paths.dotenv, 'KEY=value\r\n', 'utf8');
Expand Down Expand Up @@ -354,9 +372,13 @@ describe('dotenv', () => {
// editor and trips no-irregular-whitespace. Stripping it matters — the
// oracle previously failed a correct surgical write on BOM'd files.
const assignmentRegex = /^\uFEFF?(?:export\s+)?([A-Z][A-Z0-9_]*)=/;
const originalAssignIdx = originalLines.findIndex((line) => {
// Last-wins writer rewrites the last matching assignment. Duplicate
// keys (legal in dotenv) must all be exempt from the identity check;
// findIndex only sees the first and fails Windows CI seed 599909404.
const rewritten = new Set<number>();
originalLines.forEach((line, i) => {
const match = assignmentRegex.exec(line);
return match?.[1] === key;
if (match?.[1] === key) rewritten.add(i);
});

// A surgical write may append but must never drop lines. Without this
Expand All @@ -370,12 +392,11 @@ describe('dotenv', () => {
}

for (let i = 0; i < originalLines.length; i++) {
if (i !== originalAssignIdx) {
if (originalLines[i] !== newLines[i]) {
throw new Error(
`Line ${i} mismatch:\nOriginal: ${JSON.stringify(originalLines[i])}\nNew: ${JSON.stringify(newLines[i])}`
);
}
if (rewritten.has(i)) continue;
if (originalLines[i] !== newLines[i]) {
throw new Error(
`Line ${i} mismatch:\nOriginal: ${JSON.stringify(originalLines[i])}\nNew: ${JSON.stringify(newLines[i])}`
);
}
}

Expand Down
Loading