diff --git a/codeflash/code_utils/env_utils.py b/codeflash/code_utils/env_utils.py index eca59bfa8..e01658ab3 100644 --- a/codeflash/code_utils/env_utils.py +++ b/codeflash/code_utils/env_utils.py @@ -35,27 +35,26 @@ def check_formatter_installed(formatter_cmds: list[str], exit_on_failure: bool = @lru_cache(maxsize=1) def get_codeflash_api_key() -> str: - # prefer shell config over env var in lsp mode - api_key = ( - read_api_key_from_shell_config() - if is_LSP_enabled() - else os.environ.get("CODEFLASH_API_KEY") or read_api_key_from_shell_config() - ) + lsp_enabled = is_LSP_enabled() + if lsp_enabled: + api_key = read_api_key_from_shell_config() + else: + api_key = os.environ.get("CODEFLASH_API_KEY") or read_api_key_from_shell_config() api_secret_docs_message = "For more information, refer to the documentation at [https://docs.codeflash.ai/getting-started/codeflash-github-actions#add-your-api-key-to-your-repository-secrets]." # noqa if not api_key: - msg = ( - "I didn't find a Codeflash API key in your environment.\nYou can generate one at " - "https://app.codeflash.ai/app/apikeys ,\nthen set it as a CODEFLASH_API_KEY environment variable.\n" - f"{api_secret_docs_message}" - ) - if is_repo_a_fork(): + if lsp_enabled and is_repo_a_fork(): msg = ( "Codeflash API key not detected in your environment. It appears you're running Codeflash from a GitHub fork.\n" "For external contributors, please ensure you've added your own API key to your fork's repository secrets and set it as the CODEFLASH_API_KEY environment variable.\n" f"{api_secret_docs_message}" ) exit_with_message(msg) + msg = ( + "I didn't find a Codeflash API key in your environment.\nYou can generate one at " + "https://app.codeflash.ai/app/apikeys ,\nthen set it as a CODEFLASH_API_KEY environment variable.\n" + f"{api_secret_docs_message}" + ) raise OSError(msg) if not api_key.startswith("cf-"): msg = ( diff --git a/codeflash/code_utils/shell_utils.py b/codeflash/code_utils/shell_utils.py index 30a5aadaa..808e27952 100644 --- a/codeflash/code_utils/shell_utils.py +++ b/codeflash/code_utils/shell_utils.py @@ -22,10 +22,9 @@ def read_api_key_from_shell_config() -> Optional[str]: try: shell_rc_path = get_shell_rc_path() - with open(shell_rc_path, encoding="utf8") as shell_rc: # noqa: PTH123 - shell_contents = shell_rc.read() - matches = SHELL_RC_EXPORT_PATTERN.findall(shell_contents) - return matches[-1] if matches else None + with Path.open(shell_rc_path, encoding="utf8") as shell_rc: + matches = SHELL_RC_EXPORT_PATTERN.findall(shell_rc.read()) + return next(reversed(matches), None) except FileNotFoundError: return None diff --git a/codeflash/lsp/helpers.py b/codeflash/lsp/helpers.py index dc8f8c5d6..aa3419044 100644 --- a/codeflash/lsp/helpers.py +++ b/codeflash/lsp/helpers.py @@ -4,4 +4,4 @@ @lru_cache(maxsize=1) def is_LSP_enabled() -> bool: - return os.getenv("CODEFLASH_LSP", default="false").lower() == "true" + return os.environ.get("CODEFLASH_LSP", "false").lower() == "true"