Skip to content

Commit d4f8da7

Browse files
committed
feat: add .env file support for easier configuration
Load .env from project root (or parent dirs up to ~) on startup. Existing env vars are not overridden. python-dotenv is now a regular dependency. Closes #1
1 parent db4080a commit d4f8da7

4 files changed

Lines changed: 26 additions & 2 deletions

File tree

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ Every pattern is a real, runnable implementation — not a diagram or a blog pos
5454
pip install nanocoderagent
5555
```
5656

57-
Pick your model — any OpenAI-compatible API works:
57+
Pick your model — any OpenAI-compatible API works. You can `export` env vars or drop a `.env` file in your project root:
5858

5959
```bash
6060
# Kimi K2.5

README_CN.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ Claude Code 51 万行源码提炼出来的 7 个核心模式:
5454
pip install nanocoderagent
5555
```
5656

57-
选你的模型,任何 OpenAI 兼容 API 都行:
57+
选你的模型,任何 OpenAI 兼容 API 都行。可以 `export` 环境变量,也可以在项目根目录放一个 `.env` 文件
5858

5959
```bash
6060
# Kimi K2.5

nanocoder/config.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,27 @@
22

33
import os
44
from dataclasses import dataclass
5+
from pathlib import Path
6+
7+
8+
def _load_dotenv():
9+
"""Load .env from cwd, walking up to home dir. No-op if python-dotenv missing."""
10+
try:
11+
from dotenv import load_dotenv
12+
# search cwd first, then parent dirs up to ~
13+
env_path = Path(".env")
14+
if not env_path.exists():
15+
cur = Path.cwd()
16+
home = Path.home()
17+
while cur != home and cur != cur.parent:
18+
candidate = cur / ".env"
19+
if candidate.exists():
20+
env_path = candidate
21+
break
22+
cur = cur.parent
23+
load_dotenv(env_path, override=False)
24+
except ImportError:
25+
pass # python-dotenv not installed, silently skip
526

627

728
@dataclass
@@ -15,6 +36,8 @@ class Config:
1536

1637
@classmethod
1738
def from_env(cls) -> "Config":
39+
# load .env if present (won't override existing env vars)
40+
_load_dotenv()
1841
# pick up common env vars automatically
1942
api_key = (
2043
os.getenv("NANOCODER_API_KEY")

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ dependencies = [
2525
"openai>=1.0",
2626
"rich>=13.0",
2727
"prompt_toolkit>=3.0",
28+
"python-dotenv>=1.0",
2829
]
2930

3031
[tool.hatch.build.targets.wheel]

0 commit comments

Comments
 (0)