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

docs(dotenv): improve dotenv docs #5095

Merged
merged 2 commits into from
Jun 21, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions _tools/check_docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const ENTRY_POINTS = [
"../csv/mod.ts",
"../data_structures/mod.ts",
"../datetime/mod.ts",
"../dotenv/mod.ts",
"../encoding/mod.ts",
"../expect/mod.ts",
"../fmt/bytes.ts",
Expand Down
116 changes: 98 additions & 18 deletions dotenv/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,19 @@
* Parses and loads environment variables from a `.env` file into the current
* process, or stringify data into a `.env` file format.
*
* ```ts no-eval
* // Automatically load environment variables from a `.env` file
* import "@std/dotenv/load";
* ```
*
* ```ts
* import { parse, stringify } from "@std/dotenv";
* import { assertEquals } from "@std/assert/assert-equals";
*
* assertEquals(parse("GREETING=hello world"), { GREETING: "hello world" });
* assertEquals(stringify({ GREETING: "hello world" }), "GREETING='hello world'");
* ```
*
* @module
*/

Expand Down Expand Up @@ -62,16 +75,29 @@ export interface LoadOptions {
defaultsPath?: string | null;
}

/** Works identically to {@linkcode load}, but synchronously. */
/**
* Works identically to {@linkcode load}, but synchronously.
*
* @example Usage
* ```ts no-eval
* import { loadSync } from "@std/dotenv";
*
* const conf = loadSync();
* ```
*
* @param options Options for loading the environment variables.
* @returns The parsed environment variables.
*/
export function loadSync(
{
options: LoadOptions = {},
): Record<string, string> {
const {
envPath = ".env",
examplePath = ".env.example",
defaultsPath = ".env.defaults",
export: _export = false,
allowEmptyValues = false,
}: LoadOptions = {},
): Record<string, string> {
} = options;
const conf = envPath ? parseFileSync(envPath) : {};

if (defaultsPath) {
Expand Down Expand Up @@ -114,11 +140,12 @@ export function loadSync(
*
* Then import the environment variables using the `load` function.
*
* ```ts
* @example Basic usage
* ```ts no-eval
* // app.ts
* import { load } from "@std/dotenv";
*
* console.log(await load({export: true})); // { GREETING: "hello world" }
* console.log(await load({ export: true })); // { GREETING: "hello world" }
* console.log(Deno.env.get("GREETING")); // hello world
* ```
*
Expand All @@ -131,7 +158,8 @@ export function loadSync(
* Import the `load.ts` module to auto-import from the `.env` file and into
* the process environment.
*
* ```ts
* @example Auto-loading
* ```ts no-eval
* // app.ts
* import "@std/dotenv/load";
*
Expand Down Expand Up @@ -209,15 +237,17 @@ export function loadSync(
* |allowEmptyValues|false|Allows empty values for specified env variables (throws otherwise)
*
* ### Example configuration
* ```ts
*
* @example Using with options
* ```ts no-eval
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a brief description explaining what this snippet is doing?

* import { load } from "@std/dotenv";
*
* const conf = await load({
* envPath: "./.env_prod",
* examplePath: "./.env_required",
* export: true,
* allowEmptyValues: true,
* });
* envPath: "./.env_prod",
* examplePath: "./.env_required",
* export: true,
* allowEmptyValues: true,
* });
* ```
*
* ## Permissions
Expand Down Expand Up @@ -269,16 +299,20 @@ export function loadSync(
* `{ KEY: "default" }`. Also there is possible to do this case
* `KEY=${NO_SUCH_KEY:-${EXISTING_KEY:-default}}` which becomes
* `{ KEY: "<EXISTING_KEY_VALUE_FROM_ENV>" }`)
*
* @param options The options
* @returns The parsed environment variables
*/
export async function load(
{
options: LoadOptions = {},
): Promise<Record<string, string>> {
iuioiua marked this conversation as resolved.
Show resolved Hide resolved
const {
envPath = ".env",
examplePath = ".env.example",
defaultsPath = ".env.defaults",
export: _export = false,
allowEmptyValues = false,
}: LoadOptions = {},
): Promise<Record<string, string>> {
} = options;
const conf = envPath ? await parseFile(envPath) : {};

if (defaultsPath) {
Expand Down Expand Up @@ -370,11 +404,57 @@ function assertSafe(
/**
* Error thrown in {@linkcode load} and {@linkcode loadSync} when required
* environment variables are missing.
*
* @example Usage
* ```ts no-eval
* import { MissingEnvVarsError, load } from "@std/dotenv";
*
* try {
* await load();
* } catch (e) {
* if (e instanceof MissingEnvVarsError) {
* console.error(e.message);
* }
* }
* ```
*/
export class MissingEnvVarsError extends Error {
/** The keys of the missing environment variables. */
/**
* The keys of the missing environment variables.
*
* @example Usage
* ```ts no-eval
* import { MissingEnvVarsError, load } from "@std/dotenv";
*
* try {
* await load();
* } catch (e) {
* if (e instanceof MissingEnvVarsError) {
* console.error(e.missing);
* }
* }
* ```
*/
missing: string[];
/** Constructs a new instance. */
/**
* Constructs a new instance.
*
* @example Usage
* ```ts no-eval
* import { MissingEnvVarsError, load } from "@std/dotenv";
*
* try {
* await load();
* } catch (e) {
* if (e instanceof MissingEnvVarsError) {
* console.error(e.message);
* }
* }
* ```
*
* @param message The error message
* @param missing The keys of the missing environment variables
*/
constructor(message: string, missing: string[]) {
super(message);
this.name = "MissingEnvVarsError";
Expand Down
12 changes: 8 additions & 4 deletions dotenv/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,21 +57,25 @@ function expand(str: string, variablesMap: { [key: string]: string }): string {
/**
* Parse `.env` file output in an object.
*
* @example
* @example Usage
* ```ts
* import { parse } from "@std/dotenv/parse";
* import { assertEquals } from "@std/assert/assert-equals";
*
* const env = parse("GREETING=hello world");
* env.GREETING; // "hello world"
* assertEquals(env, { GREETING: "hello world" });
* ```
*
* @param text The text to parse.
* @returns The parsed object.
*/
export function parse(rawDotenv: string): Record<string, string> {
export function parse(text: string): Record<string, string> {
const env: Record<string, string> = {};

let match;
const keysForExpandCheck = [];

while ((match = RE_KEY_VALUE.exec(rawDotenv)) !== null) {
while ((match = RE_KEY_VALUE.exec(text)) !== null) {
const { key, interpolated, notInterpolated, unquoted } = match
?.groups as LineParseResult;

Expand Down
5 changes: 3 additions & 2 deletions dotenv/stringify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@
/**
* Stringify an object into a valid `.env` file format.
*
* @example
* @example Usage
* ```ts
* import { stringify } from "@std/dotenv/stringify";
* import { assertEquals } from "@std/assert/assert-equals";
*
* const object = { GREETING: "hello world" };
* const string = stringify(object); // GREETING='hello world'
* assertEquals(stringify(object), "GREETING='hello world'");
* ```
*
* @param object object to be stringified
Expand Down
Loading