1use serde_json::{json, Value};
2use anyhow::{Result, Context as _};
3use std::fs;
4use std::io::Write as IoWrite;
5use std::path::Path;
6
7pub struct TransformModule;
8
9impl Default for TransformModule {
10 fn default() -> Self {
11 Self::new()
12 }
13}
14
15impl TransformModule {
16 pub fn new() -> Self {
17 Self
18 }
19
20 pub fn get_tools(&self) -> Vec<Value> {
21 vec![
22 json!({
23 "name": "transform_diff",
24 "description": "Compare two texts or files and produce a diff. Useful for verifying changes or comparing versions without requiring a git repository.",
25 "inputSchema": {
26 "type": "object",
27 "properties": {
28 "a": {
29 "type": "string",
30 "description": "First text content (or file path if from_file is true)"
31 },
32 "b": {
33 "type": "string",
34 "description": "Second text content (or file path if from_file is true)"
35 },
36 "from_file": {
37 "type": "boolean",
38 "description": "If true, treat a and b as file paths (default: false)"
39 },
40 "context_lines": {
41 "type": "number",
42 "description": "Number of context lines around changes (default: 3)"
43 },
44 "format": {
45 "type": "string",
46 "enum": ["unified", "inline", "stats"],
47 "description": "Output format (default: unified)"
48 }
49 },
50 "required": ["a", "b"]
51 }
52 }),
53 json!({
54 "name": "transform_encode",
55 "description": "Encode or decode text using common encoding schemes (base64, URL, hex, HTML entities).",
56 "inputSchema": {
57 "type": "object",
58 "properties": {
59 "text": {
60 "type": "string",
61 "description": "Text to encode or decode"
62 },
63 "encoding": {
64 "type": "string",
65 "enum": ["base64", "url", "hex", "html"],
66 "description": "Encoding scheme to use"
67 },
68 "action": {
69 "type": "string",
70 "enum": ["encode", "decode"],
71 "description": "Whether to encode or decode (default: encode)"
72 }
73 },
74 "required": ["text", "encoding"]
75 }
76 }),
77 json!({
78 "name": "transform_hash",
79 "description": "Generate cryptographic hashes of text or files (SHA256, SHA512, MD5, BLAKE3).",
80 "inputSchema": {
81 "type": "object",
82 "properties": {
83 "input": {
84 "type": "string",
85 "description": "Text to hash, or file path if from_file is true"
86 },
87 "algorithm": {
88 "type": "string",
89 "enum": ["sha256", "sha512", "md5", "blake3"],
90 "description": "Hash algorithm (default: sha256)"
91 },
92 "from_file": {
93 "type": "boolean",
94 "description": "If true, hash the file at the given path (default: false)"
95 }
96 },
97 "required": ["input"]
98 }
99 }),
100 json!({
101 "name": "transform_regex",
102 "description": "Perform regex operations on text: match, find all matches, replace, split, or extract capture groups.",
103 "inputSchema": {
104 "type": "object",
105 "properties": {
106 "text": {
107 "type": "string",
108 "description": "Text to operate on"
109 },
110 "pattern": {
111 "type": "string",
112 "description": "Regular expression pattern"
113 },
114 "action": {
115 "type": "string",
116 "enum": ["match", "find_all", "replace", "split", "extract"],
117 "description": "Operation to perform (default: find_all)"
118 },
119 "replacement": {
120 "type": "string",
121 "description": "Replacement string (for replace action, supports $1 capture groups)"
122 },
123 "flags": {
124 "type": "string",
125 "description": "Regex flags: 'i' case-insensitive, 'm' multiline, 's' dot-matches-newline"
126 }
127 },
128 "required": ["text", "pattern"]
129 }
130 }),
131 json!({
132 "name": "transform_json",
133 "description": "Manipulate JSON: pretty-print, minify, validate, query with dot-notation, merge objects, list keys, or flatten nested structures.",
134 "inputSchema": {
135 "type": "object",
136 "properties": {
137 "input": {
138 "type": "string",
139 "description": "JSON string to operate on"
140 },
141 "action": {
142 "type": "string",
143 "enum": ["pretty", "minify", "validate", "query", "merge", "keys", "flatten"],
144 "description": "Operation to perform (default: pretty)"
145 },
146 "query": {
147 "type": "string",
148 "description": "Dot-notation path for query action (e.g. 'data.users[0].name')"
149 },
150 "merge_with": {
151 "type": "string",
152 "description": "Second JSON string to merge with (for merge action)"
153 }
154 },
155 "required": ["input"]
156 }
157 }),
158 json!({
159 "name": "transform_text",
160 "description": "Perform common text transformations: case conversion, line sorting, deduplication, word/line counting, truncation, wrapping, and more.",
161 "inputSchema": {
162 "type": "object",
163 "properties": {
164 "text": {
165 "type": "string",
166 "description": "Text to transform"
167 },
168 "action": {
169 "type": "string",
170 "enum": ["uppercase", "lowercase", "title_case", "snake_case", "camel_case", "kebab_case", "sort_lines", "reverse_lines", "unique_lines", "trim_lines", "number_lines", "wrap", "truncate", "stats"],
171 "description": "Transformation to apply"
172 },
173 "width": {
174 "type": "number",
175 "description": "Line width for wrap, or max length for truncate (default: 80)"
176 }
177 },
178 "required": ["text", "action"]
179 }
180 }),
181 json!({
182 "name": "transform_archive",
183 "description": "Create or extract archive files (zip, tar.gz). List archive contents without extracting.",
184 "inputSchema": {
185 "type": "object",
186 "properties": {
187 "action": {
188 "type": "string",
189 "enum": ["create", "extract", "list"],
190 "description": "Operation to perform"
191 },
192 "path": {
193 "type": "string",
194 "description": "Path to archive file (for extract/list) or output path (for create)"
195 },
196 "files": {
197 "type": "array",
198 "items": { "type": "string" },
199 "description": "Files/directories to include (for create)"
200 },
201 "format": {
202 "type": "string",
203 "enum": ["zip", "tar_gz"],
204 "description": "Archive format (default: zip)"
205 },
206 "destination": {
207 "type": "string",
208 "description": "Extraction destination directory (for extract, default: current directory)"
209 }
210 },
211 "required": ["action", "path"]
212 }
213 }),
214 ]
215 }
216
217 pub async fn diff(&self, args: Value) -> Result<Value> {
220 let a_raw = args["a"].as_str().context("Missing 'a' parameter")?;
221 let b_raw = args["b"].as_str().context("Missing 'b' parameter")?;
222 let from_file = args["from_file"].as_bool().unwrap_or(false);
223 let format = args["format"].as_str().unwrap_or("unified");
224 let context_lines = args["context_lines"].as_u64().unwrap_or(3) as usize;
225
226 let (text_a, text_b, label_a, label_b) = if from_file {
227 let a = fs::read_to_string(a_raw)
228 .with_context(|| format!("Failed to read file: {}", a_raw))?;
229 let b = fs::read_to_string(b_raw)
230 .with_context(|| format!("Failed to read file: {}", b_raw))?;
231 (a, b, a_raw.to_string(), b_raw.to_string())
232 } else {
233 (a_raw.to_string(), b_raw.to_string(), "a".to_string(), "b".to_string())
234 };
235
236 match format {
237 "stats" => {
238 let changeset = similar::TextDiff::from_lines(&text_a, &text_b);
239 let mut additions = 0usize;
240 let mut deletions = 0usize;
241 let mut unchanged = 0usize;
242
243 for change in changeset.iter_all_changes() {
244 match change.tag() {
245 similar::ChangeTag::Insert => additions += 1,
246 similar::ChangeTag::Delete => deletions += 1,
247 similar::ChangeTag::Equal => unchanged += 1,
248 }
249 }
250
251 Ok(json!({
252 "additions": additions,
253 "deletions": deletions,
254 "unchanged": unchanged,
255 "total_changes": additions + deletions,
256 "identical": additions == 0 && deletions == 0
257 }))
258 }
259 "inline" => {
260 let changeset = similar::TextDiff::from_lines(&text_a, &text_b);
261 let mut lines = Vec::new();
262
263 for change in changeset.iter_all_changes() {
264 let sign = match change.tag() {
265 similar::ChangeTag::Insert => "+",
266 similar::ChangeTag::Delete => "-",
267 similar::ChangeTag::Equal => " ",
268 };
269 lines.push(format!("{}{}", sign, change));
270 }
271
272 Ok(json!({
273 "diff": lines.join(""),
274 "format": "inline"
275 }))
276 }
277 _ => {
278 let changeset = similar::TextDiff::from_lines(&text_a, &text_b);
280 let unified = changeset
281 .unified_diff()
282 .context_radius(context_lines)
283 .header(&label_a, &label_b)
284 .to_string();
285
286 Ok(json!({
287 "diff": unified,
288 "format": "unified",
289 "context_lines": context_lines
290 }))
291 }
292 }
293 }
294
295 pub async fn encode(&self, args: Value) -> Result<Value> {
298 let text = args["text"].as_str().context("Missing 'text' parameter")?;
299 let encoding = args["encoding"].as_str().context("Missing 'encoding' parameter")?;
300 let action = args["action"].as_str().unwrap_or("encode");
301
302 let result = match (encoding, action) {
303 ("base64", "encode") => {
304 use base64::Engine;
305 base64::engine::general_purpose::STANDARD.encode(text)
306 }
307 ("base64", "decode") => {
308 use base64::Engine;
309 let bytes = base64::engine::general_purpose::STANDARD.decode(text)
310 .context("Invalid base64 input")?;
311 String::from_utf8(bytes).context("Decoded base64 is not valid UTF-8")?
312 }
313 ("url", "encode") => {
314 urlencoding::encode(text).to_string()
315 }
316 ("url", "decode") => {
317 urlencoding::decode(text)
318 .context("Invalid URL-encoded input")?
319 .to_string()
320 }
321 ("hex", "encode") => {
322 let bytes = text.as_bytes();
323 let mut hex = String::with_capacity(bytes.len() * 2);
324 for b in bytes {
325 use std::fmt::Write;
326 write!(hex, "{:02x}", b).unwrap();
327 }
328 hex
329 }
330 ("hex", "decode") => {
331 if text.len() % 2 != 0 {
332 return Err(anyhow::anyhow!("Hex string must have even length, got {}", text.len()));
333 }
334 let bytes: Result<Vec<u8>, _> = (0..text.len())
335 .step_by(2)
336 .map(|i| u8::from_str_radix(&text[i..i + 2], 16))
337 .collect();
338 let bytes = bytes.context("Invalid hex input (non-hex characters found)")?;
339 String::from_utf8(bytes).context("Decoded hex is not valid UTF-8")?
340 }
341 ("html", "encode") => {
342 let mut result = String::with_capacity(text.len() + text.len() / 8);
343 for c in text.chars() {
344 match c {
345 '&' => result.push_str("&"),
346 '<' => result.push_str("<"),
347 '>' => result.push_str(">"),
348 '"' => result.push_str("""),
349 '\'' => result.push_str("'"),
350 _ => result.push(c),
351 }
352 }
353 result
354 }
355 ("html", "decode") => {
356 text.replace("&", "&")
357 .replace("<", "<")
358 .replace(">", ">")
359 .replace(""", "\"")
360 .replace("'", "'")
361 .replace("'", "'")
362 .replace("'", "'")
363 }
364 _ => return Err(anyhow::anyhow!("Unsupported encoding/action: {}/{}", encoding, action)),
365 };
366
367 let output_length = result.len();
368 Ok(json!({
369 "result": result,
370 "encoding": encoding,
371 "action": action,
372 "input_length": text.len(),
373 "output_length": output_length
374 }))
375 }
376
377 pub async fn hash(&self, args: Value) -> Result<Value> {
380 let input = args["input"].as_str().context("Missing 'input' parameter")?;
381 let algorithm = args["algorithm"].as_str().unwrap_or("sha256");
382 let from_file = args["from_file"].as_bool().unwrap_or(false);
383
384 let (hash, input_size) = if from_file {
385 use std::io::{BufReader, Read};
386 let file = fs::File::open(input)
387 .with_context(|| format!("Failed to open file: {}", input))?;
388 let file_size = file.metadata().map(|m| m.len() as usize).unwrap_or(0);
389 let mut reader = BufReader::with_capacity(64 * 1024, file);
390
391 let hash = match algorithm {
392 "sha256" => {
393 use sha2::Digest;
394 let mut hasher = sha2::Sha256::new();
395 let mut buf = [0u8; 64 * 1024];
396 loop {
397 let n = reader.read(&mut buf)?;
398 if n == 0 { break; }
399 hasher.update(&buf[..n]);
400 }
401 format!("{:x}", hasher.finalize())
402 }
403 "sha512" => {
404 use sha2::Digest;
405 let mut hasher = sha2::Sha512::new();
406 let mut buf = [0u8; 64 * 1024];
407 loop {
408 let n = reader.read(&mut buf)?;
409 if n == 0 { break; }
410 hasher.update(&buf[..n]);
411 }
412 format!("{:x}", hasher.finalize())
413 }
414 "md5" => {
415 use md5::Digest;
416 let mut hasher = md5::Md5::new();
417 let mut buf = [0u8; 64 * 1024];
418 loop {
419 let n = reader.read(&mut buf)?;
420 if n == 0 { break; }
421 hasher.update(&buf[..n]);
422 }
423 format!("{:x}", hasher.finalize())
424 }
425 "blake3" => {
426 let mut hasher = blake3::Hasher::new();
427 let mut buf = [0u8; 64 * 1024];
428 loop {
429 let n = reader.read(&mut buf)?;
430 if n == 0 { break; }
431 hasher.update(&buf[..n]);
432 }
433 hasher.finalize().to_hex().to_string()
434 }
435 _ => return Err(anyhow::anyhow!("Unsupported algorithm: {}", algorithm)),
436 };
437 (hash, file_size)
438 } else {
439 let data = input.as_bytes();
440 let hash = match algorithm {
441 "sha256" => {
442 use sha2::Digest;
443 format!("{:x}", sha2::Sha256::digest(data))
444 }
445 "sha512" => {
446 use sha2::Digest;
447 format!("{:x}", sha2::Sha512::digest(data))
448 }
449 "md5" => {
450 use md5::Digest;
451 format!("{:x}", md5::Md5::digest(data))
452 }
453 "blake3" => {
454 blake3::hash(data).to_hex().to_string()
455 }
456 _ => return Err(anyhow::anyhow!("Unsupported algorithm: {}", algorithm)),
457 };
458 (hash, data.len())
459 };
460
461 Ok(json!({
462 "hash": hash,
463 "algorithm": algorithm,
464 "input_size": input_size,
465 "from_file": from_file
466 }))
467 }
468
469 pub async fn regex_op(&self, args: Value) -> Result<Value> {
472 let text = args["text"].as_str().context("Missing 'text' parameter")?;
473 let pattern_str = args["pattern"].as_str().context("Missing 'pattern' parameter")?;
474 let action = args["action"].as_str().unwrap_or("find_all");
475 let flags = args["flags"].as_str().unwrap_or("");
476
477 let mut pattern = String::new();
478 if !flags.is_empty() {
479 pattern.push_str("(?");
480 pattern.push_str(flags);
481 pattern.push(')');
482 }
483 pattern.push_str(pattern_str);
484
485 let re = regex::Regex::new(&pattern)
486 .with_context(|| format!("Invalid regex pattern: {}", pattern_str))?;
487
488 match action {
489 "match" => {
490 let is_match = re.is_match(text);
491 let first = re.find(text).map(|m| json!({
492 "text": m.as_str(),
493 "start": m.start(),
494 "end": m.end()
495 }));
496
497 Ok(json!({
498 "matches": is_match,
499 "first_match": first,
500 "pattern": pattern_str
501 }))
502 }
503 "find_all" => {
504 let matches: Vec<Value> = re.find_iter(text).map(|m| {
505 json!({
506 "text": m.as_str(),
507 "start": m.start(),
508 "end": m.end()
509 })
510 }).collect();
511
512 Ok(json!({
513 "matches": matches,
514 "count": matches.len(),
515 "pattern": pattern_str
516 }))
517 }
518 "replace" => {
519 let replacement = args["replacement"].as_str().unwrap_or("");
520 let result = re.replace_all(text, replacement).to_string();
521 let count = re.find_iter(text).count();
522
523 Ok(json!({
524 "result": result,
525 "replacements": count,
526 "pattern": pattern_str
527 }))
528 }
529 "split" => {
530 let parts: Vec<&str> = re.split(text).collect();
531
532 Ok(json!({
533 "parts": parts,
534 "count": parts.len(),
535 "pattern": pattern_str
536 }))
537 }
538 "extract" => {
539 let mut groups = Vec::new();
540 for caps in re.captures_iter(text) {
541 let mut group = Vec::new();
542 for i in 0..caps.len() {
543 group.push(json!({
544 "group": i,
545 "text": caps.get(i).map(|m| m.as_str())
546 }));
547 }
548 groups.push(json!(group));
549 }
550
551 Ok(json!({
552 "captures": groups,
553 "count": groups.len(),
554 "pattern": pattern_str
555 }))
556 }
557 _ => Err(anyhow::anyhow!("Unknown regex action: {}", action)),
558 }
559 }
560
561 pub async fn json_op(&self, args: Value) -> Result<Value> {
564 let input = args["input"].as_str().context("Missing 'input' parameter")?;
565 let action = args["action"].as_str().unwrap_or("pretty");
566
567 match action {
568 "validate" => {
569 match serde_json::from_str::<Value>(input) {
570 Ok(_) => Ok(json!({ "valid": true })),
571 Err(e) => Ok(json!({
572 "valid": false,
573 "error": e.to_string()
574 })),
575 }
576 }
577 "pretty" => {
578 let parsed: Value = serde_json::from_str(input)
579 .context("Invalid JSON input")?;
580 let pretty = serde_json::to_string_pretty(&parsed)?;
581
582 Ok(json!({
583 "result": pretty,
584 "action": "pretty"
585 }))
586 }
587 "minify" => {
588 let parsed: Value = serde_json::from_str(input)
589 .context("Invalid JSON input")?;
590 let minified = serde_json::to_string(&parsed)?;
591
592 Ok(json!({
593 "result": minified,
594 "action": "minify",
595 "original_length": input.len(),
596 "minified_length": minified.len()
597 }))
598 }
599 "query" => {
600 let query = args["query"].as_str().context("Missing 'query' parameter")?;
601 let parsed: Value = serde_json::from_str(input)
602 .context("Invalid JSON input")?;
603 let result = json_query(&parsed, query);
604
605 Ok(json!({
606 "query": query,
607 "result": result,
608 "found": !result.is_null()
609 }))
610 }
611 "merge" => {
612 let merge_with = args["merge_with"].as_str()
613 .context("Missing 'merge_with' parameter")?;
614 let mut base: Value = serde_json::from_str(input)
615 .context("Invalid JSON in 'input'")?;
616 let overlay: Value = serde_json::from_str(merge_with)
617 .context("Invalid JSON in 'merge_with'")?;
618
619 json_merge(&mut base, &overlay);
620 let result = serde_json::to_string_pretty(&base)?;
621
622 Ok(json!({
623 "result": result,
624 "action": "merge"
625 }))
626 }
627 "keys" => {
628 let parsed: Value = serde_json::from_str(input)
629 .context("Invalid JSON input")?;
630
631 let keys = match &parsed {
632 Value::Object(map) => map.keys().cloned().collect::<Vec<_>>(),
633 _ => return Err(anyhow::anyhow!("Input is not a JSON object")),
634 };
635
636 Ok(json!({
637 "keys": keys,
638 "count": keys.len()
639 }))
640 }
641 "flatten" => {
642 let parsed: Value = serde_json::from_str(input)
643 .context("Invalid JSON input")?;
644 let mut flat = serde_json::Map::new();
645 json_flatten(&parsed, "", &mut flat);
646
647 let count = flat.len();
648 Ok(json!({
649 "result": Value::Object(flat),
650 "count": count
651 }))
652 }
653 _ => Err(anyhow::anyhow!("Unknown JSON action: {}", action)),
654 }
655 }
656
657 pub async fn text(&self, args: Value) -> Result<Value> {
660 let text = args["text"].as_str().context("Missing 'text' parameter")?;
661 let action = args["action"].as_str().context("Missing 'action' parameter")?;
662 let width = args["width"].as_u64().unwrap_or(80) as usize;
663
664 match action {
665 "uppercase" => Ok(json!({ "result": text.to_uppercase() })),
666 "lowercase" => Ok(json!({ "result": text.to_lowercase() })),
667 "title_case" => {
668 let result: String = text.split_whitespace()
669 .map(|word| {
670 let mut chars = word.chars();
671 match chars.next() {
672 Some(c) => format!("{}{}", c.to_uppercase(), chars.as_str().to_lowercase()),
673 None => String::new(),
674 }
675 })
676 .collect::<Vec<_>>()
677 .join(" ");
678 Ok(json!({ "result": result }))
679 }
680 "snake_case" => {
681 let result = to_snake_case(text);
682 Ok(json!({ "result": result }))
683 }
684 "camel_case" => {
685 let result = to_camel_case(text);
686 Ok(json!({ "result": result }))
687 }
688 "kebab_case" => {
689 let result = to_kebab_case(text);
690 Ok(json!({ "result": result }))
691 }
692 "sort_lines" => {
693 let mut lines: Vec<&str> = text.lines().collect();
694 lines.sort();
695 Ok(json!({ "result": lines.join("\n") }))
696 }
697 "reverse_lines" => {
698 let mut lines: Vec<&str> = text.lines().collect();
699 lines.reverse();
700 Ok(json!({ "result": lines.join("\n") }))
701 }
702 "unique_lines" => {
703 let mut seen = std::collections::HashSet::new();
704 let lines: Vec<&str> = text.lines()
705 .filter(|line| seen.insert(*line))
706 .collect();
707 let removed = text.lines().count() - lines.len();
708 Ok(json!({
709 "result": lines.join("\n"),
710 "duplicates_removed": removed
711 }))
712 }
713 "trim_lines" => {
714 let lines: Vec<&str> = text.lines()
715 .map(|l| l.trim())
716 .collect();
717 Ok(json!({ "result": lines.join("\n") }))
718 }
719 "number_lines" => {
720 let lines: Vec<String> = text.lines()
721 .enumerate()
722 .map(|(i, l)| format!("{:>4} | {}", i + 1, l))
723 .collect();
724 Ok(json!({ "result": lines.join("\n") }))
725 }
726 "wrap" => {
727 let lines: Vec<String> = text.lines()
728 .flat_map(|line| wrap_line(line, width))
729 .collect();
730 Ok(json!({ "result": lines.join("\n"), "width": width }))
731 }
732 "truncate" => {
733 let result = if text.len() > width {
734 format!("{}...", &text[..width.saturating_sub(3)])
735 } else {
736 text.to_string()
737 };
738 Ok(json!({
739 "result": result,
740 "truncated": text.len() > width,
741 "original_length": text.len()
742 }))
743 }
744 "stats" => {
745 let bytes = text.len();
746 let mut line_count = 0usize;
747 let mut char_count = 0usize;
748 let mut word_count = 0usize;
749 let mut longest_line = 0usize;
750 let mut shortest_line = usize::MAX;
751 let mut in_word = false;
752 let mut line_len = 0usize;
753
754 for c in text.chars() {
755 char_count += 1;
756 if c == '\n' {
757 line_count += 1;
758 longest_line = longest_line.max(line_len);
759 shortest_line = shortest_line.min(line_len);
760 line_len = 0;
761 in_word = false;
762 } else {
763 line_len += 1;
764 if c.is_whitespace() {
765 in_word = false;
766 } else if !in_word {
767 in_word = true;
768 word_count += 1;
769 }
770 }
771 }
772 if line_len > 0 || text.is_empty() {
774 line_count += 1;
775 longest_line = longest_line.max(line_len);
776 shortest_line = shortest_line.min(line_len);
777 }
778 if text.is_empty() {
779 shortest_line = 0;
780 }
781
782 let unique_words: std::collections::HashSet<String> = text.split_whitespace()
783 .map(|w| w.to_lowercase())
784 .collect();
785
786 let avg_line_len = if line_count == 0 { 0.0 } else {
787 char_count as f64 / line_count as f64
788 };
789
790 Ok(json!({
791 "lines": line_count,
792 "words": word_count,
793 "characters": char_count,
794 "bytes": bytes,
795 "unique_words": unique_words.len(),
796 "average_line_length": format!("{:.1}", avg_line_len),
797 "longest_line": longest_line,
798 "shortest_line": shortest_line
799 }))
800 }
801 _ => Err(anyhow::anyhow!("Unknown text action: {}", action)),
802 }
803 }
804
805 pub async fn archive(&self, args: Value) -> Result<Value> {
808 let action = args["action"].as_str().context("Missing 'action' parameter")?;
809 let path = args["path"].as_str().context("Missing 'path' parameter")?;
810 let format = args["format"].as_str().unwrap_or("zip");
811
812 match action {
813 "create" => self.archive_create(path, &args, format).await,
814 "extract" => self.archive_extract(path, &args, format).await,
815 "list" => self.archive_list(path, format).await,
816 _ => Err(anyhow::anyhow!("Unknown archive action: {}", action)),
817 }
818 }
819
820 async fn archive_create(&self, path: &str, args: &Value, format: &str) -> Result<Value> {
821 let files = args["files"].as_array()
822 .context("Missing 'files' parameter for create")?;
823
824 let file_paths: Vec<&str> = files.iter()
825 .filter_map(|v| v.as_str())
826 .collect();
827
828 match format {
829 "zip" => {
830 let file = fs::File::create(path)
831 .with_context(|| format!("Failed to create archive: {}", path))?;
832 let mut archive = zip::ZipWriter::new(file);
833 let options: zip::write::FileOptions = zip::write::FileOptions::default()
834 .compression_method(zip::CompressionMethod::Deflated);
835
836 for file_path in &file_paths {
837 let p = Path::new(file_path);
838 if p.is_file() {
839 let name = p.file_name().unwrap_or_default().to_string_lossy();
840 archive.start_file(name.to_string(), options)?;
841 let content = fs::read(file_path)?;
842 archive.write_all(&content)?;
843 } else if p.is_dir() {
844 add_dir_to_zip(&mut archive, p, p, options)?;
845 }
846 }
847
848 archive.finish()?;
849 }
850 "tar_gz" => {
851 let file = fs::File::create(path)
852 .with_context(|| format!("Failed to create archive: {}", path))?;
853 let enc = flate2::write::GzEncoder::new(file, flate2::Compression::default());
854 let mut archive = tar::Builder::new(enc);
855
856 for file_path in &file_paths {
857 let p = Path::new(file_path);
858 if p.is_file() {
859 let name = p.file_name().unwrap_or_default().to_string_lossy();
860 archive.append_path_with_name(p, name.as_ref())?;
861 } else if p.is_dir() {
862 let dir_name = p.file_name().unwrap_or_default().to_string_lossy();
863 archive.append_dir_all(dir_name.as_ref(), p)?;
864 }
865 }
866
867 archive.finish()?;
868 }
869 _ => return Err(anyhow::anyhow!("Unsupported archive format: {}", format)),
870 }
871
872 let size = fs::metadata(path)?.len();
873
874 Ok(json!({
875 "success": true,
876 "path": path,
877 "format": format,
878 "files_added": file_paths.len(),
879 "archive_size": size
880 }))
881 }
882
883 async fn archive_extract(&self, path: &str, args: &Value, format: &str) -> Result<Value> {
884 let destination = args["destination"].as_str().unwrap_or(".");
885
886 fs::create_dir_all(destination)
887 .with_context(|| format!("Failed to create destination: {}", destination))?;
888
889 let mut extracted = Vec::new();
890
891 match format {
892 "zip" => {
893 let file = fs::File::open(path)
894 .with_context(|| format!("Failed to open archive: {}", path))?;
895 let mut archive = zip::ZipArchive::new(file)?;
896
897 for i in 0..archive.len() {
898 let mut entry = archive.by_index(i)?;
899 let name = entry.name().to_string();
900 let out_path = Path::new(destination).join(&name);
901
902 if entry.is_dir() {
903 fs::create_dir_all(&out_path)?;
904 } else {
905 if let Some(parent) = out_path.parent() {
906 fs::create_dir_all(parent)?;
907 }
908 let mut outfile = fs::File::create(&out_path)?;
909 std::io::copy(&mut entry, &mut outfile)?;
910 }
911 extracted.push(name);
912 }
913 }
914 "tar_gz" => {
915 let file = fs::File::open(path)
916 .with_context(|| format!("Failed to open archive: {}", path))?;
917 let dec = flate2::read::GzDecoder::new(file);
918 let mut archive = tar::Archive::new(dec);
919
920 for entry in archive.entries()? {
921 let mut entry = entry?;
922 let entry_path = entry.path()?.to_path_buf();
923 let name = entry_path.to_string_lossy().to_string();
924 let out_path = Path::new(destination).join(&entry_path);
925
926 if let Some(parent) = out_path.parent() {
927 fs::create_dir_all(parent)?;
928 }
929 entry.unpack(&out_path)?;
930 extracted.push(name);
931 }
932 }
933 _ => return Err(anyhow::anyhow!("Unsupported archive format: {}", format)),
934 }
935
936 Ok(json!({
937 "success": true,
938 "path": path,
939 "destination": destination,
940 "format": format,
941 "files_extracted": extracted.len(),
942 "files": extracted
943 }))
944 }
945
946 async fn archive_list(&self, path: &str, format: &str) -> Result<Value> {
947 let mut entries = Vec::new();
948
949 match format {
950 "zip" => {
951 let file = fs::File::open(path)
952 .with_context(|| format!("Failed to open archive: {}", path))?;
953 let mut archive = zip::ZipArchive::new(file)?;
954
955 for i in 0..archive.len() {
956 let entry = archive.by_index_raw(i)?;
957 entries.push(json!({
958 "name": entry.name(),
959 "size": entry.size(),
960 "compressed_size": entry.compressed_size(),
961 "is_dir": entry.is_dir()
962 }));
963 }
964 }
965 "tar_gz" => {
966 let file = fs::File::open(path)
967 .with_context(|| format!("Failed to open archive: {}", path))?;
968 let dec = flate2::read::GzDecoder::new(file);
969 let mut archive = tar::Archive::new(dec);
970
971 for entry in archive.entries()? {
972 let entry = entry?;
973 let path = entry.path()?.to_string_lossy().to_string();
974 let size = entry.size();
975
976 entries.push(json!({
977 "name": path,
978 "size": size,
979 "is_dir": entry.header().entry_type().is_dir()
980 }));
981 }
982 }
983 _ => return Err(anyhow::anyhow!("Unsupported archive format: {}", format)),
984 }
985
986 Ok(json!({
987 "path": path,
988 "format": format,
989 "entries": entries,
990 "count": entries.len()
991 }))
992 }
993}
994
995fn json_query(value: &Value, query: &str) -> Value {
998 let mut current = value;
999
1000 for part in query.split('.') {
1001 if let Some(bracket_pos) = part.find('[') {
1002 let key = &part[..bracket_pos];
1003 let idx_str = &part[bracket_pos + 1..part.len() - 1];
1004
1005 if !key.is_empty() {
1006 match current.get(key) {
1007 Some(v) => current = v,
1008 None => return Value::Null,
1009 }
1010 }
1011
1012 match idx_str.parse::<usize>() {
1013 Ok(idx) => match current.get(idx) {
1014 Some(v) => current = v,
1015 None => return Value::Null,
1016 },
1017 Err(_) => return Value::Null,
1018 }
1019 } else {
1020 match current.get(part) {
1021 Some(v) => current = v,
1022 None => return Value::Null,
1023 }
1024 }
1025 }
1026
1027 current.clone()
1028}
1029
1030fn json_merge(base: &mut Value, overlay: &Value) {
1031 match (base, overlay) {
1032 (Value::Object(base_map), Value::Object(overlay_map)) => {
1033 for (key, value) in overlay_map {
1034 let entry = base_map.entry(key.clone()).or_insert(Value::Null);
1035 json_merge(entry, value);
1036 }
1037 }
1038 (base, overlay) => {
1039 *base = overlay.clone();
1040 }
1041 }
1042}
1043
1044fn json_flatten(value: &Value, prefix: &str, result: &mut serde_json::Map<String, Value>) {
1045 match value {
1046 Value::Object(map) => {
1047 for (key, val) in map {
1048 let new_key = if prefix.is_empty() {
1049 key.clone()
1050 } else {
1051 format!("{}.{}", prefix, key)
1052 };
1053 json_flatten(val, &new_key, result);
1054 }
1055 }
1056 Value::Array(arr) => {
1057 for (i, val) in arr.iter().enumerate() {
1058 let new_key = format!("{}[{}]", prefix, i);
1059 json_flatten(val, &new_key, result);
1060 }
1061 }
1062 _ => {
1063 result.insert(prefix.to_string(), value.clone());
1064 }
1065 }
1066}
1067
1068fn to_snake_case(s: &str) -> String {
1069 let mut result = String::new();
1070 for (i, c) in s.chars().enumerate() {
1071 if c.is_uppercase() {
1072 if i > 0 {
1073 result.push('_');
1074 }
1075 result.push(c.to_lowercase().next().unwrap());
1076 } else if c == ' ' || c == '-' {
1077 result.push('_');
1078 } else {
1079 result.push(c);
1080 }
1081 }
1082 result
1083}
1084
1085fn to_camel_case(s: &str) -> String {
1086 let parts: Vec<&str> = s.split(['_', '-', ' '])
1087 .filter(|p| !p.is_empty())
1088 .collect();
1089 let mut result = String::new();
1090 for (i, part) in parts.iter().enumerate() {
1091 if i == 0 {
1092 result.push_str(&part.to_lowercase());
1093 } else {
1094 let mut chars = part.chars();
1095 if let Some(c) = chars.next() {
1096 result.push(c.to_uppercase().next().unwrap());
1097 result.push_str(&chars.as_str().to_lowercase());
1098 }
1099 }
1100 }
1101 result
1102}
1103
1104fn to_kebab_case(s: &str) -> String {
1105 let mut result = String::new();
1106 for (i, c) in s.chars().enumerate() {
1107 if c.is_uppercase() {
1108 if i > 0 {
1109 result.push('-');
1110 }
1111 result.push(c.to_lowercase().next().unwrap());
1112 } else if c == '_' || c == ' ' {
1113 result.push('-');
1114 } else {
1115 result.push(c);
1116 }
1117 }
1118 result
1119}
1120
1121fn wrap_line(line: &str, width: usize) -> Vec<String> {
1122 if line.len() <= width {
1123 return vec![line.to_string()];
1124 }
1125
1126 let mut lines = Vec::new();
1127 let mut current = String::new();
1128
1129 for word in line.split_whitespace() {
1130 if current.is_empty() {
1131 current = word.to_string();
1132 } else if current.len() + 1 + word.len() <= width {
1133 current.push(' ');
1134 current.push_str(word);
1135 } else {
1136 lines.push(current);
1137 current = word.to_string();
1138 }
1139 }
1140
1141 if !current.is_empty() {
1142 lines.push(current);
1143 }
1144
1145 if lines.is_empty() {
1146 vec![line.to_string()]
1147 } else {
1148 lines
1149 }
1150}
1151
1152fn add_dir_to_zip<W: IoWrite + std::io::Seek>(
1153 archive: &mut zip::ZipWriter<W>,
1154 dir: &Path,
1155 base: &Path,
1156 options: zip::write::FileOptions,
1157) -> Result<()> {
1158 for entry in walkdir::WalkDir::new(dir) {
1159 let entry = entry?;
1160 let path = entry.path();
1161 let relative = path.strip_prefix(base).unwrap_or(path);
1162
1163 if path.is_file() {
1164 archive.start_file(relative.to_string_lossy().to_string(), options)?;
1165 let content = fs::read(path)?;
1166 archive.write_all(&content)?;
1167 } else if path.is_dir() && path != base {
1168 archive.add_directory(relative.to_string_lossy().to_string(), options)?;
1169 }
1170 }
1171 Ok(())
1172}