leetcode-local-cli 0.7.2__py3-none-any.whl → 0.8.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,6 +6,13 @@ from enum import Enum
6
6
  from getpass import getpass
7
7
  from pathlib import Path
8
8
 
9
+ from leetcode_local_cli.safe_files import (
10
+ SafeFileError,
11
+ atomic_write_text,
12
+ ensure_regular_directory,
13
+ validate_regular_file_target,
14
+ )
15
+
9
16
 
10
17
  with warnings.catch_warnings():
11
18
  # wmi 1.5.1, imported transitively by browser-cookie3 on Windows, contains
@@ -23,11 +30,6 @@ LC_DOMAIN = "leetcode.cn"
23
30
  BROWSER_LOADERS = [("Chrome", browser_cookie3.chrome)]
24
31
 
25
32
  REQUIRED_COOKIE_NAMES = ("LEETCODE_SESSION", "csrftoken")
26
- PROJECT_ROOT = Path.cwd()
27
- SESSION_DIR = PROJECT_ROOT / ".leetcode_local_cli"
28
- SESSION_FILE = SESSION_DIR / "session.json"
29
- LEGACY_SESSION_DIR = PROJECT_ROOT / ".aether_lc"
30
- LEGACY_SESSION_FILE = LEGACY_SESSION_DIR / "session.json"
31
33
 
32
34
 
33
35
  class SessionFileStatus(str, Enum):
@@ -51,31 +53,6 @@ class SessionFileError(OSError):
51
53
  pass
52
54
 
53
55
 
54
- def _resolve_default_session_file() -> Path:
55
- """Move the pre-v0.7 session to the canonical directory when possible."""
56
- if SESSION_FILE.exists() or not LEGACY_SESSION_FILE.exists():
57
- return SESSION_FILE
58
-
59
- try:
60
- SESSION_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
61
- if os.name != "nt":
62
- os.chmod(SESSION_DIR, 0o700)
63
- LEGACY_SESSION_FILE.replace(SESSION_FILE)
64
- if os.name != "nt":
65
- os.chmod(SESSION_FILE, 0o600)
66
- try:
67
- LEGACY_SESSION_DIR.rmdir()
68
- except OSError:
69
- # Preserve a non-empty legacy directory instead of deleting unrelated data.
70
- pass
71
- except OSError:
72
- if SESSION_FILE.exists():
73
- return SESSION_FILE
74
- return LEGACY_SESSION_FILE
75
-
76
- return SESSION_FILE
77
-
78
-
79
56
  def get_cookies_from_browser() -> tuple[str, dict[str, str]] | None:
80
57
  for browser_name, loader in BROWSER_LOADERS:
81
58
  try:
@@ -131,51 +108,44 @@ def get_cookies_from_input() -> dict[str, str] | None:
131
108
  return parse_cookie_header(getpass("请粘贴 Cookie(输入内容不会回显):\n"))
132
109
 
133
110
 
134
- def save_session(session_data: dict, path: Path | None = None) -> None:
135
- if path is None:
136
- _resolve_default_session_file()
137
- file_path = path or SESSION_FILE
138
- temporary_file = file_path.with_suffix(f"{file_path.suffix}.tmp")
111
+ def save_session(session_data: dict, path: Path) -> None:
139
112
  try:
140
- file_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
141
- if path is None and os.name != "nt":
142
- os.chmod(file_path.parent, 0o700)
143
- descriptor = os.open(
144
- temporary_file,
145
- os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
146
- 0o600,
113
+ content = json.dumps(session_data, indent=4, ensure_ascii=False)
114
+ ensure_regular_directory(
115
+ path.parent,
116
+ label="Session 目录",
117
+ mode=0o700,
118
+ )
119
+ if os.name != "nt":
120
+ os.chmod(path.parent, 0o700)
121
+ atomic_write_text(
122
+ path,
123
+ content,
124
+ label="Session 文件",
125
+ mode=0o600,
147
126
  )
148
- with os.fdopen(descriptor, "w", encoding="utf-8") as file:
149
- json.dump(session_data, file, indent=4, ensure_ascii=False)
150
- os.chmod(temporary_file, 0o600)
151
- temporary_file.replace(file_path)
152
- os.chmod(file_path, 0o600)
153
127
  except (OSError, TypeError, ValueError) as exc:
154
- try:
155
- temporary_file.unlink(missing_ok=True)
156
- except OSError:
157
- pass
158
128
  raise SessionFileError("无法保存 Session 文件") from exc
159
129
 
160
130
 
161
- def load_session() -> dict | None:
162
- file_path = _resolve_default_session_file()
131
+ def load_session(path: Path) -> dict | None:
163
132
  try:
164
- with open(file_path, "r", encoding="utf-8") as f:
133
+ if validate_regular_file_target(path, label="Session 文件") is None:
134
+ return None
135
+ with path.open("r", encoding="utf-8") as f:
165
136
  return json.load(f)
166
137
  except FileNotFoundError:
167
138
  return None
168
139
  except json.JSONDecodeError:
169
140
  return None
170
- except OSError as exc:
141
+ except (OSError, SafeFileError) as exc:
171
142
  raise SessionFileError("无法读取 Session 文件") from exc
172
143
 
173
144
 
174
- def inspect_session_file(path: Path | None = None) -> SessionFileInspection:
175
- if path is None:
176
- path = _resolve_default_session_file()
177
-
145
+ def inspect_session_file(path: Path) -> SessionFileInspection:
178
146
  try:
147
+ if validate_regular_file_target(path, label="Session 文件") is None:
148
+ return SessionFileInspection(status=SessionFileStatus.MISSING)
179
149
  content = path.read_text(encoding="utf-8")
180
150
 
181
151
  except FileNotFoundError:
@@ -183,7 +153,7 @@ def inspect_session_file(path: Path | None = None) -> SessionFileInspection:
183
153
  status=SessionFileStatus.MISSING,
184
154
  )
185
155
 
186
- except OSError:
156
+ except (OSError, SafeFileError):
187
157
  return SessionFileInspection(
188
158
  status=SessionFileStatus.READ_ERROR,
189
159
  )
leetcode_local_cli/cli.py CHANGED
@@ -1,7 +1,8 @@
1
1
  import sys
2
+ from pathlib import Path
2
3
  from typing import Annotated
3
4
 
4
- from typer import Exit, Option, Typer, echo
5
+ from typer import Argument, Exit, Option, Typer, confirm, echo, prompt
5
6
 
6
7
  from leetcode_local_cli.auth import (
7
8
  SessionFileError,
@@ -10,7 +11,20 @@ from leetcode_local_cli.auth import (
10
11
  save_session,
11
12
  )
12
13
  from leetcode_local_cli.client import ClientErrorKind, LeetCodeClient
14
+ from leetcode_local_cli.config import (
15
+ ConfigError,
16
+ initialize_workspace,
17
+ load_user_config,
18
+ resolve_app_paths,
19
+ )
20
+ from leetcode_local_cli.paths import (
21
+ APP_DIRECTORY_NAME,
22
+ AppPaths,
23
+ get_user_config_file,
24
+ normalize_workspace_path,
25
+ )
13
26
  from leetcode_local_cli.ui import (
27
+ info,
14
28
  loading,
15
29
  render_doctor_report,
16
30
  render_submission_result,
@@ -33,6 +47,7 @@ from leetcode_local_cli.service import (
33
47
  from leetcode_local_cli.workspace import (
34
48
  ProblemMetadata,
35
49
  SolutionFileStatus,
50
+ WorkspaceError,
36
51
  inspect_solution_file,
37
52
  run_solution_file,
38
53
  write_solution_file,
@@ -77,8 +92,72 @@ def main(
77
92
  """力扣中文站本地化刷题 CLI 工具。"""
78
93
 
79
94
 
95
+ def _require_app_paths() -> AppPaths:
96
+ try:
97
+ return resolve_app_paths()
98
+ except ConfigError as exc:
99
+ error(str(exc))
100
+ raise Exit(1) from exc
101
+
102
+
103
+ @app.command("init")
104
+ def init_workspace(
105
+ path: Annotated[
106
+ Path | None,
107
+ Argument(help="工作区完整路径;省略时交互输入父目录"),
108
+ ] = None,
109
+ yes: Annotated[
110
+ bool,
111
+ Option("--yes", help="使用显式路径初始化并跳过交互确认"),
112
+ ] = False,
113
+ ) -> None:
114
+ """配置默认工作区,并安全创建工作区基础文件。"""
115
+ config_file = get_user_config_file()
116
+ if path is None:
117
+ try:
118
+ existing_config = load_user_config(config_file)
119
+ if existing_config is not None:
120
+ existing_paths = resolve_app_paths(config_file)
121
+ success(f"继续使用现有工作区:{existing_paths.workspace_root}")
122
+ return
123
+ except ConfigError as exc:
124
+ error(str(exc))
125
+ raise Exit(1) from exc
126
+
127
+ if yes:
128
+ error("--yes 必须与工作区完整路径一起使用")
129
+ raise Exit(1)
130
+ parent_value = prompt("请输入工作区父目录").strip()
131
+ if not parent_value:
132
+ error("工作区父目录不能为空")
133
+ raise Exit(1)
134
+ workspace_root = normalize_workspace_path(parent_value) / APP_DIRECTORY_NAME
135
+ else:
136
+ workspace_root = normalize_workspace_path(path)
137
+
138
+ info(f"工作区将配置为:{workspace_root}")
139
+ if not yes and not confirm("确认继续?"):
140
+ warning("已取消工作区配置")
141
+ return
142
+
143
+ try:
144
+ result = initialize_workspace(
145
+ workspace_root,
146
+ user_config_file=config_file,
147
+ )
148
+ except ConfigError as exc:
149
+ error(str(exc))
150
+ raise Exit(1) from exc
151
+
152
+ if result.reused:
153
+ success(f"工作区已配置,现有文件保持不变:{result.paths.workspace_root}")
154
+ else:
155
+ success(f"工作区配置完成:{result.paths.workspace_root}")
156
+
157
+
80
158
  @app.command()
81
159
  def login() -> None:
160
+ paths = _require_app_paths()
82
161
  with loading("正在读取浏览器 Cookie..."):
83
162
  browser_result = get_cookies_from_browser()
84
163
  if not browser_result:
@@ -107,7 +186,8 @@ def login() -> None:
107
186
  "source": source,
108
187
  "username": username,
109
188
  "cookies": cookies,
110
- }
189
+ },
190
+ paths.session_file,
111
191
  )
112
192
  except SessionFileError as exc:
113
193
  error(str(exc))
@@ -120,32 +200,40 @@ def login() -> None:
120
200
 
121
201
  @app.command()
122
202
  def status() -> None:
123
- user_status = get_user_status()
203
+ user_status = get_user_status(_require_app_paths())
124
204
  username = user_status.get("username", "未知用户")
125
205
  success(f"在线状态: 当前账号 {username}")
126
206
 
127
207
 
128
208
  @app.command()
129
209
  def profile() -> None:
130
- account_profile = get_account_profile()
210
+ account_profile = get_account_profile(_require_app_paths())
131
211
  render_profile(account_profile)
132
212
 
133
213
 
134
214
  @app.command()
135
215
  def get(question_id: str) -> None:
136
- problem_detail = get_problem_detail_by_question_id(question_id)
216
+ problem_detail = get_problem_detail_by_question_id(
217
+ _require_app_paths(),
218
+ question_id,
219
+ )
137
220
  render_problem_detail(problem_detail)
138
221
 
139
222
 
140
223
  @app.command()
141
224
  def show(limit: int = 50, skip: int = 0) -> None:
142
- problem_summaries = get_problem_summaries(limit=limit, skip=skip)
225
+ problem_summaries = get_problem_summaries(
226
+ _require_app_paths(),
227
+ limit=limit,
228
+ skip=skip,
229
+ )
143
230
  render_problem_list(problem_summaries)
144
231
 
145
232
 
146
233
  @app.command()
147
234
  def solve(question_id: str) -> None:
148
- problem_detail = get_problem_detail_by_question_id(question_id)
235
+ paths = _require_app_paths()
236
+ problem_detail = get_problem_detail_by_question_id(paths, question_id)
149
237
  render_problem_detail(problem_detail)
150
238
  if not problem_detail.python_code:
151
239
  error("题目未提供 Python3 代码模板,无法生成 solution.py")
@@ -158,20 +246,26 @@ def solve(question_id: str) -> None:
158
246
  ):
159
247
  error("题目元信息不完整,无法生成可提交的 solution.py")
160
248
  raise Exit(1)
161
- write_solution_file(
162
- problem_detail.python_code,
163
- ProblemMetadata(
164
- problem_id=problem_detail.question_id,
165
- submit_question_id=problem_detail.submit_question_id,
166
- title=problem_detail.title,
167
- title_slug=problem_detail.title_slug,
168
- ),
169
- )
249
+ try:
250
+ write_solution_file(
251
+ paths.solution_file,
252
+ problem_detail.python_code,
253
+ ProblemMetadata(
254
+ problem_id=problem_detail.question_id,
255
+ submit_question_id=problem_detail.submit_question_id,
256
+ title=problem_detail.title,
257
+ title_slug=problem_detail.title_slug,
258
+ ),
259
+ )
260
+ except WorkspaceError as exc:
261
+ error(str(exc))
262
+ raise Exit(1)
170
263
 
171
264
 
172
265
  @app.command()
173
266
  def test() -> None:
174
- inspection = inspect_solution_file()
267
+ paths = _require_app_paths()
268
+ inspection = inspect_solution_file(paths.solution_file)
175
269
  match inspection.status:
176
270
  case SolutionFileStatus.MISSING:
177
271
  error("未找到 solution.py,请先执行 lc solve <题号>")
@@ -191,7 +285,7 @@ def test() -> None:
191
285
  error(f"solution.py 存在 Python 语法错误({line})")
192
286
  raise Exit(1)
193
287
 
194
- result = run_solution_file()
288
+ result = run_solution_file(paths.solution_file)
195
289
  if result.returncode:
196
290
  error("本地测试失败")
197
291
  raise Exit(result.returncode)
@@ -208,8 +302,9 @@ def doctor(
208
302
  ),
209
303
  ] = False,
210
304
  ) -> None:
305
+ paths = _require_app_paths()
211
306
  with loading("正在检查本地环境与 LeetCode 连接..."):
212
- report = get_doctor_report(run_solution=run_solution)
307
+ report = get_doctor_report(paths, run_solution=run_solution)
213
308
  render_doctor_report(report)
214
309
  if not report.ok:
215
310
  raise Exit(1)
@@ -217,7 +312,7 @@ def doctor(
217
312
 
218
313
  @app.command()
219
314
  def submit() -> None:
220
- result = submit_current_solution()
315
+ result = submit_current_solution(_require_app_paths())
221
316
  render_submission_result(result)
222
317
 
223
318
 
@@ -0,0 +1,317 @@
1
+ from dataclasses import dataclass
2
+ import json
3
+ from pathlib import Path
4
+ import tomllib
5
+
6
+ from leetcode_local_cli.paths import (
7
+ AppPaths,
8
+ get_user_config_file,
9
+ normalize_workspace_path,
10
+ )
11
+ from leetcode_local_cli.safe_files import (
12
+ SafeFileError,
13
+ atomic_write_text,
14
+ create_empty_regular_file,
15
+ create_text_file,
16
+ ensure_regular_directory,
17
+ validate_directory_target,
18
+ validate_regular_file_target,
19
+ )
20
+
21
+
22
+ CONFIG_VERSION = 1
23
+ SUPPORTED_SITE = "cn"
24
+ SUPPORTED_LANGUAGE = "python3"
25
+
26
+
27
+ class ConfigError(ValueError):
28
+ """Configuration is missing, malformed, unsupported, or unsafe."""
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class UserConfig:
33
+ version: int
34
+ default_workspace: Path
35
+ default_site: str
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class WorkspaceConfig:
40
+ version: int
41
+ site: str
42
+ language: str
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class WorkspaceInitResult:
47
+ paths: AppPaths
48
+ workspace_created: bool
49
+ workspace_config_created: bool
50
+ solution_created: bool
51
+
52
+ @property
53
+ def reused(self) -> bool:
54
+ return not any(
55
+ (
56
+ self.workspace_created,
57
+ self.workspace_config_created,
58
+ self.solution_created,
59
+ )
60
+ )
61
+
62
+
63
+ def _load_toml(path: Path, *, label: str) -> dict[str, object] | None:
64
+ try:
65
+ target_status = validate_regular_file_target(path, label=label)
66
+ except SafeFileError as exc:
67
+ raise ConfigError(str(exc)) from exc
68
+ if target_status is None:
69
+ return None
70
+
71
+ try:
72
+ with path.open("rb") as file:
73
+ return tomllib.load(file)
74
+ except tomllib.TOMLDecodeError as exc:
75
+ raise ConfigError(f"{label}不是有效的 TOML") from exc
76
+ except (OSError, UnicodeError) as exc:
77
+ raise ConfigError(f"无法读取{label}") from exc
78
+
79
+
80
+ def _require_exact_keys(
81
+ data: dict[str, object],
82
+ expected_keys: set[str],
83
+ *,
84
+ label: str,
85
+ ) -> None:
86
+ actual_keys = set(data)
87
+ if actual_keys == expected_keys:
88
+ return
89
+ missing_keys = sorted(expected_keys - actual_keys)
90
+ unknown_keys = sorted(actual_keys - expected_keys)
91
+ details: list[str] = []
92
+ if missing_keys:
93
+ details.append(f"缺少字段:{'、'.join(missing_keys)}")
94
+ if unknown_keys:
95
+ details.append(f"未知字段:{'、'.join(unknown_keys)}")
96
+ raise ConfigError(f"{label}结构无效({';'.join(details)})")
97
+
98
+
99
+ def _require_version(data: dict[str, object], *, label: str) -> int:
100
+ version = data.get("version")
101
+ if type(version) is not int:
102
+ raise ConfigError(f"{label}中的 version 必须是整数")
103
+ if version != CONFIG_VERSION:
104
+ raise ConfigError(
105
+ f"{label}版本不受支持:{version},当前支持版本为 {CONFIG_VERSION}"
106
+ )
107
+ return version
108
+
109
+
110
+ def _require_string(
111
+ data: dict[str, object],
112
+ key: str,
113
+ *,
114
+ label: str,
115
+ ) -> str:
116
+ value = data.get(key)
117
+ if not isinstance(value, str) or not value.strip():
118
+ raise ConfigError(f"{label}中的 {key} 必须是非空字符串")
119
+ return value
120
+
121
+
122
+ def load_user_config(path: Path) -> UserConfig | None:
123
+ data = _load_toml(path, label="用户配置文件")
124
+ if data is None:
125
+ return None
126
+ _require_exact_keys(
127
+ data,
128
+ {"version", "default_workspace", "default_site"},
129
+ label="用户配置文件",
130
+ )
131
+ version = _require_version(data, label="用户配置文件")
132
+ workspace_value = _require_string(
133
+ data,
134
+ "default_workspace",
135
+ label="用户配置文件",
136
+ )
137
+ default_site = _require_string(
138
+ data,
139
+ "default_site",
140
+ label="用户配置文件",
141
+ )
142
+ workspace_path = Path(workspace_value).expanduser()
143
+ if not workspace_path.is_absolute():
144
+ raise ConfigError("default_workspace 必须是绝对路径")
145
+ if default_site != SUPPORTED_SITE:
146
+ raise ConfigError(f"当前不支持站点:{default_site}")
147
+ return UserConfig(
148
+ version=version,
149
+ default_workspace=normalize_workspace_path(workspace_path),
150
+ default_site=default_site,
151
+ )
152
+
153
+
154
+ def load_workspace_config(path: Path) -> WorkspaceConfig | None:
155
+ data = _load_toml(path, label="工作区配置文件")
156
+ if data is None:
157
+ return None
158
+ _require_exact_keys(
159
+ data,
160
+ {"version", "site", "language"},
161
+ label="工作区配置文件",
162
+ )
163
+ version = _require_version(data, label="工作区配置文件")
164
+ site = _require_string(data, "site", label="工作区配置文件")
165
+ language = _require_string(data, "language", label="工作区配置文件")
166
+ if site != SUPPORTED_SITE:
167
+ raise ConfigError(f"当前不支持站点:{site}")
168
+ if language != SUPPORTED_LANGUAGE:
169
+ raise ConfigError(f"当前不支持语言:{language}")
170
+ return WorkspaceConfig(version=version, site=site, language=language)
171
+
172
+
173
+ def resolve_app_paths(user_config_file: Path | None = None) -> AppPaths:
174
+ config_file = (
175
+ get_user_config_file()
176
+ if user_config_file is None
177
+ else normalize_workspace_path(user_config_file)
178
+ )
179
+ user_config = load_user_config(config_file)
180
+ if user_config is None:
181
+ raise ConfigError("尚未配置工作区,请先执行 lc init")
182
+ paths = AppPaths.from_workspace(
183
+ user_config.default_workspace,
184
+ user_config_file=config_file,
185
+ )
186
+ try:
187
+ workspace_status = validate_directory_target(
188
+ paths.workspace_root,
189
+ label="默认工作区目录",
190
+ )
191
+ except SafeFileError as exc:
192
+ raise ConfigError(str(exc)) from exc
193
+ if workspace_status is None:
194
+ raise ConfigError("默认工作区目录不存在,请执行 lc init <完整路径> 重新配置")
195
+ workspace_config = load_workspace_config(paths.workspace_config_file)
196
+ if workspace_config is None:
197
+ raise ConfigError("默认目录缺少工作区配置,请执行 lc init <完整路径> 重新配置")
198
+ if workspace_config.site != user_config.default_site:
199
+ raise ConfigError("用户配置与工作区配置的站点不一致")
200
+ return paths
201
+
202
+
203
+ def _toml_string(value: str) -> str:
204
+ return json.dumps(value, ensure_ascii=False)
205
+
206
+
207
+ def _serialize_user_config(config: UserConfig) -> str:
208
+ return (
209
+ f"version = {config.version}\n"
210
+ f"default_workspace = {_toml_string(config.default_workspace.as_posix())}\n"
211
+ f"default_site = {_toml_string(config.default_site)}\n"
212
+ )
213
+
214
+
215
+ def _serialize_workspace_config(config: WorkspaceConfig) -> str:
216
+ return (
217
+ f"version = {config.version}\n"
218
+ f"site = {_toml_string(config.site)}\n"
219
+ f"language = {_toml_string(config.language)}\n"
220
+ )
221
+
222
+
223
+ def initialize_workspace(
224
+ workspace_root: str | Path,
225
+ *,
226
+ user_config_file: Path | None = None,
227
+ ) -> WorkspaceInitResult:
228
+ config_file = (
229
+ get_user_config_file()
230
+ if user_config_file is None
231
+ else normalize_workspace_path(user_config_file)
232
+ )
233
+ load_user_config(config_file)
234
+ paths = AppPaths.from_workspace(
235
+ workspace_root,
236
+ user_config_file=config_file,
237
+ )
238
+
239
+ workspace_created = False
240
+ workspace_config_created = False
241
+ solution_created = False
242
+ try:
243
+ workspace_created = ensure_regular_directory(
244
+ paths.workspace_root,
245
+ label="工作区目录",
246
+ )
247
+ existing_workspace_config = load_workspace_config(paths.workspace_config_file)
248
+ if existing_workspace_config is None:
249
+ workspace_config_created = create_text_file(
250
+ paths.workspace_config_file,
251
+ _serialize_workspace_config(
252
+ WorkspaceConfig(
253
+ version=CONFIG_VERSION,
254
+ site=SUPPORTED_SITE,
255
+ language=SUPPORTED_LANGUAGE,
256
+ )
257
+ ),
258
+ label="工作区配置文件",
259
+ )
260
+ elif (
261
+ existing_workspace_config.site != SUPPORTED_SITE
262
+ or existing_workspace_config.language != SUPPORTED_LANGUAGE
263
+ ):
264
+ raise ConfigError("现有工作区配置与当前版本不兼容")
265
+
266
+ solution_created = create_empty_regular_file(
267
+ paths.solution_file,
268
+ label="solution.py",
269
+ )
270
+ ensure_regular_directory(
271
+ config_file.parent,
272
+ label="用户配置目录",
273
+ mode=0o700,
274
+ )
275
+ atomic_write_text(
276
+ config_file,
277
+ _serialize_user_config(
278
+ UserConfig(
279
+ version=CONFIG_VERSION,
280
+ default_workspace=paths.workspace_root,
281
+ default_site=SUPPORTED_SITE,
282
+ )
283
+ ),
284
+ label="用户配置文件",
285
+ mode=0o600,
286
+ )
287
+ except (SafeFileError, ConfigError) as exc:
288
+ if solution_created:
289
+ _remove_created_file(paths.solution_file)
290
+ if workspace_config_created:
291
+ _remove_created_file(paths.workspace_config_file)
292
+ if workspace_created:
293
+ _remove_created_directory(paths.workspace_root)
294
+ if isinstance(exc, ConfigError):
295
+ raise
296
+ raise ConfigError(str(exc)) from exc
297
+
298
+ return WorkspaceInitResult(
299
+ paths=paths,
300
+ workspace_created=workspace_created,
301
+ workspace_config_created=workspace_config_created,
302
+ solution_created=solution_created,
303
+ )
304
+
305
+
306
+ def _remove_created_file(path: Path) -> None:
307
+ try:
308
+ path.unlink(missing_ok=True)
309
+ except OSError:
310
+ pass
311
+
312
+
313
+ def _remove_created_directory(path: Path) -> None:
314
+ try:
315
+ path.rmdir()
316
+ except OSError:
317
+ pass