Skip to content
Merged
Show file tree
Hide file tree
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
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ Relative paths are resolved from the current working directory.
| `--strict` | Fail on extra keys as well as missing or empty keys |
| `--json` | Print JSON instead of the human-readable report |
| `--github` | Print GitHub Actions annotations instead of the human-readable report; cannot be combined with `--json` |
| `--duplicates` | Also report keys that `.env` assigns more than once (warnings, errors with `--strict`) |
| `--help`, `-h` | Show usage and exit successfully |
| `--version`, `-v` | Show the package version and exit successfully |
| `--allow-empty <KEY>` | Keys that may be empty; repeatable or comma-separated; `PREFIX*` matches by prefix |
Expand Down Expand Up @@ -200,6 +201,32 @@ Extra keys (warnings): D
When everything is fine, envguard prints
`Success: required environment keys are present and non-empty.` and exits 0.

### Duplicate keys

A key assigned twice in `.env` silently uses the last value. With `--duplicates`, envguard also lists such keys. With this `.env.example`:

```text
A=
```

and this `.env`:

```text
A=1
B=2
A=3
```

`envguard --duplicates` prints:

```text
Success: required environment keys are present and non-empty.
Extra keys (warnings): B
Duplicate keys (warnings): A
```

and exits 0; with `--strict` both lists are errors and the exit code is 1. Only assignments that envguard recognizes count, `export A=1` and `A=1` are the same key, and the template file is not checked. `--json` then adds a last field `"duplicate":["A"]` (always present with `--duplicates`, possibly empty); `--github` adds one line per key, `::warning file=.env,title=envguard::Duplicate key A (assigned more than once)` (`::error` with `--strict`). `--ignore-extra` does not affect duplicates. Without `--duplicates` nothing changes.

### GitHub Actions annotations

In a GitHub Actions job, `--github` makes each problem an annotation on the run and pull request. For example, with this `.env.example`:
Expand Down
8 changes: 6 additions & 2 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { resolve } from "node:path";
import { parseArgs } from "node:util";
import { compareEnv } from "./compare";
import { createReport, formatGithub, formatHuman, formatJson } from "./format";
import { parseEnv } from "./parse";
import { findDuplicateKeys, parseEnv } from "./parse";

const help = `Usage: envguard [options]

Expand All @@ -16,6 +16,7 @@ Options:
--strict Treat extra keys as errors rather than warnings
--allow-empty <KEY> Keys allowed to be empty; repeatable, comma-separated, KEY or PREFIX*
--ignore-extra <KEY> Extra keys to leave out of the report; repeatable, comma-separated, KEY or PREFIX*
--duplicates Report keys assigned more than once in the env file
--json Print one JSON report
--github Print GitHub Actions annotations (::error and ::warning lines)
--help, -h Show this help
Expand Down Expand Up @@ -49,6 +50,7 @@ function main(): number {
"ignore-extra": { type: "string", multiple: true },
json: { type: "boolean", default: false },
github: { type: "boolean", default: false },
duplicates: { type: "boolean", default: false },
help: { type: "boolean", short: "h" },
version: { type: "boolean", short: "v" },
},
Expand Down Expand Up @@ -78,13 +80,15 @@ function main(): number {

const envPath = resolve(values.env);
const examplePath = resolve(values.example);
const env = parseEnv(readFileSync(envPath, "utf8"));
const envText = readFileSync(envPath, "utf8");
const env = parseEnv(envText);
const example = parseEnv(readFileSync(examplePath, "utf8"));
const report = createReport(
compareEnv(env, example, allowEmpty, ignoreExtra),
envPath,
examplePath,
values.strict,
values.duplicates ? findDuplicateKeys(envText) : undefined,
);
const output = values.github
? formatGithub(report, values.env, values.example)
Expand Down
18 changes: 17 additions & 1 deletion src/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export interface Report extends Comparison {
strict: boolean;
env: string;
example: string;
duplicate?: string[];
}

/** Copy and sort the lists so report creation never mutates its input. */
Expand All @@ -13,16 +14,22 @@ export function createReport(
env: string,
example: string,
strict = false,
duplicate?: readonly string[],
): Report {
const { missing, extra, empty } = comparison;
const duplicateKeys = duplicate === undefined ? undefined : [...duplicate].sort();
return {
ok: missing.length === 0 && empty.length === 0 && (!strict || extra.length === 0),
ok:
missing.length === 0 &&
empty.length === 0 &&
(!strict || (extra.length === 0 && (duplicateKeys?.length ?? 0) === 0)),
strict,
env,
example,
missing: [...missing].sort(),
extra: [...extra].sort(),
empty: [...empty].sort(),
...(duplicateKeys === undefined ? {} : { duplicate: duplicateKeys }),
};
}

Expand Down Expand Up @@ -59,6 +66,10 @@ export function formatGithub(report: Report, envPath: string, examplePath: strin
(key) =>
`::${report.strict ? "error" : "warning"} file=${file},title=envguard::Extra key ${key} (not in ${escapedExample})`,
),
...(report.duplicate ?? []).map(
(key) =>
`::${report.strict ? "error" : "warning"} file=${file},title=envguard::Duplicate key ${key} (assigned more than once)`,
),
];
return lines.join("\n");
}
Expand All @@ -79,5 +90,10 @@ export function formatHuman(report: Report): string {
if (report.extra.length > 0) {
lines.push(`Extra keys (${report.strict ? "errors" : "warnings"}): ${report.extra.join(", ")}`);
}
if (report.duplicate && report.duplicate.length > 0) {
lines.push(
`Duplicate keys (${report.strict ? "errors" : "warnings"}): ${report.duplicate.join(", ")}`,
);
}
return lines.join("\n");
}
25 changes: 22 additions & 3 deletions src/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,35 @@
export function parseEnv(text: string): Map<string, string> {
const entries = new Map<string, string>();

for (const assignment of parseAssignments(text)) {
entries.set(assignment.key, assignment.value);
}

return entries;
}

export function findDuplicateKeys(text: string): string[] {
const counts = new Map<string, number>();

for (const assignment of parseAssignments(text)) {
counts.set(assignment.key, (counts.get(assignment.key) ?? 0) + 1);
}

return [...counts]
.filter(([, count]) => count > 1)
.map(([key]) => key)
.sort();
}

function* parseAssignments(text: string): Generator<{ key: string; value: string }> {
for (const line of text.replace(/^\uFEFF/, "").split(/\r?\n/)) {
const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_.]*)\s*=(.*)$/.exec(line);
if (!match) continue;

const [, key, raw] = match;
const value = parseValue(raw);
if (value !== undefined) entries.set(key, value);
if (value !== undefined) yield { key, value };
}

return entries;
}

function parseValue(raw: string): string | undefined {
Expand Down
Loading
Loading