worktree_setup_operations 0.1.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
//! 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 => write!(f, "copy"),
            Self::Overwrite => write!(f, "overwrite"),
            Self::CopyGlob => write!(f, "copy"),
            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>,
}

/// 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,
        &|_, _, _, _| {},
    )
}

/// 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 mut operations = Vec::new();

    // Calculate relative path from repo root to config directory
    let config_relative_dir = config
        .config_dir
        .strip_prefix(main_worktree)
        .unwrap_or(&config.config_dir);

    // Calculate total operations (excluding unstaged - those are handled separately)
    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 mut current_op = 0usize;

    // Plan symlinks
    for symlink_path in &config.config.symlinks {
        current_op += 1;
        let source = main_worktree.join(config_relative_dir).join(symlink_path);
        let target = target_worktree.join(config_relative_dir).join(symlink_path);
        let display_path = config_relative_dir.join(symlink_path);
        let display_str = display_path.to_string_lossy().to_string();

        on_progress(current_op, total_ops, &display_str, None);

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

        operations.push(PlannedOperation {
            display_path: display_str,
            operation_type: OperationType::Symlink,
            source,
            target,
            file_count: 0, // Symlinks don't have file counts
            is_directory: false,
            will_skip,
            skip_reason,
        });
    }

    // Plan explicit copies
    for copy_path in &config.config.copy {
        current_op += 1;
        let source = main_worktree.join(config_relative_dir).join(copy_path);
        let target = target_worktree.join(config_relative_dir).join(copy_path);
        let display_path = config_relative_dir.join(copy_path);
        let display_str = display_path.to_string_lossy().to_string();

        on_progress(current_op, total_ops, &display_str, None);

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

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

    // Plan overwrites
    for overwrite_path in &config.config.overwrite {
        current_op += 1;
        let source = main_worktree.join(config_relative_dir).join(overwrite_path);
        let target = target_worktree
            .join(config_relative_dir)
            .join(overwrite_path);
        let display_path = config_relative_dir.join(overwrite_path);
        let display_str = display_path.to_string_lossy().to_string();

        on_progress(current_op, total_ops, &display_str, None);

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

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

    // Plan glob copies (each pattern counts as 1 operation for progress)
    for pattern in &config.config.copy_glob {
        current_op += 1;
        let search_dir = main_worktree.join(config_relative_dir);
        let full_pattern = search_dir.join(pattern).to_string_lossy().to_string();

        on_progress(current_op, total_ops, pattern, None);

        for entry in glob::glob(&full_pattern)? {
            if let Ok(source) = entry {
                if let Ok(rel_path) = source.strip_prefix(&search_dir) {
                    let target = target_worktree.join(config_relative_dir).join(rel_path);
                    let display_path = config_relative_dir.join(rel_path);

                    let (will_skip, skip_reason) = if target.exists() {
                        (true, Some("exists".to_string()))
                    } else {
                        (false, None)
                    };

                    // Glob matches are always files (globs don't match directories well)
                    operations.push(PlannedOperation {
                        display_path: display_path.to_string_lossy().to_string(),
                        operation_type: OperationType::CopyGlob,
                        source,
                        target,
                        file_count: 1,
                        is_directory: false,
                        will_skip,
                        skip_reason,
                    });
                }
            }
        }
    }

    // Plan templates
    for template in &config.config.templates {
        current_op += 1;
        let source = main_worktree
            .join(config_relative_dir)
            .join(&template.source);
        let target = target_worktree
            .join(config_relative_dir)
            .join(&template.target);
        let display_path = format!(
            "{} -> {}",
            config_relative_dir.join(&template.source).display(),
            config_relative_dir.join(&template.target).display()
        );

        on_progress(current_op, total_ops, &display_path, None);

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

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

    // Note: Unstaged files are NOT planned here - they should be handled separately
    // by the caller who can show a "Checking git status..." spinner first.
    // This avoids the git operation being part of the planning progress bar.

    Ok(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
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,
            });
        }
    }

    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);
    }
}