diff --git a/codeflash/code_utils/env_utils.py b/codeflash/code_utils/env_utils.py index eca59bfa8..a7bc8a1fa 100644 --- a/codeflash/code_utils/env_utils.py +++ b/codeflash/code_utils/env_utils.py @@ -10,8 +10,7 @@ from codeflash.cli_cmds.console import logger from codeflash.code_utils.code_utils import exit_with_message from codeflash.code_utils.formatter import format_code -from codeflash.code_utils.shell_utils import read_api_key_from_shell_config -from codeflash.lsp.helpers import is_LSP_enabled +from codeflash.code_utils.shell_utils import read_api_key_from_shell_config, save_api_key_to_rc def check_formatter_installed(formatter_cmds: list[str], exit_on_failure: bool = True) -> bool: # noqa @@ -35,12 +34,21 @@ 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() - ) + # Check environment variable first + env_api_key = os.environ.get("CODEFLASH_API_KEY") + shell_api_key = read_api_key_from_shell_config() + + # If we have an env var but it's not in shell config, save it for persistence + if env_api_key and not shell_api_key: + try: + from codeflash.either import is_successful + result = save_api_key_to_rc(env_api_key) + if is_successful(result): + logger.debug(f"Automatically saved API key from environment to shell config: {result.unwrap()}") + except Exception as e: + logger.debug(f"Failed to automatically save API key to shell config: {e}") + + api_key = env_api_key or shell_api_key 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: