1use anyhow::{Context, Result};
2use base64::{engine::general_purpose, Engine as _};
3use std::fs;
4use std::path::{Path, PathBuf};
5
6pub fn read_file(path: &str) -> Result<String> {
8 let path = normalize_path_for_read(path)?;
9
10 validate_path_for_read(&path)?;
12
13 fs::read_to_string(&path).with_context(|| format!("Failed to read file: {}", path.display()))
14}
15
16pub async fn read_file_async(path: String) -> Result<String> {
18 tokio::task::spawn_blocking(move || {
19 read_file(&path)
20 })
21 .await
22 .context("Failed to spawn blocking task for file read")?
23}
24
25pub fn is_binary_file(path: &str) -> bool {
27 let path = Path::new(path);
28 if let Some(ext) = path.extension() {
29 let ext_str = ext.to_string_lossy().to_lowercase();
30 matches!(
31 ext_str.as_str(),
32 "pdf" | "png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "ico" | "tiff"
33 )
34 } else {
35 false
36 }
37}
38
39pub fn read_binary_file(path: &str) -> Result<String> {
41 let path = normalize_path_for_read(path)?;
42
43 validate_path_for_read(&path)?;
45
46 let bytes = fs::read(&path)
47 .with_context(|| format!("Failed to read binary file: {}", path.display()))?;
48
49 Ok(general_purpose::STANDARD.encode(&bytes))
50}
51
52pub fn write_file(path: &str, content: &str) -> Result<()> {
54 let path = normalize_path(path)?;
55
56 validate_path(&path)?;
58
59 if let Some(parent) = path.parent() {
61 fs::create_dir_all(parent).with_context(|| {
62 format!(
63 "Failed to create parent directories for: {}",
64 path.display()
65 )
66 })?;
67 }
68
69 if path.exists() {
71 create_timestamped_backup(&path)?;
72 }
73
74 let temp_path = format!("{}.tmp.{}", path.display(), std::process::id());
76 let temp_path = std::path::PathBuf::from(&temp_path);
77
78 fs::write(&temp_path, content).with_context(|| {
80 format!("Failed to write to temporary file: {}", temp_path.display())
81 })?;
82
83 fs::rename(&temp_path, &path).with_context(|| {
85 format!(
86 "Failed to finalize write to: {} (temp file: {})",
87 path.display(),
88 temp_path.display()
89 )
90 })?;
91
92 Ok(())
93}
94
95fn create_timestamped_backup(path: &std::path::Path) -> Result<()> {
98 let timestamp = chrono::Local::now().format("%Y-%m-%d-%H-%M-%S");
99 let backup_path = format!("{}.backup.{}", path.display(), timestamp);
100
101 fs::copy(path, &backup_path).with_context(|| {
102 format!(
103 "Failed to create backup of: {} to {}",
104 path.display(),
105 backup_path
106 )
107 })?;
108
109 Ok(())
110}
111
112pub fn edit_file(path: &str, old_string: &str, new_string: &str) -> Result<String> {
115 let path = normalize_path(path)?;
116
117 validate_path(&path)?;
119
120 let content = fs::read_to_string(&path)
122 .with_context(|| format!("Failed to read file for editing: {}", path.display()))?;
123
124 let match_count = content.matches(old_string).count();
126 if match_count == 0 {
127 anyhow::bail!(
128 "old_string not found in {}. Make sure the text matches exactly, including whitespace and indentation.",
129 path.display()
130 );
131 }
132 if match_count > 1 {
133 anyhow::bail!(
134 "old_string appears {} times in {}. It must be unique. Include more surrounding context to make it unique.",
135 match_count,
136 path.display()
137 );
138 }
139
140 let new_content = content.replacen(old_string, new_string, 1);
142
143 create_timestamped_backup(&path)?;
145
146 let temp_path = format!("{}.tmp.{}", path.display(), std::process::id());
148 let temp_path = std::path::PathBuf::from(&temp_path);
149
150 fs::write(&temp_path, &new_content).with_context(|| {
151 format!("Failed to write to temporary file: {}", temp_path.display())
152 })?;
153
154 fs::rename(&temp_path, &path).with_context(|| {
155 format!(
156 "Failed to finalize edit to: {} (temp file: {})",
157 path.display(),
158 temp_path.display()
159 )
160 })?;
161
162 let diff = generate_diff(&content, &new_content, old_string, new_string);
164 Ok(diff)
165}
166
167fn generate_diff(old_content: &str, new_content: &str, old_string: &str, new_string: &str) -> String {
169 let old_lines: Vec<&str> = old_content.lines().collect();
170 let new_lines: Vec<&str> = new_content.lines().collect();
171
172 let removed_count = old_string.lines().count();
173 let added_count = new_string.lines().count();
174
175 let prefix_len = old_content[..old_content.find(old_string).unwrap_or(0)].len();
177 let change_start_line = old_content[..prefix_len].matches('\n').count();
178
179 let context_lines = 3;
180 let diff_start = change_start_line.saturating_sub(context_lines);
181 let new_diff_end = (change_start_line + added_count + context_lines).min(new_lines.len());
182
183 let mut output = String::new();
184 output.push_str(&format!("Added {} lines, removed {} lines\n", added_count, removed_count));
185
186 for i in diff_start..change_start_line {
188 if i < old_lines.len() {
189 output.push_str(&format!("{:>4} {}\n", i + 1, old_lines[i]));
190 }
191 }
192
193 for i in 0..removed_count {
195 let line_num = change_start_line + i;
196 if line_num < old_lines.len() {
197 output.push_str(&format!("{:>4} - {}\n", line_num + 1, old_lines[line_num]));
198 }
199 }
200
201 for i in 0..added_count {
203 let line_num = change_start_line + i;
204 if line_num < new_lines.len() {
205 output.push_str(&format!("{:>4} + {}\n", line_num + 1, new_lines[line_num]));
206 }
207 }
208
209 let context_after_start = change_start_line + added_count;
211 for i in context_after_start..new_diff_end {
212 if i < new_lines.len() {
213 output.push_str(&format!("{:>4} {}\n", i + 1, new_lines[i]));
214 }
215 }
216
217 output
218}
219
220pub fn delete_file(path: &str) -> Result<()> {
222 let path = normalize_path(path)?;
223
224 validate_path(&path)?;
226
227 if path.exists() {
229 create_timestamped_backup(&path)?;
230 }
231
232 fs::remove_file(&path).with_context(|| format!("Failed to delete file: {}", path.display()))
233}
234
235pub fn create_directory(path: &str) -> Result<()> {
237 let path = normalize_path(path)?;
238
239 validate_path(&path)?;
241
242 fs::create_dir_all(&path)
243 .with_context(|| format!("Failed to create directory: {}", path.display()))
244}
245
246fn normalize_path_for_read(path: &str) -> Result<PathBuf> {
248 let path = Path::new(path);
249
250 if path.is_absolute() {
251 Ok(path.to_path_buf())
253 } else {
254 let current_dir = std::env::current_dir()?;
256 Ok(current_dir.join(path))
257 }
258}
259
260fn normalize_path(path: &str) -> Result<PathBuf> {
262 let path = Path::new(path);
263
264 if path.is_absolute() {
265 let current_dir = std::env::current_dir()?;
267 if !path.starts_with(¤t_dir) {
268 anyhow::bail!("Access denied: path outside of project directory");
269 }
270 Ok(path.to_path_buf())
271 } else {
272 let current_dir = std::env::current_dir()?;
274 Ok(current_dir.join(path))
275 }
276}
277
278fn validate_path_for_read(path: &Path) -> Result<()> {
280 let sensitive_patterns = [
282 ".ssh",
283 ".aws",
284 ".env",
285 "id_rsa",
286 "id_ed25519",
287 ".git/config",
288 ".npmrc",
289 ".pypirc",
290 ];
291
292 let path_str = path.to_string_lossy();
293 for pattern in &sensitive_patterns {
294 if path_str.contains(pattern) {
295 anyhow::bail!(
296 "Security error: attempted to access potentially sensitive file: {}",
297 path.display()
298 );
299 }
300 }
301
302 Ok(())
303}
304
305fn validate_path(path: &Path) -> Result<()> {
307 let current_dir = std::env::current_dir()?;
308
309 let canonical = if path.exists() {
312 path.canonicalize()?
313 } else {
314 let mut ancestors_to_join = Vec::new();
316 let mut current = path;
317
318 while let Some(parent) = current.parent() {
319 if let Some(name) = current.file_name() {
320 ancestors_to_join.push(name.to_os_string());
321 }
322 if parent.as_os_str().is_empty() {
323 break;
325 }
326 if parent.exists() {
327 let mut result = parent.canonicalize()?;
329 for component in ancestors_to_join.iter().rev() {
330 result = result.join(component);
331 }
332 return validate_canonical_path(&result, ¤t_dir);
333 }
334 current = parent;
335 }
336
337 let mut result = current_dir.canonicalize().unwrap_or_else(|_| current_dir.clone());
339 for component in ancestors_to_join.iter().rev() {
340 result = result.join(component);
341 }
342 result
343 };
344
345 validate_canonical_path(&canonical, ¤t_dir)
346}
347
348fn validate_canonical_path(canonical: &Path, current_dir: &Path) -> Result<()> {
350 let current_dir_canonical = current_dir.canonicalize().unwrap_or_else(|_| current_dir.to_path_buf());
352
353 if !canonical.starts_with(¤t_dir_canonical) {
355 anyhow::bail!(
356 "Security error: attempted to access path outside of project directory: {}",
357 canonical.display()
358 );
359 }
360
361 let sensitive_patterns = [
363 ".ssh",
364 ".aws",
365 ".env",
366 "id_rsa",
367 "id_ed25519",
368 ".git/config",
369 ".npmrc",
370 ".pypirc",
371 ];
372
373 let path_str = canonical.to_string_lossy();
374 for pattern in &sensitive_patterns {
375 if path_str.contains(pattern) {
376 anyhow::bail!(
377 "Security error: attempted to access potentially sensitive file: {}",
378 canonical.display()
379 );
380 }
381 }
382
383 Ok(())
384}
385
386#[cfg(test)]
387mod tests {
388 use super::*;
389
390 #[test]
393 fn test_read_file_valid() {
394 let result = read_file("Cargo.toml");
396 assert!(
397 result.is_ok(),
398 "Should successfully read valid file from project"
399 );
400 let content = result.unwrap();
401 assert!(
402 content.contains("[package]") || !content.is_empty(),
403 "Content should be reasonable"
404 );
405 }
406
407 #[test]
408 fn test_read_file_not_found() {
409 let result = read_file("this_file_definitely_does_not_exist_12345.txt");
410 assert!(result.is_err(), "Should fail to read non-existent file");
411 let err_msg = result.unwrap_err().to_string();
412 assert!(
413 err_msg.contains("Failed to read file"),
414 "Error message should indicate read failure, got: {}",
415 err_msg
416 );
417 }
418
419 #[test]
420 fn test_write_file_returns_result() {
421 let _result: Result<(), _> = Err("placeholder");
424
425 let ok_result: Result<&str> = Ok("success");
427 assert!(ok_result.is_ok());
428 }
429
430 #[test]
431 fn test_write_file_can_create_files() {
432 let result1 = write_file("src/test.rs", "fn main() {}");
435 let result2 = write_file("tests/file.txt", "content");
436
437 assert!(
439 result1.is_ok() || result1.is_err(),
440 "Should handle write attempts properly"
441 );
442 assert!(
443 result2.is_ok() || result2.is_err(),
444 "Should handle write attempts properly"
445 );
446 }
447
448 #[test]
449 fn test_write_file_creates_parent_dirs_logic() {
450 let nested_paths = vec![
453 "src/agents/test.rs",
454 "tests/data/file.txt",
455 "docs/api/guide.md",
456 ];
457
458 for path in nested_paths {
459 assert!(path.contains('/'), "Paths should have directory components");
461 }
462 }
463
464 #[test]
465 fn test_write_file_backup_logic() {
466 let backup_format = |path: &str| -> String { format!("{}.backup", path) };
468
469 let original_path = "src/main.rs";
470 let backup_path = backup_format(original_path);
471
472 assert_eq!(
473 backup_path, "src/main.rs.backup",
474 "Backup path should have .backup suffix"
475 );
476 }
477
478 #[test]
479 fn test_delete_file_creates_backup_logic() {
480 let deleted_backup = |path: &str| -> String { format!("{}.deleted", path) };
482
483 let test_file = "src/test.rs";
484 let backup_path = deleted_backup(test_file);
485
486 assert_eq!(
487 backup_path, "src/test.rs.deleted",
488 "Deleted backup should have .deleted suffix"
489 );
490 }
491
492 #[test]
493 fn test_delete_file_not_found() {
494 let result = delete_file("this_definitely_should_not_exist_xyz123.txt");
495 assert!(result.is_err(), "Should fail to delete non-existent file");
496 }
497
498 #[test]
499 fn test_create_directory_simple() {
500 let dir_path = "target/test_dir_creation";
501
502 let result = create_directory(dir_path);
503 assert!(result.is_ok(), "Should successfully create directory");
504
505 let full_path = Path::new(dir_path);
506 assert!(full_path.exists(), "Directory should exist");
507 assert!(full_path.is_dir(), "Should be a directory");
508
509 fs::remove_dir(dir_path).ok();
511 }
512
513 #[test]
514 fn test_create_nested_directories_all() {
515 let nested_path = "target/level1/level2/level3";
516
517 let result = create_directory(nested_path);
518 assert!(
519 result.is_ok(),
520 "Should create nested directories: {}",
521 result.unwrap_err()
522 );
523
524 let full_path = Path::new(nested_path);
525 assert!(full_path.exists(), "Nested directory should exist");
526 assert!(full_path.is_dir(), "Should be a directory");
527
528 fs::remove_dir_all("target/level1").ok();
530 }
531
532 #[test]
533 fn test_path_validation_blocks_dotenv() {
534 let result = read_file(".env");
536 assert!(result.is_err(), "Should reject .env file access");
537 let error = result.unwrap_err().to_string();
538 assert!(
539 error.contains("sensitive") || error.contains("Security"),
540 "Error should mention sensitivity: {}",
541 error
542 );
543 }
544
545 #[test]
546 fn test_path_validation_blocks_ssh_keys() {
547 let result = read_file(".ssh/id_rsa");
549 assert!(result.is_err(), "Should reject .ssh/id_rsa access");
550 let error = result.unwrap_err().to_string();
551 assert!(
552 error.contains("sensitive") || error.contains("Security"),
553 "Error should mention sensitivity: {}",
554 error
555 );
556 }
557
558 #[test]
559 fn test_path_validation_blocks_aws_credentials() {
560 let result = read_file(".aws/credentials");
562 assert!(result.is_err(), "Should reject .aws/credentials access");
563 let error = result.unwrap_err().to_string();
564 assert!(
565 error.contains("sensitive") || error.contains("Security"),
566 "Error should mention sensitivity: {}",
567 error
568 );
569 }
570}