Repository navigation
Expand file tree
/
Copy pathcodex-local-project-sync.command
More file actions
585 lines (515 loc) · 24.7 KB
/
Copy pathcodex-local-project-sync.command
File metadata and controls
585 lines (515 loc) · 24.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
#!/usr/bin/python3
"""Preview or restore existing local Codex project registrations on this Mac."""
import argparse
from contextlib import closing
from datetime import datetime
import fcntl
import hashlib
import json
import os
from pathlib import Path
import plistlib
import re
import sqlite3
import stat
import subprocess
import sys
import tempfile
import time
ACCOUNT = 'electron-account-renderer-state-v1'
PROJECTS = 'local-projects'
MAP = 'app-server-project-id-by-legacy-project-id-by-host'
CHECKPOINT = 'app-server-projects-migration-by-host'
ORDER = 'project-order'
PINS = 'pinned-project-ids'
KEYS = (PROJECTS, MAP, CHECKPOINT, ORDER, PINS)
PROJECT_FIELDS = frozenset({'id', 'name', 'rootPaths', 'createdAt', 'updatedAt'})
STATE_NAME = '.codex-global-state.json'
APP_NAMES = ('ChatGPT', 'Codex')
SUPPORTED = {('26.1103.60933', '25894'), ('26.1103.41825', '25679')}
class RestoreError(Exception):
pass
class PartialError(RestoreError):
pass
def dictionary(value):
if not isinstance(value, dict):
raise RestoreError('项目状态格式不受支持。')
return value
def strings(value):
if not isinstance(value, list) or any(not isinstance(item, str) or not item for item in value):
raise RestoreError('项目列表格式不受支持。')
return value
def record(project_id, project, imported=False):
project = dictionary(project)
if imported and (project_id.startswith('g-p-') or set(project) != PROJECT_FIELDS):
raise RestoreError('旧项目包含未识别的字段。')
if project.get('id') != project_id or not isinstance(project.get('name'), str) or not project['name']:
raise RestoreError('项目 ID 或名称无效。')
paths = strings(project.get('rootPaths'))
if not paths or any(not os.path.isabs(path) or '\0' in path for path in paths):
raise RestoreError('项目根目录无效。')
if imported and any(type(project[key]) is not int or project[key] < 0
for key in ('createdAt', 'updatedAt')):
raise RestoreError('旧项目时间戳无效。')
canonical = tuple(os.path.realpath(path) for path in paths)
if len(set(canonical)) != len(canonical):
raise RestoreError('项目根目录重复。')
return project['name'], tuple(paths), canonical
def project_database(home):
db_path = home / 'state' / 'state_5.sqlite'
try:
with closing(sqlite3.connect(db_path.as_uri() + '?mode=ro', uri=True, timeout=3)) as db:
db.execute('BEGIN')
projects = {key: (name, []) for key, name in db.execute('SELECT id, name FROM projects')}
for key, path in db.execute('SELECT project_id, path FROM project_roots ORDER BY project_id, position'):
if key in projects:
projects[key][1].append(path)
return {key: (name, tuple(paths)) for key, (name, paths) in projects.items()}
except sqlite3.Error:
raise RestoreError('无法只读校验 Codex 项目数据库,数据库可能正被占用或版本不受支持。') from None
def state_file(home):
path = home / STATE_NAME
info = path.lstat()
if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o022:
raise RestoreError('Codex 状态文件类型或权限异常。')
return path
def local_mapping(container, host):
return dictionary(dictionary(container).get(host, {}))
def project_from_db(key, project, aliases, db):
name, paths, canonical = record(key, project, imported=True)
db_id = aliases.get(key, key)
if not isinstance(db_id, str) or db.get(db_id) != (name, paths):
raise RestoreError('项目 ID、名称或根目录与数据库不一致。')
return db_id, canonical
def preference_positions(value):
try:
return {item: index for index, item in reversed(list(enumerate(strings(value))))}
except RestoreError:
return {}
def build_catalog(profiles, db, host):
candidates = {}
aliases_by_db = {}
ids_by_alias = {}
ids_by_root = {}
invalid = 0
for rank, profile in enumerate(profiles.values()):
if profile is None:
continue
try:
projects = dictionary(profile.get(PROJECTS, {}))
aliases = local_mapping(profile.get(MAP, {}), host)
except RestoreError:
invalid += 1
continue
preferences = {key: preference_positions(profile.get(key, [])) for key in (ORDER, PINS)}
for key, project in projects.items():
try:
db_id, canonical = project_from_db(key, project, aliases, db)
except RestoreError:
invalid += 1
continue
candidates.setdefault(db_id, (project, canonical, rank, preferences))
aliases_by_db.setdefault(db_id, set()).add(key)
ids_by_alias.setdefault(key, set()).add(db_id)
for root in canonical:
ids_by_root.setdefault(root, set()).add(db_id)
catalog = {}
for db_id, item in candidates.items():
project, canonical, _, _ = item
key = project['id']
if (len(aliases_by_db[db_id]) == 1 and len(ids_by_alias[key]) == 1
and all(len(ids_by_root[root]) == 1 for root in canonical)):
catalog[db_id] = item
return catalog, invalid, len(candidates) - len(catalog)
def target_patch(target, catalog, db, host):
if target is None:
raise RestoreError('账号项目状态格式不受支持。')
projects = dictionary(target.get(PROJECTS, {}))
mappings = dictionary(target.get(MAP, {}))
aliases = local_mapping(mappings, host)
if any(not isinstance(value, str) or not value for value in aliases.values()):
raise RestoreError('当前项目 ID 映射格式无效。')
checkpoints = dictionary(target.get(CHECKPOINT, {}))
checkpoint = dictionary(checkpoints.get(host, {'version': 1}))
if type(checkpoint.get('version')) is not int or checkpoint['version'] != 1:
raise RestoreError('当前本地项目迁移版本不受支持。')
prior_prefs = {key: strings(target.get(key, [])) for key in (ORDER, PINS)}
current = {key: record(key, project) for key, project in projects.items()}
existing_ids = {aliases.get(key, key) for key in projects}
existing_roots = {root for entry in current.values() for root in entry[2]}
added = {}
imported_map = {}
incoming_prefs = {key: [] for key in (ORDER, PINS)}
collisions = 0
for db_id, (project, canonical, rank, preferences) in catalog.items():
key = project['id']
if key in current:
name, paths, _ = current[key]
if (name, paths) != db[db_id] or aliases.get(key, key) != db_id:
collisions += 1
continue
if (db_id in existing_ids or any(root in existing_roots for root in canonical)
or (key in aliases and aliases[key] != db_id)
or any(alias != key and value == db_id for alias, value in aliases.items())):
collisions += 1
continue
added[key] = project
imported_map[key] = db_id
for pref in (ORDER, PINS):
if key in preferences[pref]:
incoming_prefs[pref].append((rank, preferences[pref][key], key))
if not added:
return {}, 0, collisions
if host not in checkpoints:
for key, project in projects.items():
project_from_db(key, project, aliases, db)
changes = {
PROJECTS: dict(projects, **added),
MAP: dict(mappings, **{host: dict(aliases, **imported_map)}),
}
if host not in checkpoints:
changes[CHECKPOINT] = dict(checkpoints, **{host: {'version': 1, 'projectsMigrated': True}})
for key in (ORDER, PINS):
extra = [project for _, _, project in sorted(incoming_prefs[key]) if project not in prior_prefs[key]]
if extra:
changes[key] = prior_prefs[key] + extra
patch = {key: value for key, value in changes.items() if key not in target or value != target[key]}
return patch, len(added), collisions
def profile_globals(state):
account = dictionary(state.get(ACCOUNT, {}))
owner = account.get('owner')
if not isinstance(owner, str) or not owner:
raise RestoreError('无法识别当前 Codex 账号状态。')
inactive = dictionary(account.get('inactive', {}))
profiles = {None: state}
for key, entry in sorted(inactive.items()):
if key == owner or (isinstance(entry, dict) and 'globals' not in entry):
continue
value = entry.get('globals') if isinstance(entry, dict) else None
profiles[key] = value if isinstance(value, dict) else None
return owner, profiles
def inspect(home):
home = home.resolve()
original = state_file(home).read_bytes()
try:
state = dictionary(json.loads(original))
except (ValueError, UnicodeError):
raise RestoreError('Codex 状态文件无法读取为 JSON。') from None
owner, profiles = profile_globals(state)
host = 'local:' + str(home)
db = project_database(home)
catalog, invalid, ambiguous = build_catalog(profiles, db, host)
patches = {}
summary = {'known': len(profiles), 'catalog': len(catalog), 'added': 0, 'active_added': 0,
'invalid': invalid, 'ambiguous': ambiguous, 'blocked': 0, 'active_blocked': False,
'collisions': 0, 'missing': sum(any(not Path(path).is_dir() for path in project['rootPaths'])
for project, _, _, _ in catalog.values())}
for key, target in profiles.items():
try:
patch, added, collisions = target_patch(target, catalog, db, host)
except RestoreError:
summary['blocked'] += 1
if key is None:
summary['active_blocked'] = True
continue
summary['collisions'] += collisions
if patch:
patches[key] = patch
summary['added'] += added
if key is None:
summary['active_added'] = added
scope = {key: ({field: target[field] for field in KEYS if field in target} if target is not None else None)
for key, target in profiles.items()}
return {'owner': owner, 'state': state, 'original': original, 'patches': patches,
'summary': summary, 'scope': scope}
def revalidate(home, preview):
current = inspect(home)
if current['owner'] != preview['owner']:
raise RestoreError('当前账号已变化,请重新预检。')
if current['scope'] != preview['scope'] or current['patches'] != preview['patches']:
raise RestoreError('账号项目状态、历史项目或数据库已变化,请重新预检。')
return current
def merge_state(state, patches):
merged = dict(state, **patches.get(None, {}))
nested = {key: patch for key, patch in patches.items() if key is not None}
if nested:
account = dict(state[ACCOUNT])
inactive = dict(account['inactive'])
for key, patch in nested.items():
entry = inactive[key]
inactive[key] = dict(entry, globals=dict(entry['globals'], **patch))
account['inactive'] = inactive
merged[ACCOUNT] = account
return merged
def main_processes():
try:
result = subprocess.run(['/bin/ps', '-axo', 'comm='], check=True, capture_output=True,
text=True, timeout=5)
except (OSError, subprocess.SubprocessError, UnicodeError):
raise RestoreError('无法可靠检查 ChatGPT/Codex 主进程。') from None
matches = []
for line in result.stdout.splitlines():
executable = line.strip()
path = Path(executable)
if (executable in APP_NAMES or (path.name in APP_NAMES and path.is_absolute()
and path.parent.name == 'MacOS' and path.parent.parent.name == 'Contents'
and path.parent.parent.parent.suffix.lower() == '.app')):
matches.append(executable)
return matches
def safe_label(label):
return ''.join(char if char.isprintable() else '?' for char in label)
def supported_bundle(executable):
try:
path = Path(executable)
if not path.is_file() or not os.access(path, os.X_OK):
raise ValueError('missing executable')
with (path.parent.parent / 'Info.plist').open('rb') as stream:
info = plistlib.load(stream)
version = str(info['CFBundleShortVersionString'])
build = str(info['CFBundleVersion'])
if info.get('CFBundleIdentifier') != 'com.openai.codex' or info.get('CFBundleExecutable') != path.name:
raise ValueError('invalid bundle')
except (OSError, ValueError, KeyError, TypeError, plistlib.InvalidFileException):
raise RestoreError('无法确认正在运行的 Codex 安装版本。可用 --check 只读检查。') from None
if (version, build) not in SUPPORTED:
version = safe_label(version)
build = safe_label(build)
raise RestoreError(f'当前版本 {version}({build})尚未验证写入。可用 --check 只读检查。')
return version, build
def identify_app(install_dirs):
processes = main_processes()
if processes:
if len(processes) != 1 or not Path(processes[0]).is_absolute():
raise RestoreError('无法唯一确认正在运行的 ChatGPT/Codex 安装。')
executable = processes[0]
return executable, supported_bundle(executable), True
installs = set()
for parent in install_dirs:
for name in APP_NAMES:
bundle = parent / (name + '.app')
if not bundle.is_dir():
continue
contents = bundle.resolve() / 'Contents'
try:
with (contents / 'Info.plist').open('rb') as stream:
info = plistlib.load(stream)
except (OSError, ValueError, plistlib.InvalidFileException):
raise RestoreError('标准安装目录内有无法识别的 ChatGPT/Codex 应用。') from None
if not isinstance(info, dict):
raise RestoreError('标准安装目录内有无法识别的 ChatGPT/Codex 应用。')
if info.get('CFBundleIdentifier') != 'com.openai.codex':
continue
executable = info.get('CFBundleExecutable')
if executable not in APP_NAMES:
raise RestoreError('无法确认标准安装目录内的 Codex 主程序。')
installs.add(str(contents / 'MacOS' / executable))
if len(installs) != 1:
raise RestoreError('无法在标准安装目录确认唯一的 Codex 应用。请打开需要恢复的应用后重试。')
executable = next(iter(installs))
return executable, supported_bundle(executable), False
def guard_app_off():
if main_processes():
raise RestoreError('ChatGPT/Codex 仍在运行或已经重开。请完全退出后重新执行。')
def wait_for_exit():
deadline = time.monotonic() + 900
absent = 0
while time.monotonic() < deadline:
absent = 0 if main_processes() else absent + 1
if absent >= 2:
return
time.sleep(0.8)
raise RestoreError('等待完全退出超时,请重新运行。')
def directory_identity(path, private=False):
try:
if not path.is_absolute() or path.resolve(strict=True) != path:
raise RestoreError('备份目录必须是已存在的绝对路径,且不能含符号链接。')
info = path.lstat()
except (OSError, RuntimeError):
raise RestoreError('无法访问备份目录。') from None
mode = stat.S_IMODE(info.st_mode)
if (not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid()
or mode & 0o022 or mode & 0o300 != 0o300 or not os.access(path, os.W_OK | os.X_OK)
or (private and mode != 0o700)):
raise RestoreError('备份目录需要由当前用户拥有并可写,且不能允许其他用户写入。')
return info.st_dev, info.st_ino
def backup_root(explicit, user_home=None):
if explicit is not None:
directory_identity(explicit)
return explicit
parent = (Path.home() if user_home is None else user_home) / 'Library' / 'Application Support'
directory_identity(parent)
tool = private_subdirectory(parent, 'Codex Local Project Sync')
return private_subdirectory(tool, 'backups')
def fsync_dir(path):
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(fd)
finally:
os.close(fd)
def digest(raw):
return hashlib.sha256(raw).hexdigest()
def private_subdirectory(parent, name):
path = parent / name
try:
path.mkdir(mode=0o700)
except FileExistsError:
pass
else:
fsync_dir(parent)
directory_identity(path, private=True)
return path
def require_no_acl(*paths):
# macOS can inherit ACL grants even when the Unix permission bits are private.
try:
listing = subprocess.run(['/bin/ls', '-ldeb', *map(str, paths)], check=True,
capture_output=True, timeout=5)
except (OSError, subprocess.SubprocessError):
raise RestoreError('无法核验私有备份的 macOS ACL。') from None
if not listing.stdout or listing.stderr:
raise RestoreError('无法核验私有备份的 macOS ACL。')
if re.search(rb'(?m)^[ \t]*[0-9]+:', listing.stdout):
raise RestoreError('备份目录或文件包含 macOS ACL。请换用不会继承 ACL 的备份目录。')
def verify_backup(root, root_identity, backup):
if directory_identity(root) != root_identity:
raise RestoreError('备份目录或所在卷已变化,已停止写入。')
try:
directory = directory_identity(backup.parent, private=True)
info = backup.lstat()
except OSError:
raise RestoreError('无法核验已写入的私有备份。') from None
if (directory[0] != root_identity[0] or info.st_dev != root_identity[0]
or not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid()
or stat.S_IMODE(info.st_mode) != 0o600 or info.st_nlink != 1):
raise RestoreError('备份文件的权限、类型或所在卷发生变化。')
require_no_acl(backup.parent, backup)
return directory, info.st_ino, info.st_size, info.st_mtime_ns
def write_backup(root, scope, patches, original, content):
now = datetime.now().astimezone()
backup_dir = Path(tempfile.mkdtemp(prefix=f'{now:%Y%m%dT%H%M%S}-', dir=root))
directory_identity(backup_dir, private=True)
require_no_acl(backup_dir)
backup = backup_dir / 'project-state-before.json'
prior = []
for profile, patch in patches.items():
fields = scope[profile]
path = [] if profile is None else [ACCOUNT, 'inactive', profile, 'globals']
before = {key: {'present': True, 'value': fields[key]} if key in fields else {'present': False}
for key in patch}
prior.append({'path': path, 'fields': before})
fd = os.open(backup, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0), 0o600)
with os.fdopen(fd, 'w', encoding='utf-8') as stream:
os.fchmod(stream.fileno(), 0o600)
require_no_acl(backup)
json.dump({'created_at': now.isoformat(), 'before_sha256': digest(original),
'after_sha256': digest(content), 'before': prior}, stream, ensure_ascii=False, indent=2)
stream.flush()
os.fsync(stream.fileno())
for directory in (backup_dir, root):
fsync_dir(directory)
return backup
def apply(home, preview, backup_dir, bundle=None):
home = home.resolve()
home_fd = os.open(home, os.O_RDONLY | os.O_DIRECTORY)
try:
try:
fcntl.flock(home_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise RestoreError('已有另一个恢复操作在执行。') from None
guard_app_off()
if bundle and supported_bundle(bundle[0]) != bundle[1]:
raise RestoreError('Codex 安装版本已变化,请重新预检。')
current = revalidate(home, preview)
path = state_file(home)
original = current['original']
patches = current['patches']
if not patches:
raise RestoreError('没有可写入的项目变更。')
merged = merge_state(current['state'], patches)
content = json.dumps(merged, ensure_ascii=False, separators=(',', ':'), allow_nan=False).encode()
root = backup_root(backup_dir)
root_identity = directory_identity(root)
backup = write_backup(root, current['scope'], patches, original, content)
backup_identity = verify_backup(root, root_identity, backup)
fd, temp = tempfile.mkstemp(prefix='.codex-project-restore-', dir=home)
replaced = False
try:
with os.fdopen(fd, 'wb') as stream:
os.fchmod(stream.fileno(), 0o600)
stream.write(content)
stream.flush()
os.fsync(stream.fileno())
if verify_backup(root, root_identity, backup) != backup_identity:
raise RestoreError('备份在恢复期间变化,请重新预检。')
if bundle and supported_bundle(bundle[0]) != bundle[1]:
raise RestoreError('Codex 安装版本已变化,请重新预检。')
guard_app_off()
if state_file(home).read_bytes() != original:
raise RestoreError('状态文件在恢复期间变化,请重新预检。')
os.replace(temp, path)
replaced = True
fsync_dir(home)
if state_file(home).read_bytes() != content:
raise RestoreError('恢复后的本地状态校验失败。')
except BaseException:
if replaced or not os.path.lexists(temp):
raise PartialError(f'已写入状态文件,但未能完成持久化校验。备份位于 {backup}') from None
raise
finally:
if not replaced:
Path(temp).unlink(missing_ok=True)
return backup
finally:
os.close(home_fd)
def print_preview(preview):
summary = preview['summary']
print(f'已有 {summary["known"]} 份账号项目状态,可核验的本地项目共 {summary["catalog"]} 个。')
print(f'本次为 {len(preview["patches"])} 份状态补写 {summary["added"]} 条登记,'
f'其中当前账号补写 {summary["active_added"]} 个项目。')
if summary['missing']:
print(f'{summary["missing"]} 个项目的原目录当前不存在,保留其已核验登记。')
if any(summary[key] for key in ('invalid', 'ambiguous', 'collisions', 'blocked')):
print(f'跳过 {summary["invalid"]} 条无效来源、{summary["ambiguous"]} 个歧义项目、'
f'{summary["collisions"]} 条目标冲突和 {summary["blocked"]} 份不兼容账号状态。')
if summary['active_blocked']:
print('当前账号的项目状态不兼容,本次不会修改该账号。')
def main():
parser = argparse.ArgumentParser(description='将核验通过的本地项目补齐到已有 Codex 账号状态。')
parser.add_argument('--check', action='store_true', help='只读预检,不写入任何状态')
parser.add_argument('--backup-dir', type=Path, metavar='ABSOLUTE_PATH',
help='使用已存在且由当前用户拥有的绝对备份目录')
args = parser.parse_args()
home = Path.home() / '.codex'
try:
if args.backup_dir is not None:
directory_identity(args.backup_dir)
preview = inspect(home)
print_preview(preview)
if args.check:
return 0
if not preview['patches']:
print('本次没有可安全写入的项目变更。')
return 0
if not sys.stdout.isatty():
raise RestoreError('请双击此文件或在终端运行。只读检查可用 --check。')
executable, build, running = identify_app((Path('/Applications'), Path.home() / 'Applications'))
if running:
print('请在 ChatGPT/Codex 内按 Cmd+Q 完全退出。等待终端提示写入完成后再重开应用。', flush=True)
else:
print('ChatGPT/Codex 当前已关闭,正在核对并写入本地项目状态。', flush=True)
wait_for_exit()
backup = apply(home, preview, args.backup_dir, (executable, build))
print(f'已写入并校验 {preview["summary"]["added"]} 条项目登记。'
'请重新打开 ChatGPT/Codex 检查侧栏。')
print(f'恢复前备份:{backup}')
return 0
except (KeyboardInterrupt, EOFError):
print('\n已取消。')
return 1
except RestoreError as error:
print(str(error), file=sys.stderr)
return 2
except (OSError, ValueError, TypeError, KeyError, RecursionError):
print('读取或写入失败,请检查 Codex 本地状态与备份目录后重试。', file=sys.stderr)
return 2
if __name__ == '__main__':
raise SystemExit(main())