feat(cli) : add native and fallback .env support#3
Conversation
|
Warning Review limit reached
Next review available in: 50 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (3)
📝 WalkthroughWalkthroughThe CLI now loads a local ChangesLocal environment support
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
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (5)
.gitignoreopenspec/changes/P9-env-support/proposal.mdopenspec/changes/P9-env-support/tasks.mdsrc/cli.tssrc/env.test.ts
| // 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; | ||
| } | ||
| } |
There was a problem hiding this comment.
📐 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.tsexportingparseEnvFile(content: string): Record<string, string>) and call it fromcli.ts.src/env.test.ts#L4-L19: ReplacesimulateEnvLoadwith 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.
| // 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.
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.
Summary
This PR adds support for automatically loading local
.envenvironment files when Modlane starts up. This removes the need for developers to manually runexportorsetcommands in their terminal sessions to set their API keys.What Was Added/Changed
src/cli.ts):.envfile at startup.process.loadEnvFile()(available in Node 20.12+)..envfiles are already configured in.gitignoreto ensure developer keys are never committed.proposal.mdandtasks.mdunderopenspec/changes/P9-env-support/.Testing
src/env.test.tsto verify the fallback parser against standard key-values, quotes, comments, and spacing patterns..env.Verified that:
pnpm run typecheckpasses with zero compiler errors.pnpm run buildsucceeds.pnpm testruns and passes all 21 tests.Summary by CodeRabbit
New Features
.envfile..enventries generate a warning without preventing the CLI from starting.Documentation
.envfile support.Tests
.enventries.