worktree_setup_operations 0.3.0

File operations for worktree-setup
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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
//! Operation planning - enumerate operations with file counts without executing.

#![cfg_attr(feature = "fail-on-warnings", deny(warnings))]
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
#![allow(clippy::multiple_crate_versions)]

use std::path::{Path, PathBuf};

use worktree_setup_config::LoadedConfig;
use worktree_setup_copy::count_files_with_progress;

use crate::ApplyConfigOptions;
use crate::error::OperationError;

/// Type of operation to perform.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OperationType {
    /// Create a symlink.
    Symlink,
    /// Copy file/directory (skip if exists).
    Copy,
    /// Overwrite file/directory.
    Overwrite,
    /// Copy from glob pattern match.
    CopyGlob,
    /// Copy template file.
    Template,
    /// Copy unstaged/untracked file.
    Unstaged,
}

impl std::fmt::Display for OperationType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Symlink => write!(f, "symlink"),
            Self::Copy | Self::CopyGlob => write!(f, "copy"),
            Self::Overwrite => write!(f, "overwrite"),
            Self::Template => write!(f, "template"),
            Self::Unstaged => write!(f, "unstaged"),
        }
    }
}

/// A planned operation with metadata for progress display.
#[derive(Debug, Clone)]
pub struct PlannedOperation {
    /// Display path (relative to config).
    pub display_path: String,
    /// Type of operation.
    pub operation_type: OperationType,
    /// Source path (absolute).
    pub source: PathBuf,
    /// Target path (absolute).
    pub target: PathBuf,
    /// Number of files (1 for single files, N for directories).
    pub file_count: u64,
    /// Whether this is a directory operation.
    pub is_directory: bool,
    /// Whether this operation will be skipped.
    pub will_skip: bool,
    /// Reason for skipping (if applicable).
    pub skip_reason: Option<String>,
    /// Whether to force-overwrite existing targets.
    pub force_overwrite: bool,
}

/// Resolve a path from config, handling repo-root-relative paths.
///
/// Paths starting with `/` are relative to the base (repo root).
/// Other paths are relative to the config file's directory.
///
/// # Arguments
///
/// * `base` - The base path (`main_worktree` or `target_worktree`)
/// * `config_relative_dir` - Relative path from repo root to config directory
/// * `path` - The path from the config file
///
/// # Returns
///
/// A tuple of (`resolved_path`, `display_path`)
fn resolve_path(base: &Path, config_relative_dir: &Path, path: &str) -> (PathBuf, String) {
    path.strip_prefix('/').map_or_else(
        || {
            // Config-relative path (e.g., "data" -> "apps/myapp/data")
            let display = config_relative_dir.join(path);
            (base.join(&display), display.to_string_lossy().to_string())
        },
        |stripped| {
            // Repo-root-relative path (e.g., "/.nix" -> ".nix")
            (base.join(stripped), stripped.to_string())
        },
    )
}

/// Plan all operations for a config without executing.
///
/// This enumerates all operations that would be performed, along with file counts
/// for progress display. Operations are returned in execution order.
///
/// # Arguments
///
/// * `config` - The loaded configuration
/// * `main_worktree` - Path to the main worktree (source)
/// * `target_worktree` - Path to the target worktree (destination)
/// * `options` - Options to override config settings
///
/// # Errors
///
/// * If glob pattern matching fails
pub fn plan_operations(
    config: &LoadedConfig,
    main_worktree: &Path,
    target_worktree: &Path,
    options: &ApplyConfigOptions,
) -> Result<Vec<PlannedOperation>, OperationError> {
    plan_operations_with_progress(
        config,
        main_worktree,
        target_worktree,
        options,
        &|_, _, _, _| {},
    )
}

/// Shared context for planning operations.
struct PlanContext<'a, F> {
    config_relative_dir: &'a Path,
    main_worktree: &'a Path,
    target_worktree: &'a Path,
    overwrite: bool,
    on_progress: &'a F,
    total_ops: usize,
}

/// Plan all operations for a config with progress reporting.
///
/// This is like `plan_operations` but reports progress during scanning,
/// which is useful for displaying a progress bar to the user.
///
/// The progress callback receives:
/// - `current_op`: Current operation index (1-based)
/// - `total_ops`: Total number of operations to scan
/// - `path`: Path being scanned
/// - `file_count`: Current file count (Some during directory scan, None for quick checks)
///
/// # Arguments
///
/// * `config` - The loaded configuration
/// * `main_worktree` - Path to the main worktree (source)
/// * `target_worktree` - Path to the target worktree (destination)
/// * `options` - Options to override config settings
/// * `on_progress` - Progress callback
///
/// # Errors
///
/// * If glob pattern matching fails
pub fn plan_operations_with_progress<F>(
    config: &LoadedConfig,
    main_worktree: &Path,
    target_worktree: &Path,
    options: &ApplyConfigOptions,
    on_progress: &F,
) -> Result<Vec<PlannedOperation>, OperationError>
where
    F: Fn(usize, usize, &str, Option<u64>),
{
    let config_relative_dir = config
        .config_dir
        .strip_prefix(main_worktree)
        .unwrap_or(&config.config_dir);

    let total_ops = config.config.symlinks.len()
        + config.config.copy.len()
        + config.config.overwrite.len()
        + config.config.copy_glob.len()
        + config.config.templates.len();

    let ctx = PlanContext {
        config_relative_dir,
        main_worktree,
        target_worktree,
        overwrite: options.overwrite_existing,
        on_progress,
        total_ops,
    };

    let mut current_op = 0usize;
    let mut operations = Vec::new();

    operations.extend(plan_symlink_ops(
        &ctx,
        &mut current_op,
        &config.config.symlinks,
    ));
    operations.extend(plan_copy_ops(&ctx, &mut current_op, &config.config.copy));
    operations.extend(plan_overwrite_ops(
        &ctx,
        &mut current_op,
        &config.config.overwrite,
    ));
    operations.extend(plan_glob_ops(
        &ctx,
        &mut current_op,
        &config.config.copy_glob,
    )?);
    operations.extend(plan_template_ops(
        &ctx,
        &mut current_op,
        &config.config.templates,
    ));

    Ok(operations)
}

/// Plan symlink operations.
fn plan_symlink_ops<F>(
    ctx: &PlanContext<'_, F>,
    current_op: &mut usize,
    symlinks: &[String],
) -> Vec<PlannedOperation>
where
    F: Fn(usize, usize, &str, Option<u64>),
{
    let mut operations = Vec::new();

    for symlink_path in symlinks {
        *current_op += 1;
        let (source, display_str) =
            resolve_path(ctx.main_worktree, ctx.config_relative_dir, symlink_path);
        let (target, _) = resolve_path(ctx.target_worktree, ctx.config_relative_dir, symlink_path);

        (ctx.on_progress)(*current_op, ctx.total_ops, &display_str, None);

        let (will_skip, skip_reason, force) = if !source.exists() {
            (true, Some("not found".to_string()), false)
        } else if target.exists() || target.is_symlink() {
            if ctx.overwrite {
                (false, None, true)
            } else {
                (true, Some("exists".to_string()), false)
            }
        } else {
            (false, None, false)
        };

        operations.push(PlannedOperation {
            display_path: display_str,
            operation_type: OperationType::Symlink,
            source,
            target,
            file_count: 0,
            is_directory: false,
            will_skip,
            skip_reason,
            force_overwrite: force,
        });
    }

    operations
}

/// Plan explicit copy operations.
fn plan_copy_ops<F>(
    ctx: &PlanContext<'_, F>,
    current_op: &mut usize,
    copies: &[String],
) -> Vec<PlannedOperation>
where
    F: Fn(usize, usize, &str, Option<u64>),
{
    let mut operations = Vec::new();

    for copy_path in copies {
        *current_op += 1;
        let (source, display_str) =
            resolve_path(ctx.main_worktree, ctx.config_relative_dir, copy_path);
        let (target, _) = resolve_path(ctx.target_worktree, ctx.config_relative_dir, copy_path);

        (ctx.on_progress)(*current_op, ctx.total_ops, &display_str, None);

        let (will_skip, skip_reason, file_count, is_directory, op_type) = if !source.exists() {
            (
                true,
                Some("not found".to_string()),
                0,
                false,
                OperationType::Copy,
            )
        } else if target.exists() {
            if ctx.overwrite {
                let is_dir = source.is_dir();
                let count = if is_dir {
                    count_files_with_progress(&source, |n| {
                        (ctx.on_progress)(*current_op, ctx.total_ops, &display_str, Some(n));
                    })
                } else {
                    1
                };
                (false, None, count, is_dir, OperationType::Overwrite)
            } else {
                (
                    true,
                    Some("exists".to_string()),
                    0,
                    false,
                    OperationType::Copy,
                )
            }
        } else {
            let is_dir = source.is_dir();
            let count = if is_dir {
                count_files_with_progress(&source, |n| {
                    (ctx.on_progress)(*current_op, ctx.total_ops, &display_str, Some(n));
                })
            } else {
                1
            };
            (false, None, count, is_dir, OperationType::Copy)
        };

        operations.push(PlannedOperation {
            display_path: display_str,
            operation_type: op_type,
            source,
            target,
            file_count,
            is_directory,
            will_skip,
            skip_reason,
            force_overwrite: false,
        });
    }

    operations
}

/// Plan overwrite operations.
fn plan_overwrite_ops<F>(
    ctx: &PlanContext<'_, F>,
    current_op: &mut usize,
    overwrites: &[String],
) -> Vec<PlannedOperation>
where
    F: Fn(usize, usize, &str, Option<u64>),
{
    let mut operations = Vec::new();

    for overwrite_path in overwrites {
        *current_op += 1;
        let (source, display_str) =
            resolve_path(ctx.main_worktree, ctx.config_relative_dir, overwrite_path);
        let (target, _) =
            resolve_path(ctx.target_worktree, ctx.config_relative_dir, overwrite_path);

        (ctx.on_progress)(*current_op, ctx.total_ops, &display_str, None);

        let (will_skip, skip_reason, file_count, is_directory) = if source.exists() {
            let is_dir = source.is_dir();
            let count = if is_dir {
                count_files_with_progress(&source, |n| {
                    (ctx.on_progress)(*current_op, ctx.total_ops, &display_str, Some(n));
                })
            } else {
                1
            };
            (false, None, count, is_dir)
        } else {
            (true, Some("not found".to_string()), 0, false)
        };

        operations.push(PlannedOperation {
            display_path: display_str,
            operation_type: OperationType::Overwrite,
            source,
            target,
            file_count,
            is_directory,
            will_skip,
            skip_reason,
            force_overwrite: false,
        });
    }

    operations
}

/// Plan glob copy operations.
///
/// # Errors
///
/// * If glob pattern matching fails
fn plan_glob_ops<F>(
    ctx: &PlanContext<'_, F>,
    current_op: &mut usize,
    patterns: &[String],
) -> Result<Vec<PlannedOperation>, OperationError>
where
    F: Fn(usize, usize, &str, Option<u64>),
{
    let mut operations = Vec::new();

    for pattern in patterns {
        *current_op += 1;

        let (search_dir, display_prefix, glob_pattern) = pattern.strip_prefix('/').map_or_else(
            || {
                (
                    ctx.main_worktree.join(ctx.config_relative_dir),
                    ctx.config_relative_dir.to_path_buf(),
                    pattern.as_str(),
                )
            },
            |stripped| (ctx.main_worktree.to_path_buf(), PathBuf::new(), stripped),
        );

        let full_pattern = search_dir.join(glob_pattern).to_string_lossy().to_string();

        (ctx.on_progress)(*current_op, ctx.total_ops, pattern, None);

        for entry in glob::glob(&full_pattern)? {
            if let Ok(source) = entry
                && let Ok(rel_path) = source.strip_prefix(&search_dir)
            {
                let target = if pattern.starts_with('/') {
                    ctx.target_worktree.join(rel_path)
                } else {
                    ctx.target_worktree
                        .join(ctx.config_relative_dir)
                        .join(rel_path)
                };
                let display_path = if display_prefix.as_os_str().is_empty() {
                    rel_path.to_path_buf()
                } else {
                    display_prefix.join(rel_path)
                };

                let (will_skip, skip_reason, op_type) = if target.exists() {
                    if ctx.overwrite {
                        (false, None, OperationType::Overwrite)
                    } else {
                        (true, Some("exists".to_string()), OperationType::CopyGlob)
                    }
                } else {
                    (false, None, OperationType::CopyGlob)
                };

                operations.push(PlannedOperation {
                    display_path: display_path.to_string_lossy().to_string(),
                    operation_type: op_type,
                    source,
                    target,
                    file_count: 1,
                    is_directory: false,
                    will_skip,
                    skip_reason,
                    force_overwrite: false,
                });
            }
        }
    }

    Ok(operations)
}

/// Plan template operations.
fn plan_template_ops<F>(
    ctx: &PlanContext<'_, F>,
    current_op: &mut usize,
    templates: &[worktree_setup_config::TemplateMapping],
) -> Vec<PlannedOperation>
where
    F: Fn(usize, usize, &str, Option<u64>),
{
    let mut operations = Vec::new();

    for template in templates {
        *current_op += 1;
        let (source, source_display) =
            resolve_path(ctx.main_worktree, ctx.config_relative_dir, &template.source);
        let (target, target_display) = resolve_path(
            ctx.target_worktree,
            ctx.config_relative_dir,
            &template.target,
        );
        let display_path = format!("{source_display} -> {target_display}");

        (ctx.on_progress)(*current_op, ctx.total_ops, &display_path, None);

        let (will_skip, skip_reason, op_type) = if !source.exists() {
            (true, Some("not found".to_string()), OperationType::Template)
        } else if target.exists() {
            if ctx.overwrite {
                (false, None, OperationType::Overwrite)
            } else {
                (true, Some("exists".to_string()), OperationType::Template)
            }
        } else {
            (false, None, OperationType::Template)
        };

        operations.push(PlannedOperation {
            display_path,
            operation_type: op_type,
            source,
            target,
            file_count: 1,
            is_directory: false,
            will_skip,
            skip_reason,
            force_overwrite: false,
        });
    }

    operations
}

/// Plan unstaged file operations.
///
/// This is separate from `plan_operations` so the caller can show a different
/// progress indicator for the git status check.
///
/// # Arguments
///
/// * `unstaged_files` - List of unstaged/untracked file paths from git
/// * `main_worktree` - Path to the main worktree (source)
/// * `target_worktree` - Path to the target worktree (destination)
///
/// # Returns
///
/// Vector of planned operations for unstaged files
#[must_use]
pub fn plan_unstaged_operations(
    unstaged_files: &[String],
    main_worktree: &Path,
    target_worktree: &Path,
) -> Vec<PlannedOperation> {
    let mut operations = Vec::new();

    for file in unstaged_files {
        let source = main_worktree.join(file);
        let target = target_worktree.join(file);

        // Only plan if source exists
        if source.exists() {
            operations.push(PlannedOperation {
                display_path: file.clone(),
                operation_type: OperationType::Unstaged,
                source,
                target,
                file_count: 1,
                is_directory: false,
                will_skip: false,
                skip_reason: None,
                force_overwrite: false,
            });
        }
    }

    operations
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;
    use worktree_setup_config::Config;

    fn create_test_config(dir: &Path) -> LoadedConfig {
        LoadedConfig {
            config: Config {
                description: "Test".to_string(),
                symlinks: vec!["data".to_string()],
                copy: vec!["config.json".to_string()],
                overwrite: vec!["settings.json".to_string()],
                ..Default::default()
            },
            config_path: dir.join("worktree.config.toml"),
            config_dir: dir.to_path_buf(),
            relative_path: "worktree.config.toml".to_string(),
        }
    }

    #[test]
    fn test_plan_operations_basic() {
        let main_dir = TempDir::new().unwrap();
        let target_dir = TempDir::new().unwrap();

        // Create source files
        fs::create_dir_all(main_dir.path().join("data")).unwrap();
        fs::write(main_dir.path().join("config.json"), "{}").unwrap();
        fs::write(main_dir.path().join("settings.json"), "{}").unwrap();

        let config = create_test_config(main_dir.path());
        let options = ApplyConfigOptions::default();

        let ops = plan_operations(&config, main_dir.path(), target_dir.path(), &options).unwrap();

        assert_eq!(ops.len(), 3);
        assert_eq!(ops[0].operation_type, OperationType::Symlink);
        assert_eq!(ops[1].operation_type, OperationType::Copy);
        assert_eq!(ops[2].operation_type, OperationType::Overwrite);
    }

    #[test]
    fn test_plan_operations_skip_existing() {
        let main_dir = TempDir::new().unwrap();
        let target_dir = TempDir::new().unwrap();

        // Create source and target files
        fs::write(main_dir.path().join("config.json"), "{}").unwrap();
        fs::write(target_dir.path().join("config.json"), "existing").unwrap();

        let config = LoadedConfig {
            config: Config {
                copy: vec!["config.json".to_string()],
                ..Default::default()
            },
            config_path: main_dir.path().join("worktree.config.toml"),
            config_dir: main_dir.path().to_path_buf(),
            relative_path: "worktree.config.toml".to_string(),
        };
        let options = ApplyConfigOptions::default();

        let ops = plan_operations(&config, main_dir.path(), target_dir.path(), &options).unwrap();

        assert_eq!(ops.len(), 1);
        assert!(ops[0].will_skip);
        assert_eq!(ops[0].skip_reason, Some("exists".to_string()));
    }

    #[test]
    fn test_plan_operations_directory_file_count() {
        let main_dir = TempDir::new().unwrap();
        let target_dir = TempDir::new().unwrap();

        // Create a directory with files
        let data_dir = main_dir.path().join("data");
        fs::create_dir_all(&data_dir).unwrap();
        fs::write(data_dir.join("file1.txt"), "1").unwrap();
        fs::write(data_dir.join("file2.txt"), "2").unwrap();
        fs::create_dir(data_dir.join("subdir")).unwrap();
        fs::write(data_dir.join("subdir/file3.txt"), "3").unwrap();

        let config = LoadedConfig {
            config: Config {
                copy: vec!["data".to_string()],
                ..Default::default()
            },
            config_path: main_dir.path().join("worktree.config.toml"),
            config_dir: main_dir.path().to_path_buf(),
            relative_path: "worktree.config.toml".to_string(),
        };
        let options = ApplyConfigOptions::default();

        let ops = plan_operations(&config, main_dir.path(), target_dir.path(), &options).unwrap();

        assert_eq!(ops.len(), 1);
        assert!(ops[0].is_directory);
        assert_eq!(ops[0].file_count, 3);
    }

    #[test]
    fn test_plan_operations_with_progress_callback() {
        use std::cell::RefCell;

        let main_dir = TempDir::new().unwrap();
        let target_dir = TempDir::new().unwrap();

        // Create source files
        fs::create_dir_all(main_dir.path().join("data")).unwrap();
        fs::write(main_dir.path().join("config.json"), "{}").unwrap();

        let config = LoadedConfig {
            config: Config {
                symlinks: vec!["data".to_string()],
                copy: vec!["config.json".to_string()],
                ..Default::default()
            },
            config_path: main_dir.path().join("worktree.config.toml"),
            config_dir: main_dir.path().to_path_buf(),
            relative_path: "worktree.config.toml".to_string(),
        };
        let options = ApplyConfigOptions::default();

        let progress_calls = RefCell::new(Vec::new());
        let ops = plan_operations_with_progress(
            &config,
            main_dir.path(),
            target_dir.path(),
            &options,
            &|current, total, path, _file_count| {
                progress_calls
                    .borrow_mut()
                    .push((current, total, path.to_string()));
            },
        )
        .unwrap();

        let calls = progress_calls.into_inner();
        assert_eq!(ops.len(), 2);
        assert_eq!(calls.len(), 2);
        assert_eq!(calls[0], (1, 2, "data".to_string()));
        assert_eq!(calls[1], (2, 2, "config.json".to_string()));
    }

    #[test]
    fn test_plan_unstaged_operations() {
        let main_dir = TempDir::new().unwrap();
        let target_dir = TempDir::new().unwrap();

        // Create source files
        fs::write(main_dir.path().join("modified.txt"), "content").unwrap();
        fs::write(main_dir.path().join("untracked.txt"), "content").unwrap();

        let unstaged = vec!["modified.txt".to_string(), "untracked.txt".to_string()];
        let ops = plan_unstaged_operations(&unstaged, main_dir.path(), target_dir.path());

        assert_eq!(ops.len(), 2);
        assert_eq!(ops[0].operation_type, OperationType::Unstaged);
        assert_eq!(ops[1].operation_type, OperationType::Unstaged);
    }

    #[test]
    fn test_plan_operations_repo_root_relative_paths() {
        let main_dir = TempDir::new().unwrap();
        let target_dir = TempDir::new().unwrap();

        // Create repo structure:
        // main_dir/
        //   .nix/
        //     flake.nix
        //   .envrc
        //   apps/
        //     myapp/
        //       worktree.config.toml (config is here)

        // Create root-level files
        fs::create_dir_all(main_dir.path().join(".nix")).unwrap();
        fs::write(main_dir.path().join(".nix/flake.nix"), "{}").unwrap();
        fs::write(main_dir.path().join(".envrc"), "use flake").unwrap();

        // Create app directory structure
        let app_dir = main_dir.path().join("apps/myapp");
        fs::create_dir_all(&app_dir).unwrap();

        // Config in subdirectory referencing root files with /
        let config = LoadedConfig {
            config: Config {
                copy: vec!["/.nix".to_string(), "/.envrc".to_string()],
                ..Default::default()
            },
            config_path: app_dir.join("worktree.config.toml"),
            config_dir: app_dir.clone(),
            relative_path: "apps/myapp/worktree.config.toml".to_string(),
        };
        let options = ApplyConfigOptions::default();

        let ops = plan_operations(&config, main_dir.path(), target_dir.path(), &options).unwrap();

        assert_eq!(ops.len(), 2);

        // Check .nix directory
        assert_eq!(ops[0].display_path, ".nix");
        assert_eq!(ops[0].source, main_dir.path().join(".nix"));
        assert_eq!(ops[0].target, target_dir.path().join(".nix"));
        assert!(ops[0].is_directory);
        assert!(!ops[0].will_skip);

        // Check .envrc file
        assert_eq!(ops[1].display_path, ".envrc");
        assert_eq!(ops[1].source, main_dir.path().join(".envrc"));
        assert_eq!(ops[1].target, target_dir.path().join(".envrc"));
        assert!(!ops[1].is_directory);
        assert!(!ops[1].will_skip);
    }

    #[test]
    fn test_plan_operations_mixed_paths() {
        let main_dir = TempDir::new().unwrap();
        let target_dir = TempDir::new().unwrap();

        // Create repo structure with both root and app-level files
        fs::write(main_dir.path().join(".envrc"), "use flake").unwrap();

        let app_dir = main_dir.path().join("apps/myapp");
        fs::create_dir_all(&app_dir).unwrap();
        fs::write(app_dir.join("local.config"), "app config").unwrap();

        // Config with mixed paths: one root-relative, one config-relative
        let config = LoadedConfig {
            config: Config {
                copy: vec![
                    "/.envrc".to_string(),      // root-relative
                    "local.config".to_string(), // config-relative
                ],
                ..Default::default()
            },
            config_path: app_dir.join("worktree.config.toml"),
            config_dir: app_dir.clone(),
            relative_path: "apps/myapp/worktree.config.toml".to_string(),
        };
        let options = ApplyConfigOptions::default();

        let ops = plan_operations(&config, main_dir.path(), target_dir.path(), &options).unwrap();

        assert_eq!(ops.len(), 2);

        // Root-relative path: /.envrc -> .envrc
        assert_eq!(ops[0].display_path, ".envrc");
        assert_eq!(ops[0].source, main_dir.path().join(".envrc"));
        assert_eq!(ops[0].target, target_dir.path().join(".envrc"));

        // Config-relative path: local.config -> apps/myapp/local.config
        assert_eq!(ops[1].display_path, "apps/myapp/local.config");
        assert_eq!(ops[1].source, app_dir.join("local.config"));
        assert_eq!(
            ops[1].target,
            target_dir.path().join("apps/myapp/local.config")
        );
    }

    #[test]
    fn test_plan_operations_template_with_root_paths() {
        let main_dir = TempDir::new().unwrap();
        let target_dir = TempDir::new().unwrap();

        // Create template at root
        fs::write(main_dir.path().join(".env.template"), "KEY=value").unwrap();

        let app_dir = main_dir.path().join("apps/myapp");
        fs::create_dir_all(&app_dir).unwrap();

        let config = LoadedConfig {
            config: Config {
                templates: vec![worktree_setup_config::TemplateMapping {
                    source: "/.env.template".to_string(), // root-relative source
                    target: ".env.local".to_string(),     // config-relative target
                }],
                ..Default::default()
            },
            config_path: app_dir.join("worktree.config.toml"),
            config_dir: app_dir.clone(),
            relative_path: "apps/myapp/worktree.config.toml".to_string(),
        };
        let options = ApplyConfigOptions::default();

        let ops = plan_operations(&config, main_dir.path(), target_dir.path(), &options).unwrap();

        assert_eq!(ops.len(), 1);
        assert_eq!(ops[0].operation_type, OperationType::Template);
        assert_eq!(
            ops[0].display_path,
            ".env.template -> apps/myapp/.env.local"
        );
        assert_eq!(ops[0].source, main_dir.path().join(".env.template"));
        assert_eq!(
            ops[0].target,
            target_dir.path().join("apps/myapp/.env.local")
        );
    }
}