A very minimal `.env` parser for Deno.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

48 lines
1.6 KiB

  1. /**
  2. * Parses a `.env` file and sets the found key-value pairs in the current
  3. * environment.
  4. * @param filename An optional file name to use instead of `.env`.
  5. */
  6. export default async function minimal_dotenv(filename = ".env"): Promise<void> {
  7. // Request permission to read the .env file.
  8. const readPermission = await Deno.permissions.request({
  9. name: "read",
  10. path: filename,
  11. });
  12. if (readPermission.state !== "granted") {
  13. throw new Error(
  14. "Read permission not granted (use --allow-read to skip the prompt)",
  15. );
  16. }
  17. // Request permission to access the environment.
  18. const envPermission = await Deno.permissions.request({ name: "env" });
  19. if (envPermission.state !== "granted") {
  20. throw new Error(
  21. "Environment permission not granted (use --allow-env to skip the prompt)",
  22. );
  23. }
  24. // Read and decode the .env file.
  25. const decoder = new TextDecoder("utf8");
  26. const contents = decoder.decode(await Deno.readFile(filename));
  27. // Split the contents by newline and only include non-zero length strings and
  28. // lines not starting with a #.
  29. const lines = contents
  30. .split(/[\r\n]+/)
  31. .filter((line) => line.length > 0 && !line.startsWith("#"));
  32. for (const line of lines) {
  33. const matches = /^(?<key>[A-Z0-9_]+)="(?<value>.+)"$/.exec(line);
  34. if (matches === null) {
  35. throw new Error(`${line} does not match the expected format`);
  36. }
  37. // The `?? {}` is to make the compiler happy, if the regex matches then we
  38. // know the capture groups will too.
  39. const { key, value } = matches.groups ?? {};
  40. Deno.env.set(key, value);
  41. }
  42. }