Skip to content

feat(cli) : add native and fallback .env support#3

Merged
DataDave-Dev merged 3 commits into
DataDave-Dev:mainfrom
YasserYG8:feat/env-file-support
Jul 11, 2026
Merged

feat(cli) : add native and fallback .env support#3
DataDave-Dev merged 3 commits into
DataDave-Dev:mainfrom
YasserYG8:feat/env-file-support

Conversation

@YasserYG8

@YasserYG8 YasserYG8 commented Jul 11, 2026

Copy link
Copy Markdown
Collaborator

Summary

This PR adds support for automatically loading local .env environment files when Modlane starts up. This removes the need for developers to manually run export or set commands in their terminal sessions to set their API keys.

What Was Added/Changed

  1. Automatic .env Loader (src/cli.ts):
    • Checks for a local .env file at startup.
    • Dynamically loads variables using Node's native process.loadEnvFile() (available in Node 20.12+).
    • Falls back to a clean, zero-dependency manual line parser for older Node 20 sub-versions.
  2. Gitignore Safety Check:
    • Verified .env files are already configured in .gitignore to ensure developer keys are never committed.
  3. Spec-first Documentation:
    • Created proposal.md and tasks.md under openspec/changes/P9-env-support/.

Testing

  • Added a new unit test file src/env.test.ts to verify the fallback parser against standard key-values, quotes, comments, and spacing patterns.
  • Ran local integration tests by starting the server and executing requests to OpenRouter using key files loaded from .env.

Verified that:

  • pnpm run typecheck passes with zero compiler errors.
  • pnpm run build succeeds.
  • pnpm test runs and passes all 21 tests.

Summary by CodeRabbit

  • New Features

    • The CLI now automatically loads API keys and other settings from a local .env file.
    • Supports quoted values, comments, blank lines, and compatible fallback behavior across Node.js versions.
    • Invalid .env entries generate a warning without preventing the CLI from starting.
  • Documentation

    • Added documentation and completion details for local .env file support.
  • Tests

    • Added coverage for standard, quoted, commented, and blank .env entries.

@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@DataDave-Dev, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 50 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: d4384709-e96b-4454-80fd-721551d1a85c

📥 Commits

Reviewing files that changed from the base of the PR and between 0bd22fc and 6d7e558.

📒 Files selected for processing (3)
  • src/cli.ts
  • src/env.test.ts
  • src/env.ts
📝 Walkthrough

Walkthrough

The CLI now loads a local .env file at startup through Node’s native loader or a fallback parser. Tests cover assignments, comments, blank lines, and quoted values, with supporting proposal, task, and ignore-rule updates.

Changes

Local environment support

Layer / File(s) Summary
Startup environment loading
.gitignore, openspec/changes/P9-env-support/*, src/cli.ts
The CLI checks for .env, loads it natively when supported, otherwise parses key-value lines, and reports loading failures with warnings.
Fallback parser validation
src/env.test.ts
Tests cover basic values, ignored comments and blank lines, and single- or double-quoted values.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant FileSystem
  participant ProcessEnv
  CLI->>FileSystem: Check for .env
  alt Native loader available
    CLI->>ProcessEnv: Call process.loadEnvFile()
  else Native loader unavailable
    CLI->>FileSystem: Read and parse .env
    CLI->>ProcessEnv: Assign parsed variables
  end
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: CLI support for loading .env files with native and fallback parsing.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@YasserYG8 YasserYG8 requested a review from DataDave-Dev July 11, 2026 14:34

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/cli.ts`:
- Around line 12-22: Update the fallback .env parsing loop in cli.ts to strip
inline # comments from unquoted values, matching process.loadEnvFile() while
preserving # characters inside quoted values. Apply this before assigning the
parsed value to process.env[key], using the existing val handling.
- Around line 4-24: Extract the duplicated fallback parser into an exported
parseEnvFile function in src/env.ts, returning parsed key-value pairs; update
src/cli.ts lines 4-24 to call it when process.loadEnvFile is unavailable and
assign the result to process.env. Update src/env.test.ts lines 4-19 to import
parseEnvFile, remove simulateEnvLoad, and replace all its calls so tests
exercise the production parser.

In `@src/env.test.ts`:
- Around line 4-19: The tests currently use simulateEnvLoad, duplicating the
parser from cli.ts instead of exercising production behavior. Remove this helper
and update the affected tests in src/env.test.ts to invoke the exported
production environment-loading/parser function from cli.ts, preserving the
existing test cases and assertions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 1d416c05-6a35-4474-be3f-90aee4a2ce6e

📥 Commits

Reviewing files that changed from the base of the PR and between 8d9ecac and 0bd22fc.

📒 Files selected for processing (5)
  • .gitignore
  • openspec/changes/P9-env-support/proposal.md
  • openspec/changes/P9-env-support/tasks.md
  • src/cli.ts
  • src/env.test.ts

Comment thread src/cli.ts Outdated
Comment on lines +4 to +24
// Load local environment variables from .env if present
if (existsSync(".env")) {
try {
if (typeof process.loadEnvFile === "function") {
process.loadEnvFile(".env");
} else {
// Fallback parser for Node.js versions < 20.12
const content = readFileSync(".env", "utf8");
for (const line of content.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const idx = trimmed.indexOf("=");
if (idx === -1) continue;
const key = trimmed.slice(0, idx).trim();
let val = trimmed.slice(idx + 1).trim();
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
val = val.slice(1, -1);
}
process.env[key] = val;
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Parser logic is duplicated between production code and tests instead of being shared. The fallback .env parser lives inline in src/cli.ts and is copy-pasted as simulateEnvLoad in src/env.test.ts, meaning the tests don't actually exercise the production code path.

  • src/cli.ts#L4-L24: Extract the fallback parser into a separate, exported function (e.g., src/env.ts exporting parseEnvFile(content: string): Record<string, string>) and call it from cli.ts.
  • src/env.test.ts#L4-L19: Replace simulateEnvLoad with an import of the extracted parser so tests validate the real implementation.
♻️ Proposed extraction

New file src/env.ts:

export function parseEnvFile(content: string): Record<string, string> {
  const env: Record<string, string> = {};
  for (const line of content.split(/\r?\n/)) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith("#")) continue;
    const idx = trimmed.indexOf("=");
    if (idx === -1) continue;
    const key = trimmed.slice(0, idx).trim();
    let val = trimmed.slice(idx + 1).trim();
    if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
      val = val.slice(1, -1);
    }
    env[key] = val;
  }
  return env;
}

src/cli.ts fallback path:

+import { parseEnvFile } from "./env.js";
 // ...
     } else {
-      const content = readFileSync(".env", "utf8");
-      for (const line of content.split(/\r?\n/)) {
-        const trimmed = line.trim();
-        if (!trimmed || trimmed.startsWith("#")) continue;
-        const idx = trimmed.indexOf("=");
-        if (idx === -1) continue;
-        const key = trimmed.slice(0, idx).trim();
-        let val = trimmed.slice(idx + 1).trim();
-        if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
-          val = val.slice(1, -1);
-        }
-        process.env[key] = val;
-      }
+      const parsed = parseEnvFile(readFileSync(".env", "utf8"));
+      for (const [key, val] of Object.entries(parsed)) {
+        process.env[key] = val;
+      }
     }

src/env.test.ts:

-import { expect, test } from "vitest";
-
-// A small wrapper around our loader logic to test it
-function simulateEnvLoad(content: string): Record<string, string> {
-  const env: Record<string, string> = {};
-  for (const line of content.split(/\r?\n/)) {
-    const trimmed = line.trim();
-    if (!trimmed || trimmed.startsWith("#")) continue;
-    const idx = trimmed.indexOf("=");
-    if (idx === -1) continue;
-    const key = trimmed.slice(0, idx).trim();
-    let val = trimmed.slice(idx + 1).trim();
-    if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
-      val = val.slice(1, -1);
-    }
-    env[key] = val;
-  }
-  return env;
-}
+import { expect, test } from "vitest";
+import { parseEnvFile } from "./env.js";

Then replace all simulateEnvLoad(...) calls with parseEnvFile(...).

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Load local environment variables from .env if present
if (existsSync(".env")) {
try {
if (typeof process.loadEnvFile === "function") {
process.loadEnvFile(".env");
} else {
// Fallback parser for Node.js versions < 20.12
const content = readFileSync(".env", "utf8");
for (const line of content.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const idx = trimmed.indexOf("=");
if (idx === -1) continue;
const key = trimmed.slice(0, idx).trim();
let val = trimmed.slice(idx + 1).trim();
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
val = val.slice(1, -1);
}
process.env[key] = val;
}
}
// Load local environment variables from .env if present
if (existsSync(".env")) {
try {
if (typeof process.loadEnvFile === "function") {
process.loadEnvFile(".env");
} else {
const parsed = parseEnvFile(readFileSync(".env", "utf8"));
for (const [key, val] of Object.entries(parsed)) {
process.env[key] = val;
}
}
📍 Affects 2 files
  • src/cli.ts#L4-L24 (this comment)
  • src/env.test.ts#L4-L19
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/cli.ts` around lines 4 - 24, Extract the duplicated fallback parser into
an exported parseEnvFile function in src/env.ts, returning parsed key-value
pairs; update src/cli.ts lines 4-24 to call it when process.loadEnvFile is
unavailable and assign the result to process.env. Update src/env.test.ts lines
4-19 to import parseEnvFile, remove simulateEnvLoad, and replace all its calls
so tests exercise the production parser.

Comment thread src/cli.ts Outdated
Comment thread src/env.test.ts Outdated
The test duplicated the parser inline instead of exercising the real
one. Extract parseEnv/loadDotEnv to src/env.ts, import from cli.ts, and
point the test at the actual parser. Also drop the ordering hazard of
running loader code between import statements.
@DataDave-Dev DataDave-Dev merged commit 92bc07d into DataDave-Dev:main Jul 11, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants