MCPcopy Create free account
hub / github.com/FSoft-AI4Code/CodeWiki / safe_write

Function safe_write

codewiki/cli/utils/fs.py:60–86  ·  view source on GitHub ↗

Safely write content to a file using atomic write (temp file + rename). Args: path: File path content: Content to write encoding: File encoding Raises: FileSystemError: If write fails

(path: Path, content: str, encoding: str = "utf-8")

Source from the content-addressed store, hash-verified

58
59def safe_write(path: Path, content: str, encoding: str = "utf-8"):
60 """
61 Safely write content to a file using atomic write (temp file + rename).
62
63 Args:
64 path: File path
65 content: Content to write
66 encoding: File encoding
67
68 Raises:
69 FileSystemError: If write fails
70 """
71 path = Path(path).expanduser().resolve()
72 temp_path = path.with_suffix(path.suffix + ".tmp")
73
74 try:
75 # Write to temp file
76 with open(temp_path, "w", encoding=encoding) as f:
77 f.write(content)
78
79 # Atomic rename
80 temp_path.replace(path)
81 except Exception as e:
82 # Clean up temp file if it exists
83 if temp_path.exists():
84 temp_path.unlink()
85 raise FileSystemError(f"Cannot write to {path}: {e}")
86
87
88def safe_read(path: Path, encoding: str = "utf-8") -> str:
89 """

Callers 3

generateMethod · 0.90
_save_api_key_to_fileMethod · 0.90
saveMethod · 0.90

Calls 2

FileSystemErrorClass · 0.90
resolveMethod · 0.80

Tested by

no test coverage detected