22
33import json
44import os
5- import sys
5+ from dataclasses import dataclass
66from functools import lru_cache
77from pathlib import Path
88from typing import TYPE_CHECKING , Any , Optional
1313from pydantic .json import pydantic_encoder
1414
1515from codeflash .cli_cmds .console import console , logger
16+ from codeflash .code_utils .code_utils import exit_with_message
1617from codeflash .code_utils .env_utils import ensure_codeflash_api_key , get_codeflash_api_key , get_pr_number
1718from codeflash .code_utils .git_utils import get_current_branch , get_repo_owner_and_name
1819from codeflash .github .PrComment import FileDiffContent , PrComment
2627
2728from packaging import version
2829
29- if os .environ .get ("CODEFLASH_CFAPI_SERVER" , "prod" ).lower () == "local" :
30- CFAPI_BASE_URL = "http://localhost:3001"
31- CFWEBAPP_BASE_URL = "http://localhost:3000"
32- logger .info (f"Using local CF API at { CFAPI_BASE_URL } ." )
33- console .rule ()
34- else :
35- CFAPI_BASE_URL = "https://app.codeflash.ai"
36- CFWEBAPP_BASE_URL = "https://app.codeflash.ai"
30+
31+ @dataclass
32+ class BaseUrls :
33+ cfapi_base_url : Optional [str ] = None
34+ cfwebapp_base_url : Optional [str ] = None
35+
36+
37+ @lru_cache (maxsize = 1 )
38+ def get_cfapi_base_urls () -> BaseUrls :
39+ if os .environ .get ("CODEFLASH_CFAPI_SERVER" , "prod" ).lower () == "local" :
40+ cfapi_base_url = "http://localhost:3001"
41+ cfwebapp_base_url = "http://localhost:3000"
42+ logger .info (f"Using local CF API at { cfapi_base_url } ." )
43+ console .rule ()
44+ else :
45+ cfapi_base_url = "https://app.codeflash.ai"
46+ cfwebapp_base_url = "https://app.codeflash.ai"
47+ return BaseUrls (cfapi_base_url = cfapi_base_url , cfwebapp_base_url = cfwebapp_base_url )
3748
3849
3950def make_cfapi_request (
@@ -53,8 +64,9 @@ def make_cfapi_request(
5364 :param suppress_errors: If True, suppress error logging for HTTP errors.
5465 :return: The response object from the API.
5566 """
56- url = f"{ CFAPI_BASE_URL } /cfapi{ endpoint } "
57- cfapi_headers = {"Authorization" : f"Bearer { api_key or get_codeflash_api_key ()} " }
67+ url = f"{ get_cfapi_base_urls ().cfapi_base_url } /cfapi{ endpoint } "
68+ final_api_key = api_key or get_codeflash_api_key ()
69+ cfapi_headers = {"Authorization" : f"Bearer { final_api_key } " }
5870 if extra_headers :
5971 cfapi_headers .update (extra_headers )
6072 try :
@@ -86,16 +98,22 @@ def make_cfapi_request(
8698
8799
88100@lru_cache (maxsize = 1 )
89- def get_user_id (api_key : Optional [str ] = None ) -> Optional [str ]:
101+ def get_user_id (api_key : Optional [str ] = None ) -> Optional [str ]: # noqa: PLR0911
90102 """Retrieve the user's userid by making a request to the /cfapi/cli-get-user endpoint.
91103
104+ :param api_key: The API key to use. If None, uses get_codeflash_api_key().
92105 :return: The userid or None if the request fails.
93106 """
107+ lsp_enabled = is_LSP_enabled ()
94108 if not api_key and not ensure_codeflash_api_key ():
95109 return None
96110
97111 response = make_cfapi_request (
98- endpoint = "/cli-get-user" , method = "GET" , extra_headers = {"cli_version" : __version__ }, api_key = api_key
112+ endpoint = "/cli-get-user" ,
113+ method = "GET" ,
114+ extra_headers = {"cli_version" : __version__ },
115+ api_key = api_key ,
116+ suppress_errors = True ,
99117 )
100118 if response .status_code == 200 :
101119 if "min_version" not in response .text :
@@ -107,15 +125,31 @@ def get_user_id(api_key: Optional[str] = None) -> Optional[str]:
107125 if min_version and version .parse (min_version ) > version .parse (__version__ ):
108126 msg = "Your Codeflash CLI version is outdated. Please update to the latest version using `pip install --upgrade codeflash`."
109127 console .print (f"[bold red]{ msg } [/bold red]" )
110- if is_LSP_enabled () :
128+ if lsp_enabled :
111129 logger .debug (msg )
112130 return f"Error: { msg } "
113- sys . exit ( 1 )
131+ exit_with_message ( msg , error_on_exit = True )
114132 return userid
115133
116134 logger .error ("Failed to retrieve userid from the response." )
117135 return None
118136
137+ if response .status_code == 403 :
138+ error_title = "Invalid Codeflash API key. The API key you provided is not valid."
139+ if lsp_enabled :
140+ return f"Error: { error_title } "
141+ msg = (
142+ f"{ error_title } \n "
143+ "Please generate a new one at https://app.codeflash.ai/app/apikeys ,\n "
144+ "then set it as a CODEFLASH_API_KEY environment variable.\n "
145+ "For more information, refer to the documentation at \n "
146+ "https://docs.codeflash.ai/optimizing-with-codeflash/codeflash-github-actions#manual-setup\n "
147+ "or\n "
148+ "https://docs.codeflash.ai/optimizing-with-codeflash/codeflash-github-actions#automated-setup-recommended"
149+ )
150+ exit_with_message (msg , error_on_exit = True )
151+
152+ # For other errors, log and return None (backward compatibility)
119153 logger .error (f"Failed to look up your userid; is your CF API key valid? ({ response .reason } )" )
120154 return None
121155
0 commit comments