Skip to content

Commit 5d9de63

Browse files
author
Codeflash Bot
committed
handle edge cases where config file not found or it's empty
1 parent 2c84b05 commit 5d9de63

File tree

3 files changed

+62
-43
lines changed

3 files changed

+62
-43
lines changed

codeflash/cli_cmds/cmd_init.py

Lines changed: 32 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
from codeflash.code_utils.github_utils import get_github_secrets_page_url
3333
from codeflash.code_utils.shell_utils import get_shell_rc_path, save_api_key_to_rc
3434
from codeflash.either import is_successful
35+
from codeflash.lsp.helpers import is_LSP_enabled
3536
from codeflash.telemetry.posthog_cf import ph
3637
from codeflash.version import __version__ as version
3738

@@ -648,41 +649,41 @@ def check_for_toml_or_setup_file() -> str | None:
648649
apologize_and_exit()
649650
create_toml = toml_answers["create_toml"]
650651
if create_toml:
651-
ph("cli-create-pyproject-toml")
652-
# Define a minimal pyproject.toml content
653-
new_pyproject_toml = tomlkit.document()
654-
new_pyproject_toml["tool"] = {"codeflash": {}}
655-
try:
656-
pyproject_toml_path.write_text(tomlkit.dumps(new_pyproject_toml), encoding="utf8")
657-
658-
# Check if the pyproject.toml file was created
659-
if pyproject_toml_path.exists():
660-
success_panel = Panel(
661-
Text(
662-
f"✅ Created a pyproject.toml file at {pyproject_toml_path}\n\n"
663-
"Your project is now ready for Codeflash configuration!",
664-
style="green",
665-
justify="center",
666-
),
667-
title="🎉 Success!",
668-
border_style="bright_green",
669-
)
670-
console.print(success_panel)
671-
console.print("\n📍 Press any key to continue...")
672-
console.input()
673-
ph("cli-created-pyproject-toml")
674-
except OSError:
675-
click.echo(
676-
"❌ Failed to create pyproject.toml. Please check your disk permissions and available space."
677-
)
678-
apologize_and_exit()
679-
else:
680-
click.echo("⏩️ Skipping pyproject.toml creation.")
681-
apologize_and_exit()
652+
create_empty_pyproject_toml(pyproject_toml_path)
682653
click.echo()
683654
return cast("str", project_name)
684655

685656

657+
def create_empty_pyproject_toml(pyproject_toml_path: Path) -> None:
658+
ph("cli-create-pyproject-toml")
659+
lsp_mode = is_LSP_enabled()
660+
# Define a minimal pyproject.toml content
661+
new_pyproject_toml = tomlkit.document()
662+
new_pyproject_toml["tool"] = {"codeflash": {}}
663+
try:
664+
pyproject_toml_path.write_text(tomlkit.dumps(new_pyproject_toml), encoding="utf8")
665+
666+
# Check if the pyproject.toml file was created
667+
if pyproject_toml_path.exists() and not lsp_mode:
668+
success_panel = Panel(
669+
Text(
670+
f"✅ Created a pyproject.toml file at {pyproject_toml_path}\n\n"
671+
"Your project is now ready for Codeflash configuration!",
672+
style="green",
673+
justify="center",
674+
),
675+
title="🎉 Success!",
676+
border_style="bright_green",
677+
)
678+
console.print(success_panel)
679+
console.print("\n📍 Press any key to continue...")
680+
console.input()
681+
ph("cli-created-pyproject-toml")
682+
except OSError:
683+
click.echo("❌ Failed to create pyproject.toml. Please check your disk permissions and available space.")
684+
apologize_and_exit()
685+
686+
686687
def install_github_actions(override_formatter_check: bool = False) -> None: # noqa: FBT001, FBT002
687688
try:
688689
config, _config_file_path = parse_config_file(override_formatter_check=override_formatter_check)

codeflash/code_utils/config_parser.py

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55

66
import tomlkit
77

8+
from codeflash.lsp.helpers import is_LSP_enabled
9+
810
PYPROJECT_TOML_CACHE = {}
911
ALL_CONFIG_FILES = {} # map path to closest config file
1012

@@ -93,15 +95,23 @@ def parse_config_file(
9395
msg = f"Error while parsing the config file {config_file_path}. Please recheck the file for syntax errors. Error: {e}"
9496
raise ValueError(msg) from e
9597

98+
lsp_mode = is_LSP_enabled()
99+
96100
try:
97101
tool = data["tool"]
98102
assert isinstance(tool, dict)
99-
config = tool["codeflash"]
103+
config = tool.get("codeflash", {})
100104
except tomlkit.exceptions.NonExistentKey as e:
105+
if lsp_mode:
106+
# don't fail in lsp mode if codeflash config is not found.
107+
return {}, config_file_path
101108
msg = f"Could not find the 'codeflash' block in the config file {config_file_path}. Please run 'codeflash init' to create the config file."
102109
raise ValueError(msg) from e
103110
assert isinstance(config, dict)
104111

112+
if config == {} and lsp_mode:
113+
return {}, config_file_path
114+
105115
# default values:
106116
path_keys = ["module-root", "tests-root", "benchmarks-root"]
107117
path_list_keys = ["ignore-paths"]
@@ -139,12 +149,13 @@ def parse_config_file(
139149
else:
140150
config[key] = []
141151

142-
assert config["test-framework"] in {"pytest", "unittest"}, (
143-
"In pyproject.toml, Codeflash only supports the 'test-framework' as pytest and unittest."
144-
)
152+
if config.get("test-framework"):
153+
assert config["test-framework"] in {"pytest", "unittest"}, (
154+
"In pyproject.toml, Codeflash only supports the 'test-framework' as pytest and unittest."
155+
)
145156
# see if this is happening during GitHub actions setup
146-
if len(config["formatter-cmds"]) > 0 and not override_formatter_check:
147-
assert config["formatter-cmds"][0] != "your-formatter $file", (
157+
if config.get("formatter-cmds") and len(config.get("formatter-cmds")) > 0 and not override_formatter_check:
158+
assert config.get("formatter-cmds")[0] != "your-formatter $file", (
148159
"The formatter command is not set correctly in pyproject.toml. Please set the "
149160
"formatter command in the 'formatter-cmds' key. More info - https://docs.codeflash.ai/configuration"
150161
)

codeflash/lsp/beta.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
CommonSections,
1616
SetupInfo,
1717
configure_pyproject_toml,
18+
create_empty_pyproject_toml,
1819
get_suggestions,
1920
get_valid_subdirs,
2021
is_valid_pyproject_toml,
@@ -171,13 +172,19 @@ def _find_pyproject_toml(workspace_path: str) -> tuple[Path | None, bool]:
171172
@server.feature("writeConfig")
172173
def write_config(_server: CodeflashLanguageServer, params: WriteConfigParams) -> dict[str, any]:
173174
cfg = params.config
174-
cfg_file = Path(params.config_file)
175+
cfg_file = Path(params.config_file) if params.config_file else None
176+
177+
parsed_config = {}
178+
179+
if cfg_file and not cfg_file.exists():
180+
# the client provided a config path but it doesn't exist
181+
create_empty_pyproject_toml(cfg_file)
182+
elif cfg_file and cfg_file.exists():
183+
try:
184+
parsed_config, _ = parse_config_file(cfg_file)
185+
except Exception as e:
186+
return {"status": "error", "message": f"Failed to parse configuration: {e}"}
175187

176-
try:
177-
parsed_config, _ = parse_config_file(cfg_file)
178-
except Exception as e:
179-
return {"status": "error", "message": f"Failed to parse configuration: {e}"}
180-
_server.show_message_log(f"{parsed_config}", "Info")
181188
setup_info = SetupInfo(
182189
module_root=getattr(cfg, "module_root", ""),
183190
tests_root=getattr(cfg, "tests_root", ""),

0 commit comments

Comments
 (0)