Skip to content

Commit

Permalink
Fixup handling mismatched braches
Browse files Browse the repository at this point in the history
  • Loading branch information
pbrisbin committed Feb 14, 2024
1 parent 351cf7f commit 997ba69
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
19 changes: 17 additions & 2 deletions src/envsubst.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,25 @@ describe("envsubst", () => {
});

test("unknown variables are replaced by whitespace", () => {
expect(envsubst("Home is $XNOPE.")).toEqual(`Home is .`);
expect(envsubst("Home is $XNOPE.")).toEqual("Home is .");
});

test("unknown variables with braces are replaced by whitespace", () => {
expect(envsubst("Home is ${XNOPE}.")).toEqual(`Home is .`);
expect(envsubst("Home is ${XNOPE}.")).toEqual("Home is .");
});

test("invalid braces are not replaced", () => {
expect(envsubst("Home is ${ HOME}.")).toEqual("Home is ${ HOME}.");
expect(envsubst("Home is ${HOME }.")).toEqual("Home is ${HOME }.");
});

test("mismatched left brace is not replaced", () => {
expect(envsubst("Home is ${HOME.")).toEqual("Home is ${HOME.");
});

test("mismatched right brace is replaced before the brace", () => {
expect(envsubst("Home is $HOME}.")).toEqual(
`Home is ${process.env.HOME}}.`,
);
});
});
10 changes: 5 additions & 5 deletions src/envsubst.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
const REGEXP = new RegExp("\\$\\{?([A-Z_]+)\\}?");
const REGEXP = new RegExp("\\$([A-Z_]+)|\\$\\{([A-Z_]+)\\}");

function replacer(_match: string, p1: string, p2: string): string {
return process.env[p2 ?? p1] ?? "";
}

/* replace environment variables in an input string, like envsubst(1) */
export function envsubst(str: string): string {
return str.replace(REGEXP, replacer);
}

function replacer(_match: string, k: string): string {
return process.env[k] ?? "";
}

0 comments on commit 997ba69

Please sign in to comment.