cobble-lang 0.6.1

A modern, Python-like language for creating Minecraft Data Packs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
use crate::commands::validate::{print_validation_report, run_validation};
use crate::config::CobbleConfig;
use crate::pack_format::{PackFormat, SUPPORTED_MINECRAFT_VERSION, SUPPORTED_PACK_FORMAT};
use crate::parser::parse;
use crate::transpiler::Transpiler;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
use zip::write::SimpleFileOptions;
use zip::{CompressionMethod, ZipWriter};

pub struct BuildOptions {
    pub input: Option<PathBuf>,
    pub output: Option<PathBuf>,
    pub namespace: Option<String>,
    pub pack_format: Option<String>,
    pub description: Option<String>,
    pub verbose: bool,
    pub zip: bool,
    pub validate: bool,
    pub commands_json: PathBuf,
}

pub fn build(options: BuildOptions) -> Result<(), String> {
    // Try to find cobble.toml
    let (config, config_dir) = if let Some(config_path) = find_config(&options.input) {
        let config = if options.pack_format.is_some() {
            CobbleConfig::load_unvalidated(&config_path)?
        } else {
            CobbleConfig::load(&config_path)?
        };
        let config_dir = config_path.parent().unwrap().to_path_buf();
        (Some(config), config_dir)
    } else {
        (
            None,
            std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
        )
    };

    // Determine source and output paths
    let source_path = if let Some(ref input) = options.input {
        input.clone()
    } else if let Some(ref cfg) = config {
        config_dir.join(&cfg.build.source)
    } else {
        return Err("No input specified and no cobble.toml found".to_string());
    };

    let output_dir = if let Some(ref output) = options.output {
        output.clone()
    } else if let Some(ref cfg) = config {
        config_dir.join(&cfg.build.output)
    } else {
        PathBuf::from("output")
    };

    // Get namespace from options, config, or use default
    let namespace = options
        .namespace
        .clone()
        .or_else(|| config.as_ref().map(|c| c.project.namespace.clone()))
        .unwrap_or_else(|| "cobble".to_string());

    // Security: Validate namespace to prevent command injection
    validate_namespace(&namespace)?;

    let description = options
        .description
        .clone()
        .or_else(|| config.as_ref().map(|c| c.project.description.clone()))
        .unwrap_or_else(|| "Generated by Cobble".to_string());

    let pack_format = if let Some(ref pack_fmt_str) = options.pack_format {
        PackFormat::parse_format(pack_fmt_str)?
    } else if let Some(ref cfg) = config {
        PackFormat::parse_format(&cfg.project.pack_format)?
    } else {
        SUPPORTED_PACK_FORMAT
    };

    // Validate pack_format against this release's single supported Minecraft target.
    if !pack_format.is_supported() {
        return Err(format!(
            "pack_format must be {} (Minecraft Java Edition {}), got {}.\n\
            Cobble v{} exclusively supports Minecraft Java Edition {}.\n\
            See https://minecraft.wiki/w/Pack_format for version compatibility.",
            SUPPORTED_PACK_FORMAT,
            SUPPORTED_MINECRAFT_VERSION,
            pack_format,
            env!("CARGO_PKG_VERSION"),
            SUPPORTED_MINECRAFT_VERSION
        ));
    }

    // Check if source is a file or directory
    let files_to_compile = if source_path.is_file() {
        vec![source_path.clone()]
    } else if source_path.is_dir() {
        if options.input.is_none() {
            if let Some(ref cfg) = config {
                if !cfg.build.entry_points.is_empty() {
                    resolve_entry_points(&source_path, &cfg.build.entry_points)?
                } else {
                    find_cobble_files(&source_path)?
                }
            } else {
                find_cobble_files(&source_path)?
            }
        } else {
            find_cobble_files(&source_path)?
        }
    } else {
        return Err(format!("Source path does not exist: {:?}", source_path));
    };

    if options.verbose {
        println!("Building {} file(s)...", files_to_compile.len());
        println!("Namespace: {}", namespace);
        println!("Pack format: {}", pack_format);
        println!("Description: {}", description);
    } else {
        println!("Building {} file(s)...", files_to_compile.len());
    }

    let final_output_dir = output_dir.clone();
    let build_output_dir = if options.validate && !files_to_compile.is_empty() {
        staging_output_dir(&final_output_dir)?
    } else {
        final_output_dir.clone()
    };

    // Create transpiler
    let mut transpiler = Transpiler::new(namespace.clone(), build_output_dir.clone());
    transpiler.set_description(description);
    transpiler.set_pack_format(pack_format);

    if files_to_compile.is_empty() {
        transpiler
            .write_data_pack()
            .map_err(|e| format!("Failed to clean data pack output: {}", e))?;
        return Err("No Cobble files found to compile".to_string());
    }

    // Compile all files
    for file_path in &files_to_compile {
        if options.verbose {
            println!(
                "  • Compiling: {:?}",
                file_path.file_name().unwrap_or_default()
            );
        } else {
            print!(
                "  • Compiling: {:?}",
                file_path.file_name().unwrap_or_default()
            );
        }

        let src = fs::read_to_string(file_path)
            .map_err(|e| format!("Failed to read {:?}: {}", file_path, e))?;

        let program = parse(&src).map_err(|errors| {
            format!(
                "Parse failed for {:?}:\n  {}",
                file_path,
                errors.join("\n  ")
            )
        })?;

        // Set current file for import resolution and source tracking
        transpiler.set_current_file_with_source(file_path, &src);

        transpiler
            .transpile(&program)
            .map_err(|e| format!("Transpilation failed for {:?}: {}", file_path, e))?;
    }

    // Write data pack
    transpiler
        .write_data_pack()
        .map_err(|e| format!("Failed to write data pack: {}", e))?;

    if options.validate {
        println!("Validating generated commands...");
        let report = match run_validation(&build_output_dir, &options.commands_json) {
            Ok(report) => report,
            Err(error) => {
                if build_output_dir != final_output_dir {
                    let _ = fs::remove_dir_all(&build_output_dir);
                }
                return Err(error);
            }
        };
        print_validation_report(&report, &options.commands_json, &build_output_dir);
        if !report.errors.is_empty() || !report.source_map_errors.is_empty() {
            if build_output_dir != final_output_dir {
                let _ = fs::remove_dir_all(&build_output_dir);
            }
            return Err(format!(
                "{} validation error(s) found",
                report.errors.len() + report.source_map_errors.len()
            ));
        }
        if build_output_dir != final_output_dir {
            replace_output_dir(&build_output_dir, &final_output_dir)?;
        }
        println!("✓ Data pack generated at {:?}", final_output_dir);
        println!("✓ All commands valid");
    } else {
        println!("✓ Data pack generated at {:?}", final_output_dir);
    }

    // Create zip if requested
    if options.zip {
        create_zip(&final_output_dir, &namespace)?;
        println!("✓ Created {}.zip", namespace);
    }

    Ok(())
}

/// Validate that namespace contains only safe characters
fn validate_namespace(namespace: &str) -> Result<(), String> {
    if namespace.is_empty() {
        return Err("Namespace cannot be empty".to_string());
    }
    if namespace.len() > 64 {
        return Err(format!(
            "Namespace too long: {} chars (max 64)",
            namespace.len()
        ));
    }
    if !namespace
        .chars()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-' || c == '.')
    {
        return Err(format!(
            "Invalid namespace '{}': Can only contain lowercase letters, digits, underscores, hyphens, and dots.\n\
            Example: 'my_datapack', 'cool-pack.v2'",
            namespace
        ));
    }
    Ok(())
}

fn staging_output_dir(output_dir: &Path) -> Result<PathBuf, String> {
    let parent = output_dir.parent().unwrap_or_else(|| Path::new("."));
    let name = output_dir
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("output");
    let stamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|e| format!("System clock error while creating staging output: {}", e))?
        .as_nanos();
    let staging = parent.join(format!(
        ".{}.cobble-staging-{}-{}",
        name,
        std::process::id(),
        stamp
    ));
    if staging.exists() {
        fs::remove_dir_all(&staging)
            .map_err(|e| format!("Failed to clean staging output {:?}: {}", staging, e))?;
    }
    Ok(staging)
}

fn replace_output_dir(staging_dir: &Path, output_dir: &Path) -> Result<(), String> {
    if output_dir.exists() {
        if output_dir.is_dir() {
            fs::remove_dir_all(output_dir)
                .map_err(|e| format!("Failed to replace output {:?}: {}", output_dir, e))?;
        } else {
            fs::remove_file(output_dir)
                .map_err(|e| format!("Failed to replace output {:?}: {}", output_dir, e))?;
        }
    }
    fs::rename(staging_dir, output_dir).map_err(|e| {
        format!(
            "Failed to move validated data pack from {:?} to {:?}: {}",
            staging_dir, output_dir, e
        )
    })
}

fn find_config(input: &Option<PathBuf>) -> Option<PathBuf> {
    if let Some(path) = input {
        if path.is_file() {
            // If input is a file, look for config in parent directories
            if let Some(parent) = path.parent() {
                return CobbleConfig::find_in_path(parent);
            }
        } else {
            // If input is a directory, look for config in it
            return CobbleConfig::find_in_path(path);
        }
    }
    // Look in current directory
    CobbleConfig::find_in_path(".")
}

fn resolve_entry_points(
    source_dir: &Path,
    entry_points: &[String],
) -> Result<Vec<PathBuf>, String> {
    let mut files = Vec::new();

    for entry_point in entry_points {
        let entry_path = Path::new(entry_point);
        let path = if entry_path.is_absolute() {
            entry_path.to_path_buf()
        } else {
            source_dir.join(entry_path)
        };

        if path.is_file() {
            files.push(path);
        } else if path.is_dir() {
            files.extend(find_cobble_files(&path)?);
        } else {
            return Err(format!("Entry point does not exist: {}", path.display()));
        }
    }

    Ok(files)
}

fn find_cobble_files(dir: &Path) -> Result<Vec<PathBuf>, String> {
    let mut files = Vec::new();

    for entry in WalkDir::new(dir)
        .follow_links(false) // Security: Don't follow symlinks to prevent attacks
        .into_iter()
        .filter_map(|e| e.ok())
    {
        let path = entry.path();
        if path.is_symlink() {
            eprintln!("⚠️  Warning: Skipping symlink: {:?}", path);
            continue;
        }
        if path.is_file() {
            if let Some(ext) = path.extension() {
                if ext == "cbl" || ext == "cobble" {
                    files.push(path.to_path_buf());
                }
            }
        }
    }

    files.sort();
    Ok(files)
}

#[cfg(test)]
#[allow(clippy::items_after_test_module)]
mod tests {
    use super::*;
    use std::sync::Mutex;

    static CWD_LOCK: Mutex<()> = Mutex::new(());

    struct CurrentDirGuard {
        previous: PathBuf,
    }

    impl CurrentDirGuard {
        fn push(path: &Path) -> Self {
            let previous = std::env::current_dir().unwrap();
            std::env::set_current_dir(path).unwrap();
            Self { previous }
        }
    }

    impl Drop for CurrentDirGuard {
        fn drop(&mut self) {
            std::env::set_current_dir(&self.previous).unwrap();
        }
    }

    #[test]
    fn resolves_entry_points_relative_to_source_dir() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let source_dir = temp_dir.path().join("src");
        fs::create_dir_all(&source_dir).unwrap();
        fs::write(source_dir.join("main.cbl"), "def main():\n    pass\n").unwrap();
        fs::write(source_dir.join("utils.cbl"), "def helper():\n    pass\n").unwrap();

        let files = resolve_entry_points(&source_dir, &["main.cbl".to_string()]).unwrap();

        assert_eq!(files, vec![source_dir.join("main.cbl")]);
    }

    #[test]
    fn build_validate_reports_missing_command_tree() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let input_file = temp_dir.path().join("test.cbl");
        let output_dir = temp_dir.path().join("output");
        let commands_json = temp_dir.path().join("missing_commands.json");
        fs::write(&input_file, "def test():\n    /say hello\n").unwrap();

        let error = build(BuildOptions {
            input: Some(input_file),
            output: Some(output_dir.clone()),
            namespace: None,
            pack_format: None,
            description: None,
            verbose: false,
            zip: false,
            validate: true,
            commands_json,
        })
        .unwrap_err();

        assert!(error.contains("Command tree not found"));
        assert!(error.contains("scripts/setup_commands_json.sh 26.1.2"));
        assert!(!temp_dir
            .path()
            .read_dir()
            .unwrap()
            .filter_map(|entry| entry.ok())
            .any(|entry| entry
                .file_name()
                .to_string_lossy()
                .contains(".output.cobble-staging-")));
    }

    #[test]
    fn build_validate_fails_on_invalid_generated_command() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let input_file = temp_dir.path().join("test.cbl");
        let output_dir = temp_dir.path().join("output");
        let commands_json = temp_dir.path().join("commands.json");
        fs::write(&input_file, "def test():\n    /say hello\n").unwrap();
        fs::write(&commands_json, r#"{"type":"root","children":{}}"#).unwrap();

        let error = build(BuildOptions {
            input: Some(input_file),
            output: Some(output_dir.clone()),
            namespace: None,
            pack_format: None,
            description: None,
            verbose: false,
            zip: false,
            validate: true,
            commands_json,
        })
        .unwrap_err();

        assert!(error.contains("validation error(s) found"));
        assert!(!output_dir.exists());
    }

    #[test]
    fn build_validate_preserves_previous_output_on_validation_failure() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let input_file = temp_dir.path().join("test.cbl");
        let output_dir = temp_dir.path().join("output");
        let valid_commands_json = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("data")
            .join("commands.json");
        if !valid_commands_json.exists() {
            return;
        }

        fs::write(&input_file, "def test():\n    /say valid\n").unwrap();
        build(BuildOptions {
            input: Some(input_file.clone()),
            output: Some(output_dir.clone()),
            namespace: None,
            pack_format: None,
            description: None,
            verbose: false,
            zip: false,
            validate: true,
            commands_json: valid_commands_json.clone(),
        })
        .unwrap();

        fs::write(&input_file, "def test():\n    /titel @a actionbar bad\n").unwrap();
        let error = build(BuildOptions {
            input: Some(input_file),
            output: Some(output_dir.clone()),
            namespace: None,
            pack_format: None,
            description: None,
            verbose: false,
            zip: false,
            validate: true,
            commands_json: valid_commands_json,
        })
        .unwrap_err();

        assert!(error.contains("validation error(s) found"));
        let content =
            fs::read_to_string(output_dir.join("data/cobble/function/test.mcfunction")).unwrap();
        assert_eq!(content.trim(), "say valid");
    }

    #[test]
    fn build_fails_on_missing_import_with_importing_file() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let input_file = temp_dir.path().join("main.cbl");
        let output_dir = temp_dir.path().join("output");
        fs::write(&input_file, "import missing\n\ndef test():\n    pass\n").unwrap();

        let error = build(BuildOptions {
            input: Some(input_file.clone()),
            output: Some(output_dir),
            namespace: None,
            pack_format: None,
            description: None,
            verbose: false,
            zip: false,
            validate: false,
            commands_json: PathBuf::from("data/commands.json"),
        })
        .unwrap_err();

        assert!(error.contains("Cannot import 'missing'"));
        assert!(error.contains(&input_file.display().to_string()));
    }

    #[test]
    fn build_fails_on_import_cycle_with_chain() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let main_file = temp_dir.path().join("main.cbl");
        let helper_file = temp_dir.path().join("helper.cbl");
        let output_dir = temp_dir.path().join("output");
        fs::write(&main_file, "import helper\n\ndef main():\n    /say main\n").unwrap();
        fs::write(
            &helper_file,
            "import main\n\ndef helper():\n    /say helper\n",
        )
        .unwrap();

        let error = build(BuildOptions {
            input: Some(main_file.clone()),
            output: Some(output_dir),
            namespace: None,
            pack_format: None,
            description: None,
            verbose: false,
            zip: false,
            validate: false,
            commands_json: PathBuf::from("data/commands.json"),
        })
        .unwrap_err();

        assert!(error.contains("Circular import detected"));
        assert!(error.contains(&main_file.display().to_string()));
        assert!(error.contains(&helper_file.display().to_string()));
    }

    #[test]
    fn cli_pack_format_overrides_invalid_config_value() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let source_dir = temp_dir.path().join("src");
        let output_dir = temp_dir.path().join("output");
        fs::create_dir_all(&source_dir).unwrap();
        fs::write(source_dir.join("main.cbl"), "def main():\n    /say hi\n").unwrap();
        fs::write(
            temp_dir.path().join("cobble.toml"),
            r#"
[project]
name = "Override"
description = "Override"
namespace = "override"
pack_format = "18"

[build]
source = "src"
output = "output"
"#,
        )
        .unwrap();

        build(BuildOptions {
            input: Some(source_dir),
            output: Some(output_dir.clone()),
            namespace: None,
            pack_format: Some("101.1".to_string()),
            description: None,
            verbose: false,
            zip: false,
            validate: false,
            commands_json: PathBuf::from("data/commands.json"),
        })
        .unwrap();

        assert!(output_dir
            .join("data/override/function/main.mcfunction")
            .exists());
    }

    #[test]
    fn empty_source_directory_cleans_previous_output() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let source_dir = temp_dir.path().join("src");
        let output_dir = temp_dir.path().join("output");
        let input_file = source_dir.join("main.cbl");
        fs::create_dir_all(&source_dir).unwrap();
        fs::write(&input_file, "def main():\n    /say hi\n").unwrap();

        let build_once = || {
            build(BuildOptions {
                input: Some(source_dir.clone()),
                output: Some(output_dir.clone()),
                namespace: Some("stale".to_string()),
                pack_format: None,
                description: None,
                verbose: false,
                zip: false,
                validate: false,
                commands_json: PathBuf::from("data/commands.json"),
            })
        };

        build_once().unwrap();
        assert!(output_dir
            .join("data/stale/function/main.mcfunction")
            .exists());

        fs::remove_file(input_file).unwrap();
        let error = build_once().unwrap_err();

        assert!(error.contains("No Cobble files found"));
        assert!(!output_dir
            .join("data/stale/function/main.mcfunction")
            .exists());
    }

    #[test]
    fn zip_contains_only_datapack_files_when_output_is_current_dir() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let _lock = CWD_LOCK.lock().unwrap();
        let _guard = CurrentDirGuard::push(temp_dir.path());
        fs::write("main.cbl", "def main():\n    /say hi\n").unwrap();

        build(BuildOptions {
            input: Some(PathBuf::from("main.cbl")),
            output: Some(PathBuf::from(".")),
            namespace: Some("zipped".to_string()),
            pack_format: None,
            description: None,
            verbose: false,
            zip: true,
            validate: false,
            commands_json: PathBuf::from("data/commands.json"),
        })
        .unwrap();

        let zip_file = fs::File::open(temp_dir.path().join("zipped.zip")).unwrap();
        let mut archive = zip::ZipArchive::new(zip_file).unwrap();
        let names: Vec<String> = (0..archive.len())
            .map(|index| archive.by_index(index).unwrap().name().to_string())
            .collect();

        assert!(names.iter().any(|name| name == "pack.mcmeta"));
        assert!(names
            .iter()
            .any(|name| name == "data/zipped/function/main.mcfunction"));
        assert!(!names.iter().any(|name| name == "main.cbl"));
        assert!(!names.iter().any(|name| name == "zipped.zip"));
        assert!(!names.iter().any(|name| name.starts_with(".cobble/")));
    }
}

fn create_zip(output_dir: &Path, namespace: &str) -> Result<(), String> {
    let zip_path = output_dir.with_file_name(format!("{}.zip", namespace));
    let file =
        fs::File::create(&zip_path).map_err(|e| format!("Failed to create zip file: {}", e))?;

    let mut zip = ZipWriter::new(file);
    let options = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);

    // Add all files from output directory to zip
    for entry in WalkDir::new(output_dir).into_iter().filter_map(|e| e.ok()) {
        let path = entry.path();
        if path.is_file() {
            let relative_path = path
                .strip_prefix(output_dir)
                .map_err(|e| format!("Failed to get relative path: {}", e))?;

            // Convert path to use forward slashes for ZIP (required by Minecraft)
            let zip_path = relative_path.to_string_lossy().replace('\\', "/");
            if zip_path != "pack.mcmeta" && !zip_path.starts_with("data/") {
                continue;
            }

            let file_data =
                fs::read(path).map_err(|e| format!("Failed to read file for zip: {}", e))?;

            zip.start_file(zip_path, options)
                .map_err(|e| format!("Failed to add file to zip: {}", e))?;

            zip.write_all(&file_data)
                .map_err(|e| format!("Failed to write file to zip: {}", e))?;
        }
    }

    zip.finish()
        .map_err(|e| format!("Failed to finalize zip: {}", e))?;

    Ok(())
}