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