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

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