1use std::fs::{self, File, OpenOptions};
2use std::io::{Read, Write};
3use std::path::{Path, PathBuf};
4use std::sync::atomic::{AtomicU64, Ordering};
5
6use crate::{
7 FileToolError, FileToolErrorCode, ResolvedExistingPath, ResolvedMutationPath, WorkspaceRoot,
8};
9
10pub const MAX_READ_BYTES: usize = 32 * 1024;
12pub const MAX_WRITE_BYTES: usize = 192 * 1024;
14pub const DEFAULT_READ_LINE_LIMIT: usize = 2_000;
16pub const MAX_READ_LINE_LIMIT: usize = 10_000;
18
19static NEXT_TEMP_ID: AtomicU64 = AtomicU64::new(0);
20
21pub(crate) fn read_utf8(
22 workspace: &WorkspaceRoot,
23 target: &ResolvedExistingPath,
24 max_bytes: usize,
25) -> Result<String, FileToolError> {
26 workspace.revalidate_existing(target)?;
27 let metadata = fs::metadata(target.host_path())
28 .map_err(|_| FileToolError::new(FileToolErrorCode::FilesystemFailure))?;
29 if !metadata.is_file() {
30 return Err(FileToolError::new(FileToolErrorCode::NotAFile));
31 }
32 if metadata.len() > max_bytes as u64 {
33 return Err(FileToolError::new(FileToolErrorCode::TooLarge));
34 }
35
36 let mut file = File::open(target.host_path())
37 .map_err(|_| FileToolError::new(FileToolErrorCode::FilesystemFailure))?;
38 let opened_metadata = file
39 .metadata()
40 .map_err(|_| FileToolError::new(FileToolErrorCode::FilesystemFailure))?;
41 workspace.verify_opened_existing(target, &opened_metadata)?;
42 let capacity = usize::try_from(metadata.len())
43 .unwrap_or(max_bytes)
44 .min(max_bytes);
45 let mut bytes = Vec::with_capacity(capacity);
46 Read::by_ref(&mut file)
47 .take((max_bytes + 1) as u64)
48 .read_to_end(&mut bytes)
49 .map_err(|_| FileToolError::new(FileToolErrorCode::FilesystemFailure))?;
50 if bytes.len() > max_bytes {
51 return Err(FileToolError::new(FileToolErrorCode::TooLarge));
52 }
53 if bytes.contains(&0) {
54 return Err(FileToolError::new(FileToolErrorCode::BinaryFile));
55 }
56 String::from_utf8(bytes).map_err(|_| FileToolError::new(FileToolErrorCode::InvalidUtf8))
57}
58
59pub(crate) fn atomic_write(
60 workspace: &WorkspaceRoot,
61 target: &ResolvedMutationPath,
62 content: &[u8],
63) -> Result<(), FileToolError> {
64 atomic_write_inner(workspace, target, content, None)
65}
66
67pub(crate) fn atomic_write_if_unchanged(
68 workspace: &WorkspaceRoot,
69 existing: &ResolvedExistingPath,
70 target: &ResolvedMutationPath,
71 expected: &str,
72 content: &[u8],
73) -> Result<(), FileToolError> {
74 atomic_write_inner(workspace, target, content, Some((existing, expected)))
75}
76
77fn atomic_write_inner(
78 workspace: &WorkspaceRoot,
79 target: &ResolvedMutationPath,
80 content: &[u8],
81 expected: Option<(&ResolvedExistingPath, &str)>,
82) -> Result<(), FileToolError> {
83 if content.len() > MAX_WRITE_BYTES {
84 return Err(FileToolError::new(FileToolErrorCode::TooLarge));
85 }
86 let parent = target
87 .host_path()
88 .parent()
89 .ok_or_else(|| FileToolError::new(FileToolErrorCode::InvalidPath))?;
90 if !parent.is_dir() {
91 return Err(FileToolError::new(FileToolErrorCode::NotFound));
92 }
93 if target.target_existed_at_resolution() {
94 let metadata = fs::metadata(target.host_path())
95 .map_err(|_| FileToolError::new(FileToolErrorCode::FilesystemFailure))?;
96 if !metadata.is_file() {
97 return Err(FileToolError::new(FileToolErrorCode::NotAFile));
98 }
99 }
100 let temporary = create_temporary(parent)?;
101 let result = write_and_commit(workspace, target, &temporary, content, expected);
102 if result.is_err() {
103 let _ = fs::remove_file(&temporary.path);
104 }
105 result
106}
107
108fn create_temporary(parent: &Path) -> Result<TemporaryFile, FileToolError> {
109 for _ in 0..32 {
110 let id = NEXT_TEMP_ID.fetch_add(1, Ordering::Relaxed);
111 let path = parent.join(format!(".tea-tmp-{}-{id}", std::process::id()));
112 match open_new_temporary(&path) {
113 Ok(file) => return Ok(TemporaryFile { path, file }),
114 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
115 Err(_) => return Err(FileToolError::new(FileToolErrorCode::FilesystemFailure)),
116 }
117 }
118 Err(FileToolError::new(FileToolErrorCode::FilesystemFailure))
119}
120
121fn open_new_temporary(path: &Path) -> std::io::Result<File> {
122 let mut options = OpenOptions::new();
123 options.write(true).create_new(true);
124 #[cfg(unix)]
125 {
126 use std::os::unix::fs::OpenOptionsExt;
127 options.mode(0o600);
128 }
129 options.open(path)
130}
131
132fn write_and_commit(
133 workspace: &WorkspaceRoot,
134 target: &ResolvedMutationPath,
135 temporary: &TemporaryFile,
136 content: &[u8],
137 expected: Option<(&ResolvedExistingPath, &str)>,
138) -> Result<(), FileToolError> {
139 if target.target_existed_at_resolution() {
140 let permissions = fs::metadata(target.host_path())
141 .map_err(|_| FileToolError::new(FileToolErrorCode::FilesystemFailure))?
142 .permissions();
143 temporary
144 .file
145 .set_permissions(permissions)
146 .map_err(|_| FileToolError::new(FileToolErrorCode::FilesystemFailure))?;
147 }
148 (&temporary.file)
149 .write_all(content)
150 .map_err(|_| FileToolError::new(FileToolErrorCode::FilesystemFailure))?;
151 temporary
152 .file
153 .sync_all()
154 .map_err(|_| FileToolError::new(FileToolErrorCode::FilesystemFailure))?;
155 if let Some((existing, expected)) = expected {
156 let current = read_utf8(workspace, existing, MAX_WRITE_BYTES)?;
157 if current != expected {
158 return Err(FileToolError::new(FileToolErrorCode::PathChanged));
159 }
160 }
161 workspace.revalidate_mutation(target)?;
162 fs::rename(&temporary.path, target.host_path())
163 .map_err(|_| FileToolError::new(FileToolErrorCode::AtomicCommitFailed))?;
164 sync_parent(target.host_path().parent());
165 Ok(())
166}
167
168fn sync_parent(parent: Option<&Path>) {
169 #[cfg(unix)]
170 if let Some(parent) = parent
171 && let Ok(directory) = File::open(parent)
172 {
173 let _ = directory.sync_all();
174 }
175 #[cfg(not(unix))]
176 let _ = parent;
177}
178
179struct TemporaryFile {
180 path: PathBuf,
181 file: File,
182}