Skip to content

Commit b5ef76e

Browse files
authored
chore: config feedback (#610)
1 parent 17fa0bc commit b5ef76e

File tree

24 files changed

+96
-136
lines changed

24 files changed

+96
-136
lines changed

src/codegen/cli/commands/config/main.py

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
from rich.table import Table
66

77
from codegen.configs.constants import ENV_FILENAME, GLOBAL_ENV_FILE
8-
from codegen.configs.session_manager import session_manager
98
from codegen.configs.user_config import UserConfig
9+
from codegen.shared.path import get_git_root_path
1010

1111

1212
@click.group(name="config")
@@ -16,8 +16,7 @@ def config_command():
1616

1717

1818
@config_command.command(name="list")
19-
@click.option("--global", "is_global", is_flag=True, help="Lists the global configuration values")
20-
def list_command(is_global: bool):
19+
def list_command():
2120
"""List current configuration values."""
2221

2322
def flatten_dict(data: dict, prefix: str = "") -> dict:
@@ -33,7 +32,7 @@ def flatten_dict(data: dict, prefix: str = "") -> dict:
3332
items[full_key] = value
3433
return items
3534

36-
config = _get_user_config(is_global)
35+
config = _get_user_config()
3736
flat_config = flatten_dict(config.to_dict())
3837
sorted_items = sorted(flat_config.items(), key=lambda x: x[0])
3938

@@ -82,10 +81,9 @@ def flatten_dict(data: dict, prefix: str = "") -> dict:
8281

8382
@config_command.command(name="get")
8483
@click.argument("key")
85-
@click.option("--global", "is_global", is_flag=True, help="Get the global configuration value")
86-
def get_command(key: str, is_global: bool):
84+
def get_command(key: str):
8785
"""Get a configuration value."""
88-
config = _get_user_config(is_global)
86+
config = _get_user_config()
8987
if not config.has_key(key):
9088
rich.print(f"[red]Error: Configuration key '{key}' not found[/red]")
9189
return
@@ -98,10 +96,9 @@ def get_command(key: str, is_global: bool):
9896
@config_command.command(name="set")
9997
@click.argument("key")
10098
@click.argument("value")
101-
@click.option("--global", "is_global", is_flag=True, help="Sets the global configuration value")
102-
def set_command(key: str, value: str, is_global: bool):
99+
def set_command(key: str, value: str):
103100
"""Set a configuration value and write to .env"""
104-
config = _get_user_config(is_global)
101+
config = _get_user_config()
105102
if not config.has_key(key):
106103
rich.print(f"[red]Error: Configuration key '{key}' not found[/red]")
107104
return
@@ -118,10 +115,10 @@ def set_command(key: str, value: str, is_global: bool):
118115
rich.print(f"[green]Successfully set {key}=[magenta]{value}[/magenta] and saved to {ENV_FILENAME}[/green]")
119116

120117

121-
def _get_user_config(is_global: bool) -> UserConfig:
122-
if is_global or (active_session_path := session_manager.get_active_session()) is None:
118+
def _get_user_config() -> UserConfig:
119+
if (project_root := get_git_root_path()) is None:
123120
env_filepath = GLOBAL_ENV_FILE
124121
else:
125-
env_filepath = active_session_path / ENV_FILENAME
122+
env_filepath = project_root / ENV_FILENAME
126123

127124
return UserConfig(env_filepath)

src/codegen/cli/commands/init/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from codegen.cli.commands.init.render import get_success_message
99
from codegen.cli.rich.codeblocks import format_command
1010
from codegen.cli.workspace.initialize_workspace import initialize_codegen
11-
from codegen.git.utils.path import get_git_root_path
11+
from codegen.shared.path import get_git_root_path
1212

1313

1414
@click.command(name="init")

src/codegen/cli/env/global_env.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,20 +38,24 @@ def _parse_env(self) -> Environment:
3838
def _load_dotenv(self) -> None:
3939
env_file = find_dotenv(filename=f".env.{self.ENV}")
4040
# if env specific .env file does not exist, try to load .env
41-
load_dotenv(env_file or None)
41+
load_dotenv(env_file or None, override=True)
4242

4343
def _get_env_var(self, var_name, required: bool = False) -> str:
4444
if self.ENV == "local":
4545
return ""
4646

47-
value = os.environ.get(var_name)
48-
if value:
47+
if value := os.environ.get(var_name):
4948
return value
49+
5050
if required:
5151
msg = f"Environment variable {var_name} is not set with ENV={self.ENV}!"
5252
raise ValueError(msg)
5353
return ""
5454

55+
def __repr__(self) -> str:
56+
# Returns all env vars in a readable format
57+
return "\n".join([f"{k}={v}" for k, v in self.__dict__.items()])
58+
5559

5660
# NOTE: load and store envvars once
5761
global_env = GlobalEnv()

src/codegen/configs/models/base_config.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
from abc import ABC
22
from pathlib import Path
33

4-
from dotenv import set_key
4+
from dotenv import load_dotenv, set_key
55
from pydantic_settings import BaseSettings, SettingsConfigDict
66

77
from codegen.configs.constants import ENV_FILENAME, GLOBAL_ENV_FILE
8-
from codegen.configs.session_manager import session_root
8+
from codegen.shared.path import get_git_root_path
99

1010

1111
class BaseConfig(BaseSettings, ABC):
@@ -18,20 +18,18 @@ class BaseConfig(BaseSettings, ABC):
1818

1919
def __init__(self, prefix: str, env_filepath: Path | None = None, *args, **kwargs) -> None:
2020
if env_filepath is None:
21-
root_path = session_root
21+
root_path = get_git_root_path()
2222
if root_path is not None:
2323
env_filepath = root_path / ENV_FILENAME
2424

2525
# Only include env files that exist
26-
env_filepaths = []
2726
if GLOBAL_ENV_FILE.exists():
28-
env_filepaths.append(GLOBAL_ENV_FILE)
27+
load_dotenv(GLOBAL_ENV_FILE, override=True)
28+
2929
if env_filepath and env_filepath.exists() and env_filepath != GLOBAL_ENV_FILE:
30-
env_filepaths.append(env_filepath)
30+
load_dotenv(env_filepath, override=True)
3131

3232
self.model_config["env_prefix"] = f"{prefix.upper()}_" if len(prefix) > 0 else ""
33-
self.model_config["env_file"] = env_filepaths
34-
3533
super().__init__(*args, **kwargs)
3634

3735
@property

src/codegen/configs/models/repository.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,3 @@ def full_name(self) -> str | None:
3737
if self.owner is not None:
3838
return f"{self.owner}/{self.name}"
3939
return None
40-
41-
42-
DefaultRepoConfig = RepositoryConfig()

src/codegen/configs/models/secrets.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,3 @@ def __init__(self, prefix: str = "", *args, **kwargs) -> None:
1414
github_token: str | None = None
1515
openai_api_key: str | None = None
1616
linear_api_key: str | None = None
17-
18-
19-
DefaultSecrets = SecretsConfig()

src/codegen/configs/session_manager.py

Lines changed: 1 addition & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import json
44
from pathlib import Path
55

6-
from codegen.configs.constants import CODEGEN_DIR_NAME, SESSION_FILE
6+
from codegen.configs.constants import SESSION_FILE
77

88

99
class SessionManager:
@@ -61,34 +61,4 @@ def __str__(self) -> str:
6161
return f"GlobalConfig:\n Active Session: {active}\n Sessions:\n {sessions_str}\n Global Session:\n {self.session_config}"
6262

6363

64-
def _get_project_root() -> Path | None:
65-
"""Get the active codegen directory."""
66-
active_session = session_manager.get_active_session()
67-
if active_session:
68-
return active_session
69-
70-
try:
71-
path = Path.cwd().resolve()
72-
except FileNotFoundError:
73-
# Current directory is not accessible
74-
return None
75-
76-
while True:
77-
codegen_path = path / CODEGEN_DIR_NAME
78-
git_path = path / ".git"
79-
80-
if codegen_path.exists():
81-
return path
82-
if git_path.exists():
83-
return path
84-
85-
parent = path.parent.resolve()
86-
if parent == path: # We've reached the root directory
87-
break
88-
path = parent
89-
90-
return None
91-
92-
9364
session_manager = SessionManager()
94-
session_root = _get_project_root()

src/codegen/configs/user_config.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,13 @@ def to_dict(self) -> dict:
3434
for key, value in self.repository.model_dump().items():
3535
config_dict[f"{self.repository.env_prefix}{key}".upper()] = value
3636

37-
# Add secrets configs with 'secrets_' prefix
38-
for key, value in self.secrets.model_dump().items():
39-
config_dict[f"{self.secrets.env_prefix}{key}".upper()] = value
40-
4137
# Add feature flags configs with 'feature_flags_' prefix
4238
for key, value in self.codebase.model_dump().items():
4339
config_dict[f"{self.codebase.env_prefix}{key}".upper()] = value
40+
41+
# Add secrets configs
42+
for key, value in self.secrets.model_dump().items():
43+
config_dict[f"{self.secrets.env_prefix}{key}".upper()] = value
4444
return config_dict
4545

4646
def has_key(self, full_key: str) -> bool:

src/codegen/extensions/lsp/protocol.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from lsprotocol.types import INITIALIZE, InitializeParams, InitializeResult
66
from pygls.protocol import LanguageServerProtocol, lsp_method
77

8-
from codegen.configs.models.codebase import DefaultCodebaseConfig
8+
from codegen.configs.models.codebase import CodebaseConfig
99
from codegen.extensions.lsp.io import LSPIO
1010
from codegen.extensions.lsp.progress import LSPProgress
1111
from codegen.extensions.lsp.utils import get_path
@@ -26,7 +26,7 @@ def _init_codebase(self, params: InitializeParams) -> None:
2626
root = get_path(params.root_uri)
2727
else:
2828
root = os.getcwd()
29-
config = DefaultCodebaseConfig.model_copy(update={"full_range_index": True})
29+
config = CodebaseConfig().model_copy(update={"full_range_index": True})
3030
io = LSPIO(self.workspace)
3131
self._server.codebase = Codebase(repo_path=str(root), config=config, io=io, progress=progress)
3232
self._server.progress_manager = progress

src/codegen/git/clients/git_repo_client.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from github.Tag import Tag
1616
from github.Workflow import Workflow
1717

18+
from codegen.configs.models.secrets import SecretsConfig
1819
from codegen.git.clients.github_client import GithubClient
1920
from codegen.git.schemas.repo_config import RepoConfig
2021
from codegen.git.utils.format import format_comparison
@@ -29,9 +30,9 @@ class GitRepoClient:
2930
gh_client: GithubClient
3031
_repo: Repository
3132

32-
def __init__(self, repo_config: RepoConfig, access_token: str) -> None:
33+
def __init__(self, repo_config: RepoConfig, access_token: str | None = None) -> None:
3334
self.repo_config = repo_config
34-
self.gh_client = self._create_github_client(token=access_token)
35+
self.gh_client = self._create_github_client(token=access_token or SecretsConfig().github_token)
3536
self._repo = self._create_client()
3637

3738
def _create_github_client(self, token: str) -> GithubClient:

src/codegen/git/repo_operator/repo_operator.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from github.IssueComment import IssueComment
1818
from github.PullRequest import PullRequest
1919

20-
from codegen.configs.models.secrets import DefaultSecrets
20+
from codegen.configs.models.secrets import SecretsConfig
2121
from codegen.git.clients.git_repo_client import GitRepoClient
2222
from codegen.git.configs.constants import CODEGEN_BOT_EMAIL, CODEGEN_BOT_NAME
2323
from codegen.git.repo_operator.local_git_repo import LocalGitRepo
@@ -58,7 +58,7 @@ def __init__(
5858
) -> None:
5959
assert repo_config is not None
6060
self.repo_config = repo_config
61-
self.access_token = access_token or DefaultSecrets.github_token
61+
self.access_token = access_token or SecretsConfig().github_token
6262
self.base_dir = repo_config.base_dir
6363
self.bot_commit = bot_commit
6464

@@ -839,7 +839,7 @@ def create_from_repo(cls, repo_path: str, url: str, access_token: str | None = N
839839
url (str): Git URL of the repository
840840
access_token (str | None): Optional GitHub API key for operations that need GitHub access
841841
"""
842-
access_token = access_token or DefaultSecrets.github_token
842+
access_token = access_token or SecretsConfig().github_token
843843
if access_token:
844844
url = add_access_token_to_url(url=url, token=access_token)
845845

src/codegen/runner/clients/codebase_client.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import logging
44

5-
from codegen.configs.models import secrets
5+
from codegen.configs.models.secrets import SecretsConfig
66
from codegen.git.schemas.repo_config import RepoConfig
77
from codegen.runner.clients.server_client import LocalServerClient
88
from codegen.runner.models.apis import SANDBOX_SERVER_PORT
@@ -16,11 +16,9 @@ class CodebaseClient(LocalServerClient):
1616
"""Client for interacting with the locally hosted sandbox server."""
1717

1818
repo_config: RepoConfig
19-
git_access_token: str | None
2019

21-
def __init__(self, repo_config: RepoConfig, git_access_token: str | None, host: str = "127.0.0.1", port: int = SANDBOX_SERVER_PORT):
20+
def __init__(self, repo_config: RepoConfig, host: str = "127.0.0.1", port: int = SANDBOX_SERVER_PORT):
2221
self.repo_config = repo_config
23-
self.git_access_token = git_access_token
2422
super().__init__(server_path=RUNNER_SERVER_PATH, host=host, port=port)
2523

2624
def _get_envs(self) -> dict:
@@ -29,9 +27,8 @@ def _get_envs(self) -> dict:
2927
"REPOSITORY_LANGUAGE": self.repo_config.language.value,
3028
"REPOSITORY_OWNER": self.repo_config.organization_name,
3129
"REPOSITORY_PATH": str(self.repo_config.repo_path),
30+
"GITHUB_TOKEN": SecretsConfig().github_token,
3231
}
33-
if self.git_access_token is not None:
34-
codebase_envs["GITHUB_TOKEN"] = self.git_access_token
3532

3633
envs.update(codebase_envs)
3734
return envs
@@ -40,5 +37,5 @@ def _get_envs(self) -> dict:
4037
if __name__ == "__main__":
4138
test_config = RepoConfig.from_repo_path("/Users/caroljung/git/codegen/codegen-agi")
4239
test_config.full_name = "codegen-sh/codegen-agi"
43-
client = CodebaseClient(test_config, secrets.github_token)
40+
client = CodebaseClient(test_config)
4441
print(client.healthcheck())

src/codegen/runner/sandbox/runner.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,9 @@ class SandboxRunner:
2929
codebase: CodebaseType
3030
executor: SandboxExecutor
3131

32-
def __init__(self, repo_config: RepoConfig, access_token: str) -> None:
32+
def __init__(self, repo_config: RepoConfig) -> None:
3333
self.repo = repo_config
34-
self.op = RepoOperator(repo_config=self.repo, access_token=access_token, setup_option=SetupOption.PULL_OR_CLONE)
34+
self.op = RepoOperator(repo_config=self.repo, setup_option=SetupOption.PULL_OR_CLONE)
3535
self.commit = self.op.git_cli.head.commit
3636

3737
async def warmup(self) -> None:

src/codegen/runner/sandbox/server.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,7 @@
77
import psutil
88
from fastapi import FastAPI
99

10-
from codegen.configs.models.repository import DefaultRepoConfig
11-
from codegen.configs.models.secrets import DefaultSecrets
10+
from codegen.configs.models.repository import RepositoryConfig
1211
from codegen.git.schemas.repo_config import RepoConfig
1312
from codegen.runner.enums.warmup_state import WarmupState
1413
from codegen.runner.models.apis import (
@@ -40,15 +39,16 @@ async def lifespan(server: FastAPI):
4039
global runner
4140

4241
try:
43-
server_info = ServerInfo(repo_name=DefaultRepoConfig.full_name or DefaultRepoConfig.name)
42+
default_repo_config = RepositoryConfig()
43+
server_info = ServerInfo(repo_name=default_repo_config.full_name or default_repo_config.name)
4444
logger.info(f"Starting up sandbox fastapi server for repo_name={server_info.repo_name}")
4545
repo_config = RepoConfig(
46-
name=DefaultRepoConfig.name,
47-
full_name=DefaultRepoConfig.full_name,
48-
base_dir=os.path.dirname(DefaultRepoConfig.path),
49-
language=ProgrammingLanguage(DefaultRepoConfig.language.upper()),
46+
name=default_repo_config.name,
47+
full_name=default_repo_config.full_name,
48+
base_dir=os.path.dirname(default_repo_config.path),
49+
language=ProgrammingLanguage(default_repo_config.language.upper()),
5050
)
51-
runner = SandboxRunner(repo_config=repo_config, access_token=DefaultSecrets.github_token)
51+
runner = SandboxRunner(repo_config=repo_config)
5252
server_info.warmup_state = WarmupState.PENDING
5353
await runner.warmup()
5454
server_info.warmup_state = WarmupState.COMPLETED

src/codegen/sdk/code_generation/codegen_sdk_codebase.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import os.path
22

3-
from codegen.configs.models.codebase import DefaultCodebaseConfig
43
from codegen.sdk.code_generation.current_code_codebase import get_codegen_codebase_base_path, get_current_code_codebase
54
from codegen.sdk.core.codebase import Codebase
65

@@ -12,5 +11,5 @@ def get_codegen_sdk_subdirectories() -> list[str]:
1211

1312
def get_codegen_sdk_codebase() -> Codebase:
1413
"""Grabs a Codebase w/ GraphSitter content. Responsible for figuring out where it is, e.g. in Modal or local"""
15-
codebase = get_current_code_codebase(DefaultCodebaseConfig, subdirectories=get_codegen_sdk_subdirectories())
14+
codebase = get_current_code_codebase(subdirectories=get_codegen_sdk_subdirectories())
1615
return codebase

0 commit comments

Comments
 (0)