Skip to content

chore: use from_repo + clean-up from_repo #462

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 13, 2025
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
5 changes: 5 additions & 0 deletions src/codegen/git/repo_operator/local_repo_operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
from codegen.git.repo_operator.repo_operator import RepoOperator
from codegen.git.schemas.enums import FetchResult
from codegen.git.schemas.repo_config import RepoConfig
from codegen.git.utils.clone_url import add_access_token_to_url
from codegen.git.utils.file_utils import create_files
from codegen.shared.configs.session_configs import config

logger = logging.getLogger(__name__)

Expand All @@ -39,7 +41,7 @@
super().__init__(repo_config=repo_config, access_token=access_token, bot_commit=bot_commit)
os.makedirs(self.repo_path, exist_ok=True)
GitCLI.init(self.repo_path)
self._local_git_repo = LocalGitRepo(repo_path=repo_config.repo_path)

Check failure on line 44 in src/codegen/git/repo_operator/local_repo_operator.py

View workflow job for this annotation

GitHub Actions / mypy

error: Argument "repo_path" to "LocalGitRepo" has incompatible type "str"; expected "Path" [arg-type]
if repo_config.full_name is None:
repo_config.full_name = self._local_git_repo.full_name

Expand All @@ -48,7 +50,7 @@
####################################################################################################################

@property
def remote_git_repo(self) -> GitRepoClient | None:

Check failure on line 53 in src/codegen/git/repo_operator/local_repo_operator.py

View workflow job for this annotation

GitHub Actions / mypy

error: Signature of "remote_git_repo" incompatible with supertype "RepoOperator" [override]
"""Get the remote GitRepoClient object for the current local repo."""
if not self.access_token:
msg = "Must initialize with access_token to get remote"
Expand Down Expand Up @@ -112,6 +114,9 @@
url (str): Git URL of the repository
access_token (str | None): Optional GitHub API key for operations that need GitHub access
"""
access_token = access_token or config.secrets.github_token
url = add_access_token_to_url(url=url, token=access_token)

# Check if repo already exists
if os.path.exists(repo_path):
try:
Expand Down Expand Up @@ -150,11 +155,11 @@
####################################################################################################################

@property
def codeowners_parser(self) -> CodeOwnersParser | None:

Check failure on line 158 in src/codegen/git/repo_operator/local_repo_operator.py

View workflow job for this annotation

GitHub Actions / mypy

error: Signature of "codeowners_parser" incompatible with supertype "RepoOperator" [override]
return None

@cached_property
def base_url(self) -> str | None:

Check failure on line 162 in src/codegen/git/repo_operator/local_repo_operator.py

View workflow job for this annotation

GitHub Actions / mypy

error: Signature of "base_url" incompatible with supertype "RepoOperator" [override]
return self._local_git_repo.base_url

@override
Expand Down
15 changes: 6 additions & 9 deletions src/codegen/sdk/core/codebase.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,13 +176,13 @@
main_project = ProjectConfig.from_path(repo_path, programming_language=programming_language)
projects = [main_project]
else:
main_project = projects[0]

Check failure on line 179 in src/codegen/sdk/core/codebase.py

View workflow job for this annotation

GitHub Actions / mypy

error: Value of type "list[ProjectConfig] | None" is not indexable [index]

# Initialize codebase
self._op = main_project.repo_operator
self.viz = VisualizationManager(op=self._op)
self.repo_path = Path(self._op.repo_path)
self.ctx = CodebaseContext(projects, config=config, io=io)

Check failure on line 185 in src/codegen/sdk/core/codebase.py

View workflow job for this annotation

GitHub Actions / mypy

error: Argument 1 to "CodebaseContext" has incompatible type "list[ProjectConfig] | None"; expected "list[ProjectConfig]" [arg-type]
self.console = Console(record=True, soft_wrap=True)

@noapidoc
Expand All @@ -198,7 +198,7 @@
yield "nodes", len(self.ctx.nodes)
yield "edges", len(self.ctx.edges)

__rich_repr__.angular = ANGULAR_STYLE

Check failure on line 201 in src/codegen/sdk/core/codebase.py

View workflow job for this annotation

GitHub Actions / mypy

error: "Callable[[Codebase[TSourceFile, TDirectory, TSymbol, TClass, TFunction, TImport, TGlobalVar, TInterface, TTypeAlias, TParameter, TCodeBlock]], Iterable[Any | tuple[Any] | tuple[str, Any] | tuple[str, Any, Any]]]" has no attribute "angular" [attr-defined]

@property
@deprecated("Please do not use the local repo operator directly")
Expand Down Expand Up @@ -226,8 +226,8 @@

@noapidoc
def _symbols(self, symbol_type: SymbolType | None = None) -> list[TSymbol | TClass | TFunction | TGlobalVar]:
matches: list[Symbol] = self.ctx.get_nodes(NodeType.SYMBOL)

Check failure on line 229 in src/codegen/sdk/core/codebase.py

View workflow job for this annotation

GitHub Actions / mypy

error: Incompatible types in assignment (expression has type "list[Importable[Any]]", variable has type "list[Symbol[Any, Any]]") [assignment]
return [x for x in matches if x.is_top_level and (symbol_type is None or x.symbol_type == symbol_type)]

Check failure on line 230 in src/codegen/sdk/core/codebase.py

View workflow job for this annotation

GitHub Actions / mypy

error: List comprehension has incompatible type List[Symbol[Any, Any]]; expected List[TSymbol | TClass | TFunction | TGlobalVar] [misc]

# =====[ Node Types ]=====
@overload
Expand All @@ -236,7 +236,7 @@
def files(self, *, extensions: Literal["*"]) -> list[File]: ...
@overload
def files(self, *, extensions: None = ...) -> list[TSourceFile]: ...
@proxy_property

Check failure on line 239 in src/codegen/sdk/core/codebase.py

View workflow job for this annotation

GitHub Actions / mypy

error: "cached_property[ProxyProperty[[Codebase[TSourceFile, TDirectory, TSymbol, TClass, TFunction, TImport, TGlobalVar, TInterface, TTypeAlias, TParameter, TCodeBlock], DefaultNamedArg(list[str] | Literal['*'] | None, 'extensions')], list[TSourceFile] | list[File]]]" not callable [operator]
def files(self, *, extensions: list[str] | Literal["*"] | None = None) -> list[TSourceFile] | list[File]:
"""A list property that returns all files in the codebase.

Expand Down Expand Up @@ -1219,11 +1219,10 @@
@classmethod
def from_repo(
cls,
repo_name: str,
repo_full_name: str,
*,
tmp_dir: str | None = None,
tmp_dir: str | None = "/tmp/codegen",
commit: str | None = None,
shallow: bool = True,
programming_language: ProgrammingLanguage | None = None,
config: CodebaseConfig = DefaultConfig,
) -> "Codebase":
Expand All @@ -1240,23 +1239,21 @@
Returns:
Codebase: A Codebase instance initialized with the cloned repository
"""
logger.info(f"Fetching codebase for {repo_name}")
logger.info(f"Fetching codebase for {repo_full_name}")

# Parse repo name
if "/" not in repo_name:
if "/" not in repo_full_name:
msg = "repo_name must be in format 'owner/repo'"
raise ValueError(msg)
owner, repo = repo_name.split("/")
owner, repo = repo_full_name.split("/")

# Setup temp directory
if tmp_dir is None:
tmp_dir = "/tmp/codegen"
os.makedirs(tmp_dir, exist_ok=True)
logger.info(f"Using directory: {tmp_dir}")

# Setup repo path and URL
repo_path = os.path.join(tmp_dir, repo)
repo_url = f"https://github.com/{repo_name}.git"
repo_url = f"https://github.com/{repo_full_name}.git"
logger.info(f"Will clone {repo_url} to {repo_path}")

try:
Expand Down
31 changes: 4 additions & 27 deletions tests/integration/codegen/git/codebase/conftest.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,13 @@
import os

import pytest
from git import Repo as GitRepo

from codegen.git.repo_operator.local_repo_operator import LocalRepoOperator
from codegen.git.schemas.repo_config import RepoConfig
from codegen.git.utils.clone_url import get_authenticated_clone_url_for_repo_config
from codegen.sdk.codebase.config import ProjectConfig
from codegen.sdk.core.codebase import Codebase
from codegen.shared.configs.session_configs import config
from codegen.shared.enums.programming_language import ProgrammingLanguage


@pytest.fixture
def repo_config(tmpdir):
repo_config = RepoConfig(
name="Kevin-s-Adventure-Game",
full_name="codegen-sh/Kevin-s-Adventure-Game",
base_dir=str(tmpdir),
)
yield repo_config


@pytest.fixture
def op(repo_config):
os.chdir(repo_config.base_dir)
GitRepo.clone_from(url=get_authenticated_clone_url_for_repo_config(repo_config, token=config.secrets.github_token), to_path=os.path.join(repo_config.base_dir, repo_config.name), depth=1)
op = LocalRepoOperator(repo_config=repo_config)
yield op


@pytest.fixture
def codebase(op: LocalRepoOperator):
project_config = ProjectConfig(repo_operator=op)
codebase = Codebase(projects=[project_config])
def codebase(tmpdir):
os.chdir(tmpdir)
codebase = Codebase.from_repo(repo_full_name="codegen-sh/Kevin-s-Adventure-Game", tmp_dir=tmpdir, programming_language=ProgrammingLanguage.PYTHON)
yield codebase