1use serde_json::{json, Value};
2use anyhow::{Result, Context as _};
3use std::path::{Path, PathBuf};
4use std::fs;
5use std::collections::HashMap;
6use chrono::Local;
7use notify::{Watcher, RecursiveMode};
8use walkdir::WalkDir;
9use std::sync::{Arc, Mutex};
10use regex::Regex;
11
12pub struct FilesystemModule {
13 snapshots: Arc<Mutex<HashMap<String, Vec<SnapshotInfo>>>>,
14}
15
16#[derive(Clone)]
17struct SnapshotInfo {
18 #[allow(dead_code)]
19 timestamp: String,
20 path: PathBuf,
21 compressed: bool,
22}
23
24impl FilesystemModule {
25 pub fn new() -> Self {
26 Self {
27 snapshots: Arc::new(Mutex::new(HashMap::new())),
28 }
29 }
30
31 pub fn get_tools(&self) -> Vec<Value> {
32 vec![
33 json!({
34 "name": "fs_read",
35 "description": "Read file contents, optionally reading specific line ranges",
36 "inputSchema": {
37 "type": "object",
38 "properties": {
39 "path": {
40 "type": "string",
41 "description": "Path to the file to read"
42 },
43 "lines": {
44 "type": "array",
45 "description": "Optional array of line ranges to read, e.g. [[1,10], [15,20]] reads lines 1-10 and 15-20",
46 "items": {
47 "type": "array",
48 "minItems": 2,
49 "maxItems": 2,
50 "items": {
51 "type": "integer"
52 }
53 }
54 }
55 },
56 "required": ["path"]
57 }
58 }),
59 json!({
60 "name": "fs_write",
61 "description": "Write content to a file, optionally writing to specific line ranges",
62 "inputSchema": {
63 "type": "object",
64 "properties": {
65 "path": {
66 "type": "string",
67 "description": "Path to the file to write"
68 },
69 "content": {
70 "type": "string",
71 "description": "Content to write to the file"
72 },
73 "lines": {
74 "type": "array",
75 "description": "Optional array of line ranges to replace, e.g. [[1,10], [15,20]]. Content will be split and replace specified ranges.",
76 "items": {
77 "type": "array",
78 "minItems": 2,
79 "maxItems": 2,
80 "items": {
81 "type": "integer"
82 }
83 }
84 }
85 },
86 "required": ["path", "content"]
87 }
88 }),
89 json!({
90 "name": "fs_move",
91 "description": "Move files or directories",
92 "inputSchema": {
93 "type": "object",
94 "properties": {
95 "source": {
96 "type": "string",
97 "description": "Source path"
98 },
99 "destination": {
100 "type": "string",
101 "description": "Destination path"
102 }
103 },
104 "required": ["source", "destination"]
105 }
106 }),
107 json!({
108 "name": "fs_copy",
109 "description": "Copy files or directories",
110 "inputSchema": {
111 "type": "object",
112 "properties": {
113 "source": {
114 "type": "string",
115 "description": "Source path"
116 },
117 "destination": {
118 "type": "string",
119 "description": "Destination path"
120 }
121 },
122 "required": ["source", "destination"]
123 }
124 }),
125 json!({
126 "name": "fs_create",
127 "description": "Create files or directories",
128 "inputSchema": {
129 "type": "object",
130 "properties": {
131 "path": {
132 "type": "string",
133 "description": "Path to create"
134 },
135 "type": {
136 "type": "string",
137 "enum": ["file", "dir"],
138 "description": "Type to create (file or dir)"
139 }
140 },
141 "required": ["path", "type"]
142 }
143 }),
144 json!({
145 "name": "fs_delete",
146 "description": "Delete files or directories",
147 "inputSchema": {
148 "type": "object",
149 "properties": {
150 "path": {
151 "type": "string",
152 "description": "Path to delete"
153 }
154 },
155 "required": ["path"]
156 }
157 }),
158 json!({
159 "name": "fs_move_desktop",
160 "description": "Move and organize items within the Desktop directory",
161 "inputSchema": {
162 "type": "object",
163 "properties": {
164 "item": {
165 "type": "string",
166 "description": "Item name or path within Desktop"
167 },
168 "destination": {
169 "type": "string",
170 "description": "Destination subfolder within Desktop"
171 }
172 },
173 "required": ["item", "destination"]
174 }
175 }),
176 json!({
177 "name": "fs_find",
178 "description": "Search for files and directories by name pattern",
179 "inputSchema": {
180 "type": "object",
181 "properties": {
182 "path": {
183 "type": "string",
184 "description": "Root path to search from"
185 },
186 "pattern": {
187 "type": "string",
188 "description": "Search pattern (substring match, or glob with wildcards like *.rs)"
189 },
190 "type": {
191 "type": "string",
192 "enum": ["file", "dir", "all"],
193 "description": "Type to search for (default: all)"
194 },
195 "max_depth": {
196 "type": "number",
197 "description": "Maximum directory depth to search (default: unlimited)"
198 },
199 "max_results": {
200 "type": "number",
201 "description": "Maximum number of results to return (default: 1000)"
202 }
203 },
204 "required": ["path", "pattern"]
205 }
206 }),
207 json!({
208 "name": "fs_ld",
209 "description": "List directory contents with details (like ls -la)",
210 "inputSchema": {
211 "type": "object",
212 "properties": {
213 "path": {
214 "type": "string",
215 "description": "Path to list"
216 }
217 },
218 "required": ["path"]
219 }
220 }),
221 json!({
222 "name": "fs_stat",
223 "description": "Get file/directory metadata and statistics",
224 "inputSchema": {
225 "type": "object",
226 "properties": {
227 "path": {
228 "type": "string",
229 "description": "Path to get stats for"
230 }
231 },
232 "required": ["path"]
233 }
234 }),
235 json!({
236 "name": "fs_permissions",
237 "description": "Get or set file permissions",
238 "inputSchema": {
239 "type": "object",
240 "properties": {
241 "path": {
242 "type": "string",
243 "description": "Path to file/directory"
244 },
245 "mode": {
246 "type": "string",
247 "description": "Permission mode (e.g., '755', '644') - omit to get current permissions"
248 }
249 },
250 "required": ["path"]
251 }
252 }),
253 json!({
254 "name": "fs_watch",
255 "description": "Watch a file or directory for changes",
256 "inputSchema": {
257 "type": "object",
258 "properties": {
259 "path": {
260 "type": "string",
261 "description": "Path to watch"
262 },
263 "duration": {
264 "type": "number",
265 "description": "Duration to watch in seconds (default: 60)"
266 }
267 },
268 "required": ["path"]
269 }
270 }),
271 json!({
272 "name": "fs_snapshot",
273 "description": "Create lightweight timestamped backups with automatic management",
274 "inputSchema": {
275 "type": "object",
276 "properties": {
277 "path": {
278 "type": "string",
279 "description": "Path to snapshot"
280 },
281 "max_snapshots": {
282 "type": "number",
283 "description": "Maximum number of snapshots to keep (default: 10)"
284 }
285 },
286 "required": ["path"]
287 }
288 }),
289 json!({
290 "name": "fs_tree",
291 "description": "Display a visual directory tree structure. Much faster than recursive fs_find + fs_ld for understanding project layout.",
292 "inputSchema": {
293 "type": "object",
294 "properties": {
295 "path": {
296 "type": "string",
297 "description": "Root directory path"
298 },
299 "max_depth": {
300 "type": "number",
301 "description": "Maximum depth to display (default: 4)"
302 },
303 "show_hidden": {
304 "type": "boolean",
305 "description": "Show hidden files/directories (default: false)"
306 },
307 "show_size": {
308 "type": "boolean",
309 "description": "Show file sizes (default: false)"
310 },
311 "dirs_only": {
312 "type": "boolean",
313 "description": "Only show directories (default: false)"
314 },
315 "pattern": {
316 "type": "string",
317 "description": "Only show entries matching this pattern (substring match)"
318 }
319 },
320 "required": ["path"]
321 }
322 }),
323 json!({
324 "name": "fs_grep",
325 "description": "Search file contents by pattern across a directory. Returns matching lines with file paths and line numbers.",
326 "inputSchema": {
327 "type": "object",
328 "properties": {
329 "path": {
330 "type": "string",
331 "description": "File or directory to search in"
332 },
333 "pattern": {
334 "type": "string",
335 "description": "Search pattern (regex supported)"
336 },
337 "case_insensitive": {
338 "type": "boolean",
339 "description": "Case-insensitive search (default: false)"
340 },
341 "max_results": {
342 "type": "number",
343 "description": "Maximum number of matches to return (default: 200)"
344 },
345 "context_lines": {
346 "type": "number",
347 "description": "Number of context lines before/after each match (default: 0)"
348 },
349 "file_pattern": {
350 "type": "string",
351 "description": "Only search files matching this pattern (e.g. '*.rs', '*.py')"
352 }
353 },
354 "required": ["path", "pattern"]
355 }
356 }),
357 json!({
358 "name": "fs_tail",
359 "description": "Read the last N lines of a file. Essential for reading log files and build output.",
360 "inputSchema": {
361 "type": "object",
362 "properties": {
363 "path": {
364 "type": "string",
365 "description": "Path to the file"
366 },
367 "lines": {
368 "type": "number",
369 "description": "Number of lines from the end (default: 20)"
370 }
371 },
372 "required": ["path"]
373 }
374 }),
375 json!({
376 "name": "fs_replace",
377 "description": "Find and replace text across one or multiple files. Supports regex patterns and directory-wide bulk replacement.",
378 "inputSchema": {
379 "type": "object",
380 "properties": {
381 "path": {
382 "type": "string",
383 "description": "File or directory to perform replacements in"
384 },
385 "find": {
386 "type": "string",
387 "description": "Text or regex pattern to find"
388 },
389 "replace": {
390 "type": "string",
391 "description": "Replacement text (supports $1 capture groups with regex)"
392 },
393 "regex": {
394 "type": "boolean",
395 "description": "Treat find as regex pattern (default: false)"
396 },
397 "file_pattern": {
398 "type": "string",
399 "description": "Only process files matching this pattern (e.g. '*.rs') — required for directories"
400 },
401 "dry_run": {
402 "type": "boolean",
403 "description": "Preview changes without writing (default: false)"
404 }
405 },
406 "required": ["path", "find", "replace"]
407 }
408 }),
409 ]
410 }
411
412 pub async fn read(&self, args: Value) -> Result<Value> {
413 let path = args["path"].as_str().context("Missing 'path' parameter")?;
414 let full_content = fs::read_to_string(path)
415 .with_context(|| format!("Failed to read file: {}", path))?;
416
417 let total_lines = full_content.lines().count();
418
419 let content = if let Some(lines_array) = args.get("lines").and_then(|v| v.as_array()) {
421 let all_lines: Vec<&str> = full_content.lines().collect();
422 let mut selected_lines = Vec::new();
423
424 for range in lines_array {
425 if let Some(range_arr) = range.as_array() {
426 if range_arr.len() == 2 {
427 let from = range_arr[0].as_i64().unwrap_or(1) as usize;
428 let to = range_arr[1].as_i64().unwrap_or(all_lines.len() as i64) as usize;
429
430 let from_idx = from.saturating_sub(1);
431 let to_idx = to.min(all_lines.len());
432
433 if from_idx < all_lines.len() && from_idx < to_idx {
434 selected_lines.extend_from_slice(&all_lines[from_idx..to_idx]);
435 }
436 }
437 }
438 }
439
440 selected_lines.join("\n")
441 } else {
442 full_content
443 };
444
445 Ok(json!({
446 "path": path,
447 "content": content,
448 "size": content.len(),
449 "total_lines": total_lines
450 }))
451 }
452
453 pub async fn write(&self, args: Value) -> Result<Value> {
454 let path = args["path"].as_str().context("Missing 'path' parameter")?;
455 let content = args["content"].as_str().context("Missing 'content' parameter")?;
456
457 let final_content = if let Some(lines_array) = args.get("lines").and_then(|v| v.as_array()) {
459 let existing_content = fs::read_to_string(path).unwrap_or_default();
461 let mut all_lines: Vec<String> = existing_content.lines().map(|s| s.to_string()).collect();
462 let new_lines: Vec<&str> = content.lines().collect();
463 let mut new_line_idx = 0;
464
465 for range in lines_array {
466 if let Some(range_arr) = range.as_array() {
467 if range_arr.len() == 2 {
468 let from = range_arr[0].as_i64().unwrap_or(1) as usize;
469 let to = range_arr[1].as_i64().unwrap_or(all_lines.len() as i64) as usize;
470
471 let from_idx = from.saturating_sub(1);
473 let to_idx = to.min(all_lines.len());
474
475 let range_size = to_idx.saturating_sub(from_idx);
477
478 while all_lines.len() < to_idx {
480 all_lines.push(String::new());
481 }
482
483 for i in 0..range_size {
485 if new_line_idx < new_lines.len() {
486 all_lines[from_idx + i] = new_lines[new_line_idx].to_string();
487 new_line_idx += 1;
488 }
489 }
490 }
491 }
492 }
493
494 all_lines.join("\n") + "\n"
495 } else {
496 content.to_string()
497 };
498
499 fs::write(path, &final_content)
500 .with_context(|| format!("Failed to write file: {}", path))?;
501
502 Ok(json!({
503 "success": true,
504 "path": path,
505 "bytes_written": final_content.len()
506 }))
507 }
508
509 pub async fn move_file(&self, args: Value) -> Result<Value> {
510 let source = args["source"].as_str().context("Missing 'source' parameter")?;
511 let destination = args["destination"].as_str().context("Missing 'destination' parameter")?;
512
513 fs::rename(source, destination)
514 .with_context(|| format!("Failed to move from {} to {}", source, destination))?;
515
516 Ok(json!({
517 "success": true,
518 "source": source,
519 "destination": destination
520 }))
521 }
522
523 pub async fn copy(&self, args: Value) -> Result<Value> {
524 let source = args["source"].as_str().context("Missing 'source' parameter")?;
525 let destination = args["destination"].as_str().context("Missing 'destination' parameter")?;
526
527 let source_path = Path::new(source);
528
529 if source_path.is_file() {
530 fs::copy(source, destination)
531 .with_context(|| format!("Failed to copy file from {} to {}", source, destination))?;
532 } else if source_path.is_dir() {
533 copy_dir_all(source, destination)
534 .with_context(|| format!("Failed to copy directory from {} to {}", source, destination))?;
535 } else {
536 anyhow::bail!("Source path does not exist: {}", source);
537 }
538
539 Ok(json!({
540 "success": true,
541 "source": source,
542 "destination": destination
543 }))
544 }
545
546 pub async fn create(&self, args: Value) -> Result<Value> {
547 let path = args["path"].as_str().context("Missing 'path' parameter")?;
548 let type_str = args["type"].as_str().context("Missing 'type' parameter")?;
549
550 match type_str {
551 "file" => {
552 fs::File::create(path)
553 .with_context(|| format!("Failed to create file: {}", path))?;
554 }
555 "dir" => {
556 fs::create_dir_all(path)
557 .with_context(|| format!("Failed to create directory: {}", path))?;
558 }
559 _ => anyhow::bail!("Invalid type: {}. Must be 'file' or 'dir'", type_str),
560 }
561
562 Ok(json!({
563 "success": true,
564 "path": path,
565 "type": type_str
566 }))
567 }
568
569 pub async fn delete(&self, args: Value) -> Result<Value> {
570 let path = args["path"].as_str().context("Missing 'path' parameter")?;
571 let path_obj = Path::new(path);
572
573 if path_obj.is_file() {
574 fs::remove_file(path)
575 .with_context(|| format!("Failed to delete file: {}", path))?;
576 } else if path_obj.is_dir() {
577 fs::remove_dir_all(path)
578 .with_context(|| format!("Failed to delete directory: {}", path))?;
579 } else {
580 anyhow::bail!("Path does not exist: {}", path);
581 }
582
583 Ok(json!({
584 "success": true,
585 "path": path
586 }))
587 }
588
589 pub async fn move_desktop(&self, args: Value) -> Result<Value> {
590 let item = args["item"].as_str().context("Missing 'item' parameter")?;
591 let destination = args["destination"].as_str().context("Missing 'destination' parameter")?;
592
593 let desktop = dirs::desktop_dir()
595 .context("Could not find Desktop directory")?;
596
597 let source_path = desktop.join(item);
598 let dest_path = desktop.join(destination).join(item);
599
600 if let Some(parent) = dest_path.parent() {
602 fs::create_dir_all(parent)?;
603 }
604
605 fs::rename(&source_path, &dest_path)
606 .with_context(|| format!("Failed to move {} to {}", source_path.display(), dest_path.display()))?;
607
608 Ok(json!({
609 "success": true,
610 "item": item,
611 "from": source_path,
612 "to": dest_path
613 }))
614 }
615
616 pub async fn find(&self, args: Value) -> Result<Value> {
617 let root_path = args["path"].as_str().context("Missing 'path' parameter")?;
618 let pattern = args["pattern"].as_str().context("Missing 'pattern' parameter")?;
619 let search_type = args["type"].as_str().unwrap_or("all");
620 let max_results = args["max_results"].as_u64().unwrap_or(1000) as usize;
621
622 let mut walker = WalkDir::new(root_path);
623 if let Some(depth) = args["max_depth"].as_u64() {
624 walker = walker.max_depth(depth as usize);
625 }
626
627 let is_glob = pattern.contains('*') || pattern.contains('?');
629
630 let mut results = Vec::new();
631
632 for entry in walker.into_iter().filter_map(|e| e.ok()) {
633 if results.len() >= max_results {
634 break;
635 }
636
637 let path = entry.path();
638 let file_name = entry.file_name().to_string_lossy();
639
640 let matches = if is_glob {
641 glob_match(pattern, &file_name)
642 } else {
643 file_name.contains(pattern) || path.to_string_lossy().contains(pattern)
644 };
645
646 if !matches {
647 continue;
648 }
649
650 match search_type {
652 "file" if !path.is_file() => continue,
653 "dir" if !path.is_dir() => continue,
654 _ => {}
655 }
656
657 let size = path.metadata().map(|m| m.len()).unwrap_or(0);
658
659 results.push(json!({
660 "path": path.to_string_lossy(),
661 "name": file_name,
662 "type": if path.is_file() { "file" } else { "dir" },
663 "size": size
664 }));
665 }
666
667 let truncated = results.len() >= max_results;
668
669 Ok(json!({
670 "results": results,
671 "count": results.len(),
672 "truncated": truncated
673 }))
674 }
675
676 pub async fn ld(&self, args: Value) -> Result<Value> {
677 let path = args["path"].as_str().context("Missing 'path' parameter")?;
678 let path_obj = Path::new(path);
679
680 if !path_obj.exists() {
681 anyhow::bail!("Path does not exist: {}", path);
682 }
683
684 let mut entries = Vec::new();
685
686 for entry in fs::read_dir(path)? {
687 let entry = entry?;
688 let metadata = entry.metadata()?;
689 let file_name = entry.file_name().to_string_lossy().to_string();
690
691 #[cfg(unix)]
692 use std::os::unix::fs::PermissionsExt;
693
694 #[cfg(unix)]
695 let permissions = format!("{:o}", metadata.permissions().mode() & 0o777);
696
697 #[cfg(not(unix))]
698 let permissions = if metadata.permissions().readonly() {
699 "r--".to_string()
700 } else {
701 "rw-".to_string()
702 };
703
704 entries.push(json!({
705 "name": file_name,
706 "type": if metadata.is_file() { "file" } else if metadata.is_dir() { "dir" } else { "other" },
707 "size": metadata.len(),
708 "permissions": permissions,
709 "modified": metadata.modified().ok().and_then(|t| {
710 t.duration_since(std::time::UNIX_EPOCH).ok().map(|d| d.as_secs())
711 })
712 }));
713 }
714
715 Ok(json!({
716 "path": path,
717 "entries": entries,
718 "count": entries.len()
719 }))
720 }
721
722 pub async fn stat(&self, args: Value) -> Result<Value> {
723 let path = args["path"].as_str().context("Missing 'path' parameter")?;
724 let metadata = fs::metadata(path)
725 .with_context(|| format!("Failed to get metadata for: {}", path))?;
726
727 #[cfg(unix)]
728 use std::os::unix::fs::PermissionsExt;
729
730 #[cfg(unix)]
731 let permissions = format!("{:o}", metadata.permissions().mode() & 0o777);
732
733 #[cfg(not(unix))]
734 let permissions = if metadata.permissions().readonly() {
735 "readonly".to_string()
736 } else {
737 "read-write".to_string()
738 };
739
740 Ok(json!({
741 "path": path,
742 "type": if metadata.is_file() { "file" } else if metadata.is_dir() { "dir" } else { "other" },
743 "size": metadata.len(),
744 "permissions": permissions,
745 "readonly": metadata.permissions().readonly(),
746 "created": metadata.created().ok().and_then(|t| {
747 t.duration_since(std::time::UNIX_EPOCH).ok().map(|d| d.as_secs())
748 }),
749 "modified": metadata.modified().ok().and_then(|t| {
750 t.duration_since(std::time::UNIX_EPOCH).ok().map(|d| d.as_secs())
751 }),
752 "accessed": metadata.accessed().ok().and_then(|t| {
753 t.duration_since(std::time::UNIX_EPOCH).ok().map(|d| d.as_secs())
754 })
755 }))
756 }
757
758 pub async fn permissions(&self, args: Value) -> Result<Value> {
759 let path = args["path"].as_str().context("Missing 'path' parameter")?;
760
761 if let Some(mode_str) = args["mode"].as_str() {
762 #[cfg(unix)]
764 {
765 use std::os::unix::fs::PermissionsExt;
766 let mode = u32::from_str_radix(mode_str, 8)
767 .with_context(|| format!("Invalid permission mode: {}", mode_str))?;
768 let permissions = std::fs::Permissions::from_mode(mode);
769 fs::set_permissions(path, permissions)
770 .with_context(|| format!("Failed to set permissions for: {}", path))?;
771
772 Ok(json!({
773 "success": true,
774 "path": path,
775 "mode": mode_str
776 }))
777 }
778
779 #[cfg(not(unix))]
780 {
781 anyhow::bail!("Setting permissions is only supported on Unix systems");
782 }
783 } else {
784 let metadata = fs::metadata(path)?;
786
787 #[cfg(unix)]
788 use std::os::unix::fs::PermissionsExt;
789
790 #[cfg(unix)]
791 let mode = format!("{:o}", metadata.permissions().mode() & 0o777);
792
793 #[cfg(not(unix))]
794 let mode = if metadata.permissions().readonly() {
795 "readonly"
796 } else {
797 "read-write"
798 };
799
800 Ok(json!({
801 "path": path,
802 "mode": mode,
803 "readonly": metadata.permissions().readonly()
804 }))
805 }
806 }
807
808 pub async fn watch(&self, args: Value) -> Result<Value> {
809 let path = args["path"].as_str().context("Missing 'path' parameter")?;
810 let duration = args["duration"].as_u64().unwrap_or(60);
811
812 let (tx, rx) = std::sync::mpsc::channel();
813 let mut watcher = notify::recommended_watcher(tx)?;
814
815 watcher.watch(Path::new(path), RecursiveMode::Recursive)?;
816
817 let mut events = Vec::new();
818 let start = std::time::Instant::now();
819
820 while start.elapsed().as_secs() < duration {
821 if let Ok(Ok(event)) = rx.recv_timeout(std::time::Duration::from_secs(1)) {
822 events.push(json!({
823 "kind": format!("{:?}", event.kind),
824 "paths": event.paths.iter().map(|p| p.to_string_lossy()).collect::<Vec<_>>()
825 }));
826 }
827 }
828
829 Ok(json!({
830 "path": path,
831 "duration": duration,
832 "events": events,
833 "event_count": events.len()
834 }))
835 }
836
837 pub async fn snapshot(&self, args: Value) -> Result<Value> {
838 let path = args["path"].as_str().context("Missing 'path' parameter")?;
839 let max_snapshots = args["max_snapshots"].as_u64().unwrap_or(10) as usize;
840
841 let path_obj = Path::new(path);
842 if !path_obj.exists() {
843 anyhow::bail!("Path does not exist: {}", path);
844 }
845
846 let snapshot_dir = path_obj.parent()
848 .unwrap_or_else(|| Path::new("."))
849 .join(".snapshots")
850 .join(path_obj.file_name().unwrap_or_else(|| path_obj.as_os_str()));
851
852 fs::create_dir_all(&snapshot_dir)?;
853
854 let timestamp = Local::now().format("%Y%m%d_%H%M%S").to_string();
856 let snapshot_name = format!("snapshot_{}", timestamp);
857 let snapshot_path = snapshot_dir.join(&snapshot_name);
858
859 if path_obj.is_file() {
861 fs::copy(path, &snapshot_path)?;
862 } else {
863 copy_dir_all(path, &snapshot_path)?;
864 }
865
866 let mut snapshots = self.snapshots.lock().unwrap();
868 let key = path.to_string();
869 let snapshot_list = snapshots.entry(key.clone()).or_insert_with(Vec::new);
870
871 snapshot_list.push(SnapshotInfo {
872 timestamp: timestamp.clone(),
873 path: snapshot_path.clone(),
874 compressed: false,
875 });
876
877 if snapshot_list.len() > max_snapshots {
879 for snapshot in snapshot_list.iter_mut().rev().skip(3) {
881 if !snapshot.compressed {
882 snapshot.compressed = true;
884 }
885 }
886
887 while snapshot_list.len() > max_snapshots {
889 if let Some(oldest) = snapshot_list.first() {
890 if oldest.path.exists() {
891 if oldest.path.is_file() {
892 fs::remove_file(&oldest.path)?;
893 } else {
894 fs::remove_dir_all(&oldest.path)?;
895 }
896 }
897 }
898 snapshot_list.remove(0);
899 }
900 }
901
902 Ok(json!({
903 "success": true,
904 "path": path,
905 "snapshot": snapshot_path,
906 "timestamp": timestamp,
907 "total_snapshots": snapshot_list.len(),
908 "max_snapshots": max_snapshots
909 }))
910 }
911
912 pub async fn tree(&self, args: Value) -> Result<Value> {
913 let path = args["path"].as_str().context("Missing 'path' parameter")?;
914 let max_depth = args["max_depth"].as_u64().unwrap_or(4) as usize;
915 let show_hidden = args["show_hidden"].as_bool().unwrap_or(false);
916 let show_size = args["show_size"].as_bool().unwrap_or(false);
917 let dirs_only = args["dirs_only"].as_bool().unwrap_or(false);
918 let pattern = args["pattern"].as_str();
919
920 let root = Path::new(path);
921 if !root.exists() {
922 anyhow::bail!("Path does not exist: {}", path);
923 }
924
925 let mut output = String::new();
926 let mut file_count = 0usize;
927 let mut dir_count = 0usize;
928
929 output.push_str(&format!("{}\n", root.display()));
930 build_tree(root, "", max_depth, 0, show_hidden, show_size, dirs_only, pattern, &mut output, &mut file_count, &mut dir_count)?;
931
932 Ok(json!({
933 "tree": output,
934 "path": path,
935 "directories": dir_count,
936 "files": file_count,
937 "max_depth": max_depth
938 }))
939 }
940
941 pub async fn grep(&self, args: Value) -> Result<Value> {
942 let path = args["path"].as_str().context("Missing 'path' parameter")?;
943 let pattern = args["pattern"].as_str().context("Missing 'pattern' parameter")?;
944 let case_insensitive = args["case_insensitive"].as_bool().unwrap_or(false);
945 let max_results = args["max_results"].as_u64().unwrap_or(200) as usize;
946 let context_lines = args["context_lines"].as_u64().unwrap_or(0) as usize;
947 let file_pattern = args["file_pattern"].as_str();
948
949 let mut regex_pattern = String::new();
950 if case_insensitive {
951 regex_pattern.push_str("(?i)");
952 }
953 regex_pattern.push_str(pattern);
954
955 let re = Regex::new(®ex_pattern)
956 .with_context(|| format!("Invalid regex pattern: {}", pattern))?;
957
958 let root = Path::new(path);
959 let mut matches = Vec::new();
960
961 let files: Vec<PathBuf> = if root.is_file() {
962 vec![root.to_path_buf()]
963 } else {
964 WalkDir::new(root)
965 .into_iter()
966 .filter_map(|e| e.ok())
967 .filter(|e| e.path().is_file())
968 .filter(|e| {
969 if let Some(fp) = file_pattern {
970 let name = e.file_name().to_string_lossy();
971 glob_match(fp, &name)
972 } else {
973 true
974 }
975 })
976 .map(|e| e.path().to_path_buf())
977 .collect()
978 };
979
980 'outer: for file_path in &files {
981 let content = match fs::read_to_string(file_path) {
982 Ok(c) => c,
983 Err(_) => continue, };
985
986 let lines: Vec<&str> = content.lines().collect();
987
988 for (line_num, line) in lines.iter().enumerate() {
989 if re.is_match(line) {
990 if matches.len() >= max_results {
991 break 'outer;
992 }
993
994 let mut context_before = Vec::new();
995 let mut context_after = Vec::new();
996
997 if context_lines > 0 {
998 let start = line_num.saturating_sub(context_lines);
999 for i in start..line_num {
1000 context_before.push(lines[i]);
1001 }
1002 let end = (line_num + 1 + context_lines).min(lines.len());
1003 for i in (line_num + 1)..end {
1004 context_after.push(lines[i]);
1005 }
1006 }
1007
1008 let mut entry = json!({
1009 "file": file_path.to_string_lossy(),
1010 "line": line_num + 1,
1011 "content": line
1012 });
1013
1014 if context_lines > 0 {
1015 entry["context_before"] = json!(context_before);
1016 entry["context_after"] = json!(context_after);
1017 }
1018
1019 matches.push(entry);
1020 }
1021 }
1022 }
1023
1024 let truncated = matches.len() >= max_results;
1025
1026 Ok(json!({
1027 "matches": matches,
1028 "count": matches.len(),
1029 "files_searched": files.len(),
1030 "pattern": pattern,
1031 "truncated": truncated
1032 }))
1033 }
1034
1035 pub async fn tail(&self, args: Value) -> Result<Value> {
1036 let path = args["path"].as_str().context("Missing 'path' parameter")?;
1037 let n = args["lines"].as_u64().unwrap_or(20) as usize;
1038
1039 let content = fs::read_to_string(path)
1040 .with_context(|| format!("Failed to read file: {}", path))?;
1041
1042 let all_lines: Vec<&str> = content.lines().collect();
1043 let total = all_lines.len();
1044 let start = total.saturating_sub(n);
1045 let tail_lines = &all_lines[start..];
1046
1047 Ok(json!({
1048 "path": path,
1049 "content": tail_lines.join("\n"),
1050 "lines_returned": tail_lines.len(),
1051 "total_lines": total,
1052 "from_line": start + 1
1053 }))
1054 }
1055
1056 pub async fn replace(&self, args: Value) -> Result<Value> {
1057 let path = args["path"].as_str().context("Missing 'path' parameter")?;
1058 let find = args["find"].as_str().context("Missing 'find' parameter")?;
1059 let replace_with = args["replace"].as_str().context("Missing 'replace' parameter")?;
1060 let use_regex = args["regex"].as_bool().unwrap_or(false);
1061 let dry_run = args["dry_run"].as_bool().unwrap_or(false);
1062 let file_pattern = args["file_pattern"].as_str();
1063
1064 let root = Path::new(path);
1065
1066 let files: Vec<PathBuf> = if root.is_file() {
1067 vec![root.to_path_buf()]
1068 } else if root.is_dir() {
1069 let fp = file_pattern.context("'file_pattern' is required when path is a directory")?;
1070 WalkDir::new(root)
1071 .into_iter()
1072 .filter_map(|e| e.ok())
1073 .filter(|e| e.path().is_file())
1074 .filter(|e| glob_match(fp, &e.file_name().to_string_lossy()))
1075 .map(|e| e.path().to_path_buf())
1076 .collect()
1077 } else {
1078 anyhow::bail!("Path does not exist: {}", path);
1079 };
1080
1081 let re = if use_regex {
1082 Some(Regex::new(find).with_context(|| format!("Invalid regex: {}", find))?)
1083 } else {
1084 None
1085 };
1086
1087 let mut results = Vec::new();
1088 let mut total_replacements = 0usize;
1089
1090 for file_path in &files {
1091 let content = match fs::read_to_string(file_path) {
1092 Ok(c) => c,
1093 Err(_) => continue,
1094 };
1095
1096 let (new_content, count) = if let Some(ref re) = re {
1097 let count = re.find_iter(&content).count();
1098 let replaced = re.replace_all(&content, replace_with).to_string();
1099 (replaced, count)
1100 } else {
1101 let count = content.matches(find).count();
1102 let replaced = content.replace(find, replace_with);
1103 (replaced, count)
1104 };
1105
1106 if count > 0 {
1107 if !dry_run {
1108 fs::write(file_path, &new_content)
1109 .with_context(|| format!("Failed to write: {}", file_path.display()))?;
1110 }
1111 total_replacements += count;
1112 results.push(json!({
1113 "file": file_path.to_string_lossy(),
1114 "replacements": count
1115 }));
1116 }
1117 }
1118
1119 Ok(json!({
1120 "success": true,
1121 "dry_run": dry_run,
1122 "files_modified": results.len(),
1123 "total_replacements": total_replacements,
1124 "files_searched": files.len(),
1125 "details": results
1126 }))
1127 }
1128}
1129
1130fn build_tree(
1131 dir: &Path,
1132 prefix: &str,
1133 max_depth: usize,
1134 current_depth: usize,
1135 show_hidden: bool,
1136 show_size: bool,
1137 dirs_only: bool,
1138 pattern: Option<&str>,
1139 output: &mut String,
1140 file_count: &mut usize,
1141 dir_count: &mut usize,
1142) -> Result<()> {
1143 if current_depth >= max_depth {
1144 return Ok(());
1145 }
1146
1147 let mut entries: Vec<_> = fs::read_dir(dir)?
1148 .filter_map(|e| e.ok())
1149 .collect();
1150
1151 entries.sort_by(|a, b| a.file_name().cmp(&b.file_name()));
1152
1153 if !show_hidden {
1155 entries.retain(|e| {
1156 !e.file_name().to_string_lossy().starts_with('.')
1157 });
1158 }
1159
1160 if let Some(pat) = pattern {
1162 entries.retain(|e| {
1163 let name = e.file_name().to_string_lossy().to_string();
1164 let is_dir = e.path().is_dir();
1165 is_dir || name.contains(pat) || glob_match(pat, &name)
1166 });
1167 }
1168
1169 if dirs_only {
1171 entries.retain(|e| e.path().is_dir());
1172 }
1173
1174 let count = entries.len();
1175
1176 for (i, entry) in entries.iter().enumerate() {
1177 let is_last = i == count - 1;
1178 let connector = if is_last { "└── " } else { "├── " };
1179 let name = entry.file_name().to_string_lossy().to_string();
1180 let path = entry.path();
1181 let is_dir = path.is_dir();
1182
1183 let size_str = if show_size && !is_dir {
1184 let size = path.metadata().map(|m| m.len()).unwrap_or(0);
1185 format!(" ({})", format_size(size))
1186 } else {
1187 String::new()
1188 };
1189
1190 let dir_marker = if is_dir { "/" } else { "" };
1191
1192 output.push_str(&format!("{}{}{}{}{}\n", prefix, connector, name, dir_marker, size_str));
1193
1194 if is_dir {
1195 *dir_count += 1;
1196 let new_prefix = format!("{}{}", prefix, if is_last { " " } else { "│ " });
1197 build_tree(&path, &new_prefix, max_depth, current_depth + 1, show_hidden, show_size, dirs_only, pattern, output, file_count, dir_count)?;
1198 } else {
1199 *file_count += 1;
1200 }
1201 }
1202
1203 Ok(())
1204}
1205
1206fn format_size(bytes: u64) -> String {
1207 if bytes >= 1_073_741_824 {
1208 format!("{:.1}G", bytes as f64 / 1_073_741_824.0)
1209 } else if bytes >= 1_048_576 {
1210 format!("{:.1}M", bytes as f64 / 1_048_576.0)
1211 } else if bytes >= 1024 {
1212 format!("{:.1}K", bytes as f64 / 1024.0)
1213 } else {
1214 format!("{}B", bytes)
1215 }
1216}
1217
1218fn glob_match(pattern: &str, text: &str) -> bool {
1220 glob_match_recursive(&pattern.chars().collect::<Vec<_>>(), &text.chars().collect::<Vec<_>>(), 0, 0)
1221}
1222
1223fn glob_match_recursive(pattern: &[char], text: &[char], pi: usize, ti: usize) -> bool {
1224 if pi == pattern.len() && ti == text.len() {
1225 return true;
1226 }
1227 if pi == pattern.len() {
1228 return false;
1229 }
1230
1231 match pattern[pi] {
1232 '*' => {
1233 for i in ti..=text.len() {
1235 if glob_match_recursive(pattern, text, pi + 1, i) {
1236 return true;
1237 }
1238 }
1239 false
1240 }
1241 '?' => {
1242 if ti < text.len() {
1243 glob_match_recursive(pattern, text, pi + 1, ti + 1)
1244 } else {
1245 false
1246 }
1247 }
1248 c => {
1249 if ti < text.len() && (c == text[ti] || c.to_lowercase().next() == text[ti].to_lowercase().next()) {
1250 glob_match_recursive(pattern, text, pi + 1, ti + 1)
1251 } else {
1252 false
1253 }
1254 }
1255 }
1256}
1257
1258fn copy_dir_all(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Result<()> {
1260 fs::create_dir_all(&dst)?;
1261
1262 for entry in fs::read_dir(src)? {
1263 let entry = entry?;
1264 let ty = entry.file_type()?;
1265
1266 if ty.is_dir() {
1267 copy_dir_all(entry.path(), dst.as_ref().join(entry.file_name()))?;
1268 } else {
1269 fs::copy(entry.path(), dst.as_ref().join(entry.file_name()))?;
1270 }
1271 }
1272
1273 Ok(())
1274}