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
31 changes: 30 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ Relative paths are resolved from the current working directory.
| `--example <path>` | Template file; defaults to `.env.example` |
| `--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` |
| `--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 @@ -199,6 +200,34 @@ Extra keys (warnings): D
When everything is fine, envguard prints
`Success: required environment keys are present and non-empty.` and exits 0.

### 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`:

```text
A=
B=
C=
```

and this `.env`:

```text
A=1
C=
CI=true
```

`envguard --github` prints (exit 1):

```text
::error file=.env,title=envguard::Missing key B (required by .env.example)
::error file=.env,title=envguard::Empty value for key C
::warning file=.env,title=envguard::Extra key CI (not in .env.example)
```

Missing and empty keys are errors; extra keys are warnings, or errors with `--strict`. Annotation paths are exactly the paths given on the command line. Nothing is printed when there is nothing to report. `--json` and `--github` cannot be combined (exit 2).

### Exit codes

| Code | Meaning |
Expand All @@ -208,7 +237,7 @@ When everything is fine, envguard prints
| 2 | Usage or file IO error |

Unknown options, missing option values, positional arguments and unreadable
files produce a message on stderr and no stdout, including with `--json`.
files produce a message on stderr and no stdout, including with `--json` and `--github`.

### Parsing and limits

Expand Down
20 changes: 17 additions & 3 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { parseArgs } from "node:util";
import { compareEnv } from "./compare";
import { createReport, formatHuman, formatJson } from "./format";
import { createReport, formatGithub, formatHuman, formatJson } from "./format";
import { parseEnv } from "./parse";

const help = `Usage: envguard [options]
Expand All @@ -17,6 +17,7 @@ Options:
--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*
--json Print one JSON report
--github Print GitHub Actions annotations (::error and ::warning lines)
--help, -h Show this help
--version, -v Show the package version

Expand Down Expand Up @@ -47,6 +48,7 @@ function main(): number {
"allow-empty": { type: "string", multiple: true },
"ignore-extra": { type: "string", multiple: true },
json: { type: "boolean", default: false },
github: { type: "boolean", default: false },
help: { type: "boolean", short: "h" },
version: { type: "boolean", short: "v" },
},
Expand All @@ -55,6 +57,10 @@ function main(): number {
const allowEmpty = parseKeyList(values["allow-empty"], "allow-empty");
const ignoreExtra = parseKeyList(values["ignore-extra"], "ignore-extra");

if (values.json && values.github) {
throw new Error("--json and --github cannot be used together");
}

if (values.help) {
process.stdout.write(help);
return 0;
Expand All @@ -80,8 +86,16 @@ function main(): number {
examplePath,
values.strict,
);
const output = values.json ? formatJson(report) : formatHuman(report);
process.stdout.write(`${output}\n`);
const output = values.github
? formatGithub(report, values.env, values.example)
: values.json
? formatJson(report)
: formatHuman(report);
if (values.github) {
if (output !== "") process.stdout.write(`${output}\n`);
} else {
process.stdout.write(`${output}\n`);
}
return report.ok ? 0 : 1;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
Expand Down
33 changes: 33 additions & 0 deletions src/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,39 @@ export function formatJson(report: Report): string {
return JSON.stringify(report);
}

function escapeMessage(value: string): string {
return value.replace(/[%\r\n]/g, (character) => {
if (character === "%") return "%25";
return character === "\r" ? "%0D" : "%0A";
});
}

function escapeFile(value: string): string {
return value.replace(/[%\r\n:,]/g, (character) => {
if (character === "%") return "%25";
if (character === "\r") return "%0D";
if (character === "\n") return "%0A";
return character === ":" ? "%3A" : "%2C";
});
}

export function formatGithub(report: Report, envPath: string, examplePath: string): string {
const file = escapeFile(envPath);
const escapedExample = escapeMessage(examplePath);
const lines = [
...report.missing.map(
(key) =>
`::error file=${file},title=envguard::Missing key ${key} (required by ${escapedExample})`,
),
...report.empty.map((key) => `::error file=${file},title=envguard::Empty value for key ${key}`),
...report.extra.map(
(key) =>
`::${report.strict ? "error" : "warning"} file=${file},title=envguard::Extra key ${key} (not in ${escapedExample})`,
),
];
return lines.join("\n");
}

/** Reports expose key names, never environment values. */
export function formatHuman(report: Report): string {
const lines = [
Expand Down
1 change: 1 addition & 0 deletions tests/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ describe("CLI", () => {
"--strict",
"--allow-empty <KEY> Keys allowed to be empty; repeatable, comma-separated, KEY or PREFIX*",
"--json",
"--github",
"--help",
"--version",
]) {
Expand Down
240 changes: 240 additions & 0 deletions tests/github.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,240 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { spawnSync } from "node:child_process";
import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { createReport, formatGithub } from "../src/format";

const cliPath = fileURLToPath(new URL("../src/cli.ts", import.meta.url));
const readmePath = new URL("../README.md", import.meta.url);

describe("GitHub annotations", () => {
let directory: string;

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

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

function writeDefaults(env: string, example: string): void {
writeFileSync(join(directory, ".env"), env, "utf8");
writeFileSync(join(directory, ".env.example"), example, "utf8");
}

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

test("formats sorted missing, empty, and extra annotations without a trailing LF", () => {
const report = createReport(
{
missing: ["Z_MISSING", "A_MISSING"],
empty: ["Z_EMPTY", "A_EMPTY"],
extra: ["Z_EXTRA", "A_EXTRA"],
},
".env",
".env.example",
);

expect(formatGithub(report, ".env", ".env.example")).toBe(
[
"::error file=.env,title=envguard::Missing key A_MISSING (required by .env.example)",
"::error file=.env,title=envguard::Missing key Z_MISSING (required by .env.example)",
"::error file=.env,title=envguard::Empty value for key A_EMPTY",
"::error file=.env,title=envguard::Empty value for key Z_EMPTY",
"::warning file=.env,title=envguard::Extra key A_EXTRA (not in .env.example)",
"::warning file=.env,title=envguard::Extra key Z_EXTRA (not in .env.example)",
].join("\n"),
);
expect(
formatGithub(
createReport({ missing: [], empty: [], extra: [] }, ".env", ".env.example"),
".env",
".env.example",
),
).toBe("");
});

test("prints the three annotation categories in order and never prints values", () => {
writeDefaults("A=1\nC=\nCI=true\nSECRET=hunter2\n", "A=\nB=\nC=\nSECRET=\n");

const result = runCli(["--github"]);

expect(result.status).toBe(1);
expect(result.stderr).toBe("");
expect(result.stdout).toBe(
[
"::error file=.env,title=envguard::Missing key B (required by .env.example)",
"::error file=.env,title=envguard::Empty value for key C",
"::warning file=.env,title=envguard::Extra key CI (not in .env.example)",
"",
].join("\n"),
);
expect(result.stdout).not.toContain("hunter2");
expect(result.stdout).not.toContain("\u001b");
});

test("uses errors for strict extras and warnings alone still exit successfully", () => {
writeDefaults("A=1\nEXTRA=2\n", "A=\n");
const warning = runCli(["--github"]);

expect(warning.status).toBe(0);
expect(warning.stderr).toBe("");
expect(warning.stdout).toBe(
"::warning file=.env,title=envguard::Extra key EXTRA (not in .env.example)\n",
);

const strict = runCli(["--github", "--strict"]);
expect(strict.status).toBe(1);
expect(strict.stderr).toBe("");
expect(strict.stdout).toBe(
"::error file=.env,title=envguard::Extra key EXTRA (not in .env.example)\n",
);
});

test("writes nothing for clean and ignored-extra reports", () => {
writeDefaults("A=1\n", "A=\n");
const clean = runCli(["--github"]);
expect(clean.status).toBe(0);
expect(clean.stderr).toBe("");
expect(clean.stdout).toBe("");

writeDefaults("A=1\nCI=true\n", "A=\n");
const ignored = runCli(["--github", "--ignore-extra", "CI"]);
expect(ignored.status).toBe(0);
expect(ignored.stderr).toBe("");
expect(ignored.stdout).toBe("");
});

test("--allow-empty keys are not annotated", () => {
writeDefaults("A=\n", "A=required\n");

const result = runCli(["--github", "--allow-empty", "A"]);

expect(result.status).toBe(0);
expect(result.stderr).toBe("");
expect(result.stdout).toBe("");
});

test("escapes comma and percent in the command-line paths without resolving them", () => {
const envPath = join("a,b", "local.env");
const examplePath = "100%.example";
mkdirSync(join(directory, "a,b"));
writeFileSync(join(directory, envPath), "", "utf8");
writeFileSync(join(directory, examplePath), "MISSING=required\n", "utf8");

const result = runCli(["--github", "--env", envPath, "--example", examplePath]);
const escapedEnvPath = envPath.replace(",", "%2C");

expect(result.status).toBe(1);
expect(result.stderr).toBe("");
expect(result.stdout).toBe(
`::error file=${escapedEnvPath},title=envguard::Missing key MISSING (required by 100%25.example)\n`,
);
});

test("escapes all workflow-command characters in file paths and message paths", () => {
const report = createReport(
{ missing: ["MISSING"], empty: [], extra: [] },
".env",
".env.example",
);

expect(formatGithub(report, "C:\\a,b%c\r\nlocal.env", "100%\r\n.example")).toBe(
"::error file=C%3A\\a%2Cb%25c%0D%0Alocal.env,title=envguard::Missing key MISSING (required by 100%25%0D%0A.example)",
);
});

test("rejects --json and --github in either order, including before help", () => {
for (const args of [
["--json", "--github"],
["--github", "--json"],
["--json", "--github", "--help"],
["--github", "--json", "--help"],
]) {
const result = runCli(args);
expect(result.status).toBe(2);
expect(result.stdout).toBe("");
expect(result.stderr).toBe("envguard: --json and --github cannot be used together\n");
}
});

test("validates --ignore-extra values before the --json and --github conflict", () => {
const result = runCli(["--json", "--github", "--ignore-extra", "bad key"]);

expect(result.status).toBe(2);
expect(result.stdout).toBe("");
expect(result.stderr).toBe(
"envguard: --ignore-extra needs a key name or a prefix ending in *\n",
);
});

test("file and argument errors with --github leave stdout empty", () => {
writeDefaults("A=1\n", "A=\n");
rmSync(join(directory, ".env"));
const missingFile = runCli(["--github"]);

expect(missingFile.status).toBe(2);
expect(missingFile.stdout).toBe("");
expect(missingFile.stderr).toMatch(/^envguard: /);

const unknownWithoutGithub = runCli(["--unknown"]);
const unknownWithGithub = runCli(["--github", "--unknown"]);
expect(unknownWithGithub.status).toBe(2);
expect(unknownWithGithub.stdout).toBe("");
expect(unknownWithGithub.stderr).toBe(unknownWithoutGithub.stderr);

const positionalWithoutGithub = runCli(["positional.env"]);
const positionalWithGithub = runCli(["positional.env", "--github"]);
expect(positionalWithGithub.status).toBe(2);
expect(positionalWithGithub.stdout).toBe("");
expect(positionalWithGithub.stderr).toBe(positionalWithoutGithub.stderr);
});

test("--github=1 is rejected as an invalid boolean option value", () => {
const result = runCli(["--github=1"]);

expect(result.status).toBe(2);
expect(result.stdout).toBe("");
expect(result.stderr).toMatch(/^envguard: .*github/i);
});

test("--github works with help and includes its description", () => {
const result = runCli(["--github", "--help"]);

expect(result.status).toBe(0);
expect(result.stderr).toBe("");
expect(result.stdout).toContain(
" --github Print GitHub Actions annotations (::error and ::warning lines)",
);
});

test("README documents the option and its exact annotation example in a text block", () => {
const readme = readFileSync(readmePath, "utf8");
const expectedLines = [
"::error file=.env,title=envguard::Missing key B (required by .env.example)",
"::error file=.env,title=envguard::Empty value for key C",
"::warning file=.env,title=envguard::Extra key CI (not in .env.example)",
];
const textBlocks = [...readme.matchAll(/```text\r?\n([\s\S]*?)\r?\n```/g)].map(
(match) => match[1],
);

expect(readme).toContain("| `--github` |");
expect(textBlocks.some((block) => block.includes(expectedLines.join("\n")))).toBe(true);
});
});
Loading