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
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ Relative paths are resolved from the current working directory.
| `--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` |
| `--quiet`, `-q` | Leave out the success line of the human report; problems and warnings are printed as usual |
| `--summary` | Add a last line to the human report with the number of missing, empty and extra keys (and duplicate keys with `--duplicates`); cannot be combined with `--json` or `--github` |
| `--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 |
Expand Down Expand Up @@ -204,6 +205,10 @@ When everything is fine, envguard prints

With `--quiet` (or `-q`) that success line is left out, so a clean run prints nothing and exits 0; warnings such as extra keys and every error report are printed exactly as before. In a shell script this reads as `envguard -q || echo "fix your .env"`. `--quiet` has no effect on `--github`, which already prints nothing for a clean run, and it cannot be combined with `--json` (exit 2, message on stderr).

### Summary line

With `--summary`, the human report gets one more last line, `Summary: 1 missing, 1 empty, 2 extra`, which counts the keys of the three lists as the report shows them (after `--allow-empty` and `--ignore-extra`). With `--duplicates` the line ends with `, 1 duplicate`. The line is also printed when the check passes (`Summary: 0 missing, 0 empty, 0 extra`), and `--quiet` leaves out only the success line, not the summary. `--summary` cannot be combined with `--json` or `--github`: the error is `envguard: --summary and --json cannot be used together` (or `--github`), exit 2.

### Duplicate keys

A key assigned twice in `.env` silently uses the last value. With `--duplicates`, envguard also lists such keys. With this `.env.example`:
Expand Down
10 changes: 9 additions & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Options:
--json Print one JSON report
--github Print GitHub Actions annotations (::error and ::warning lines)
--quiet, -q Leave out the success line of the human report
--summary Add a last line with the number of missing, empty and extra keys
--help, -h Show this help
--version, -v Show the package version

Expand Down Expand Up @@ -52,6 +53,7 @@ function main(): number {
json: { type: "boolean", default: false },
github: { type: "boolean", default: false },
quiet: { type: "boolean", short: "q", default: false },
summary: { type: "boolean", default: false },
duplicates: { type: "boolean", default: false },
help: { type: "boolean", short: "h" },
version: { type: "boolean", short: "v" },
Expand All @@ -67,6 +69,12 @@ function main(): number {
if (values.json && values.quiet) {
throw new Error("--json and --quiet cannot be used together");
}
if (values.summary && values.json) {
throw new Error("--summary and --json cannot be used together");
}
if (values.summary && values.github) {
throw new Error("--summary and --github cannot be used together");
}

if (values.help) {
process.stdout.write(help);
Expand Down Expand Up @@ -99,7 +107,7 @@ function main(): number {
? formatGithub(report, values.env, values.example)
: values.json
? formatJson(report)
: formatHuman(report, values.quiet);
: formatHuman(report, values.quiet, values.summary);
if (output !== "") process.stdout.write(`${output}\n`);
return report.ok ? 0 : 1;
} catch (error) {
Expand Down
14 changes: 13 additions & 1 deletion src/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,19 @@ export function formatGithub(report: Report, envPath: string, examplePath: strin
return lines.join("\n");
}

/** One line with the size of each list; the duplicate count appears only when duplicates were checked. */
export function formatSummary(report: Report): string {
const counts = [
`${report.missing.length} missing`,
`${report.empty.length} empty`,
`${report.extra.length} extra`,
];
if (report.duplicate !== undefined) counts.push(`${report.duplicate.length} duplicate`);
return `Summary: ${counts.join(", ")}`;
}

/** Reports expose key names, never environment values. */
export function formatHuman(report: Report, quiet = false): string {
export function formatHuman(report: Report, quiet = false, summary = false): string {
const lines = [
report.ok
? "Success: required environment keys are present and non-empty."
Expand All @@ -96,5 +107,6 @@ export function formatHuman(report: Report, quiet = false): string {
`Duplicate keys (${report.strict ? "errors" : "warnings"}): ${report.duplicate.join(", ")}`,
);
}
if (summary) lines.push(formatSummary(report));
return lines.join("\n");
}
145 changes: 145 additions & 0 deletions tests/summary.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { spawnSync } from "node:child_process";
import { mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { createReport, formatHuman, formatSummary } from "../src/format";

const cliPath = fileURLToPath(new URL("../src/cli.ts", import.meta.url));
const success = "Success: required environment keys are present and non-empty.";

describe("summary line", () => {
let directory: string;

beforeEach(() => {
directory = realpathSync(mkdtempSync(join(tmpdir(), "envguard-summary-")));
});

afterEach(() => {
rmSync(directory, { recursive: true, force: true });
});

function run(env: string, example: string, args: string[]) {
writeFileSync(join(directory, ".env"), env, "utf8");
writeFileSync(join(directory, ".env.example"), example, "utf8");
const result = spawnSync(process.execPath, ["run", cliPath, ...args], {
cwd: directory,
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
timeout: 30_000,
maxBuffer: 1024 * 1024,
});
expect(result.error).toBeUndefined();
expect(result.signal).toBeNull();
return { status: result.status, stdout: result.stdout, stderr: result.stderr };
}

const rows: [string, string, string, string[], number, string][] = [
[
"a passing check gets the success line and the summary",
"A=1\n",
"A=\n",
["--summary"],
0,
`${success}\nSummary: 0 missing, 0 empty, 0 extra\n`,
],
["without the flag nothing changes", "A=1\n", "A=\n", [], 0, `${success}\n`],
[
"every list is counted",
"A=1\nC=\nD=4\nE=5\n",
"A=\nB=\nC=\n",
["--summary"],
1,
"Environment problems found.\nMissing keys (errors): B\nEmpty values (errors): C\nExtra keys (warnings): D, E\nSummary: 1 missing, 1 empty, 2 extra\n",
],
[
"quiet leaves out only the success line",
"A=1\n",
"A=\n",
["--summary", "--quiet"],
0,
"Summary: 0 missing, 0 empty, 0 extra\n",
],
[
"ignored extra keys are not counted",
"A=1\nCI=true\nTZ=UTC\n",
"A=\n",
["--summary", "--ignore-extra", "CI*"],
0,
`${success}\nExtra keys (warnings): TZ\nSummary: 0 missing, 0 empty, 1 extra\n`,
],
[
"an allowed empty key is not counted",
"A=\n",
"A=\n",
["--summary", "--allow-empty", "A"],
0,
`${success}\nSummary: 0 missing, 0 empty, 0 extra\n`,
],
[
"duplicates add a fourth count",
"A=1\nA=2\n",
"A=\n",
["--summary", "--duplicates"],
0,
`${success}\nDuplicate keys (warnings): A\nSummary: 0 missing, 0 empty, 0 extra, 1 duplicate\n`,
],
[
"duplicates checked and none found count zero",
"A=1\n",
"A=\n",
["--duplicates", "--summary"],
0,
`${success}\nSummary: 0 missing, 0 empty, 0 extra, 0 duplicate\n`,
],
[
"strict mode keeps the counts and the exit code",
"A=1\nB=2\n",
"A=\n",
["--summary", "--strict"],
1,
"Environment problems found.\nExtra keys (errors): B\nSummary: 0 missing, 0 empty, 1 extra\n",
],
];

test.each(rows)("%s", (_name, env, example, args, status, stdout) => {
const result = run(env, example, args);
expect(result.stderr).toBe("");
expect(result.status).toBe(status);
expect(result.stdout).toBe(stdout);
});

test.each([
["--json", "--summary and --json cannot be used together"],
["--github", "--summary and --github cannot be used together"],
])("%s with --summary is a usage error", (flag, message) => {
const result = run("A=1\n", "A=\n", ["--summary", flag ?? ""]);
expect(result.status).toBe(2);
expect(result.stdout).toBe("");
expect(result.stderr).toBe(`envguard: ${message}\n`);
});

test("the summary never shows a value", () => {
const result = run("A=secret-one\nB=secret-two\n", "A=\n", ["--summary"]);
expect(result.stdout).not.toContain("secret");
});

test("formatSummary counts the lists of a report", () => {
const report = createReport({ missing: ["B"], extra: ["D", "E"], empty: [] }, "e", "x");
expect(formatSummary(report)).toBe("Summary: 1 missing, 0 empty, 2 extra");
const checked = createReport({ missing: [], extra: [], empty: [] }, "e", "x", false, ["A"]);
expect(formatSummary(checked)).toBe("Summary: 0 missing, 0 empty, 0 extra, 1 duplicate");
});

test("formatHuman adds the summary last and only when asked", () => {
const report = createReport({ missing: [], extra: ["B"], empty: [] }, "e", "x");
expect(formatHuman(report, false, true)).toBe(
`${success}\nExtra keys (warnings): B\nSummary: 0 missing, 0 empty, 1 extra`,
);
expect(formatHuman(report)).toBe(`${success}\nExtra keys (warnings): B`);
expect(formatHuman(report, true, true)).toBe(
"Extra keys (warnings): B\nSummary: 0 missing, 0 empty, 1 extra",
);
});
});
Loading