fastsync 0.7.0

A fast, safe one-way directory synchronization tool for large local folders.
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
//! fastsync 的核心库入口。
//!
//! 这里负责串联“扫描 -> 比较 -> 执行 -> 校验/汇总”的主流程。

rust_i18n::i18n!("locales", fallback = "en");

pub mod cli;
pub mod compare;
pub mod config;
pub mod endpoint;
pub mod error;
pub mod executor;
pub mod hash;
pub mod i18n;
pub mod network;
pub mod plan;
pub mod scan;
pub mod summary;
pub mod verify;

use std::time::Instant;

use tracing::info;

use crate::compare::build_plan_with_endpoints;
use crate::config::SyncConfig;
use crate::endpoint::SyncEndpoints;
use crate::error::Result;
use crate::executor::execute_plan_with_endpoints;
use crate::summary::SyncSummary;
use crate::verify::verify_all_source_files_with_endpoints;

/// 执行一次单向目录同步。
///
/// 输入为已经解析完成的配置,输出为稳定的同步摘要。该函数不负责解析 CLI,
/// 也不直接渲染终端输出,方便后续被测试、GUI 或服务化入口复用。
pub fn run_sync(config: SyncConfig) -> Result<SyncSummary> {
    let endpoints = SyncEndpoints::local(config.source.clone(), config.target.clone());
    run_sync_with_endpoints(config, endpoints)
}

/// 使用给定端点执行一次单向目录同步。
///
/// 当前公开 CLI 会传入本地端点;该入口为后续远端端点接入保留稳定编排层。
pub fn run_sync_with_endpoints(
    config: SyncConfig,
    endpoints: SyncEndpoints,
) -> Result<SyncSummary> {
    let started = Instant::now();
    info!(
        source = %endpoints.source().root().display(),
        target = %endpoints.target().root().display(),
        "{}",
        crate::i18n::tr_current("log.scan_started")
    );

    let source_snapshot = endpoints.scan_source(config.follow_symlinks)?;
    let target_snapshot = endpoints.scan_target(config.follow_symlinks)?;

    info!(
        source_entries = source_snapshot.entries.len(),
        target_entries = target_snapshot.entries.len(),
        "{}",
        crate::i18n::tr_current("log.scan_finished")
    );

    let plan = build_plan_with_endpoints(&config, &endpoints, &source_snapshot, &target_snapshot)?;
    info!(
        operations = plan.operations.len(),
        bytes = plan.bytes_to_copy,
        "{}",
        crate::i18n::tr_current("log.plan_built")
    );

    let mut summary = execute_plan_with_endpoints(&config, &endpoints, &plan)?;
    summary.source = endpoints.source().root().to_path_buf();
    summary.target = endpoints.target().root().to_path_buf();
    summary.source_entries = source_snapshot.entries.len();
    summary.target_entries = target_snapshot.entries.len();
    summary.planned_operations = plan.operations.len();
    summary.bytes_planned = plan.bytes_to_copy;
    summary.blake3_compared_files = plan.blake3_compared_files;

    if !config.dry_run && config.verify_mode.verify_all_files() {
        let verified = verify_all_source_files_with_endpoints(&source_snapshot, &endpoints)?;
        summary.verified_files += verified;
    }

    summary.duration_ms = started.elapsed().as_millis();
    Ok(summary)
}

#[cfg(test)]
mod tests {
    use std::fs;

    use tempfile::tempdir;

    use crate::cli::Cli;
    use crate::config::SyncConfig;

    #[test]
    fn run_sync_copies_new_file() -> std::result::Result<(), Box<dyn std::error::Error>> {
        let source = tempdir()?;
        let target = tempdir()?;
        fs::write(source.path().join("a.txt"), "hello")?;

        let mut cli = Cli::for_test(source.path(), target.path());
        cli.verify = crate::config::VerifyMode::Changed;
        let config = SyncConfig::try_from(cli)?;

        let summary = crate::run_sync(config)?;

        assert_eq!(fs::read_to_string(target.path().join("a.txt"))?, "hello");
        assert_eq!(summary.copied_files, 1);
        assert_eq!(summary.verified_files, 0);
        assert_eq!(summary.errors, 0);
        Ok(())
    }

    #[test]
    fn dry_run_does_not_modify_target() -> std::result::Result<(), Box<dyn std::error::Error>> {
        let source = tempdir()?;
        let target = tempdir()?;
        fs::write(source.path().join("a.txt"), "hello")?;

        let mut cli = Cli::for_test(source.path(), target.path());
        cli.dry_run = true;
        let config = SyncConfig::try_from(cli)?;

        let summary = crate::run_sync(config)?;

        assert!(!target.path().join("a.txt").exists());
        assert_eq!(summary.planned_operations, 1);
        assert_eq!(summary.copied_files, 1);
        Ok(())
    }

    #[test]
    fn fast_compare_hashes_same_size_file_when_metadata_differs()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let source = tempdir()?;
        let target = tempdir()?;
        let source_file = source.path().join("a.txt");
        let target_file = target.path().join("a.txt");
        fs::write(&source_file, "new-value")?;
        fs::write(&target_file, "old-value")?;

        let source_timestamp = filetime::FileTime::from_unix_time(1_700_000_100, 0);
        let target_timestamp = filetime::FileTime::from_unix_time(1_700_000_000, 0);
        filetime::set_file_mtime(&source_file, source_timestamp)?;
        filetime::set_file_mtime(&target_file, target_timestamp)?;

        let cli = Cli::for_test(source.path(), target.path());
        let config = SyncConfig::try_from(cli)?;

        let summary = crate::run_sync(config)?;

        assert_eq!(fs::read_to_string(target_file)?, "new-value");
        assert_eq!(summary.copied_files, 1);
        assert_eq!(summary.blake3_compared_files, 1);
        assert_eq!(summary.verified_files, 1);
        Ok(())
    }

    #[test]
    fn strict_compare_syncs_metadata_when_content_matches()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let source = tempdir()?;
        let target = tempdir()?;
        let source_file = source.path().join("a.txt");
        let target_file = target.path().join("a.txt");
        fs::write(&source_file, "same-value")?;
        fs::write(&target_file, "same-value")?;

        let source_timestamp = filetime::FileTime::from_unix_time(1_700_000_100, 0);
        let target_timestamp = filetime::FileTime::from_unix_time(1_700_000_000, 0);
        filetime::set_file_mtime(&source_file, source_timestamp)?;
        filetime::set_file_mtime(&target_file, target_timestamp)?;

        let mut cli = Cli::for_test(source.path(), target.path());
        cli.compare = crate::config::CompareMode::Strict;
        let config = SyncConfig::try_from(cli)?;

        let summary = crate::run_sync(config)?;

        assert_eq!(fs::read_to_string(&target_file)?, "same-value");
        assert_eq!(summary.copied_files, 0);
        assert_eq!(summary.metadata_updates, 1);
        assert_eq!(summary.blake3_compared_files, 1);
        assert_eq!(summary.verified_files, 0);
        assert_eq!(
            fs::metadata(&target_file)?.modified()?,
            fs::metadata(&source_file)?.modified()?
        );
        Ok(())
    }

    #[test]
    fn disabled_metadata_sync_skips_metadata_update()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let source = tempdir()?;
        let target = tempdir()?;
        let source_file = source.path().join("a.txt");
        let target_file = target.path().join("a.txt");
        fs::write(&source_file, "same-value")?;
        fs::write(&target_file, "same-value")?;

        let source_timestamp = filetime::FileTime::from_unix_time(1_700_000_100, 0);
        let target_timestamp = filetime::FileTime::from_unix_time(1_700_000_000, 0);
        filetime::set_file_mtime(&source_file, source_timestamp)?;
        filetime::set_file_mtime(&target_file, target_timestamp)?;
        let target_modified_before = fs::metadata(&target_file)?.modified()?;

        let mut cli = Cli::for_test(source.path(), target.path());
        cli.sync_metadata = false;
        let config = SyncConfig::try_from(cli)?;

        let summary = crate::run_sync(config)?;

        assert_eq!(summary.copied_files, 0);
        assert_eq!(summary.metadata_updates, 0);
        assert_eq!(summary.blake3_compared_files, 1);
        assert_eq!(
            fs::metadata(&target_file)?.modified()?,
            target_modified_before
        );
        Ok(())
    }

    #[test]
    fn strict_shortcut_hashes_when_metadata_matches()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let source = tempdir()?;
        let target = tempdir()?;
        let source_file = source.path().join("a.txt");
        let target_file = target.path().join("a.txt");
        fs::write(&source_file, "new-value")?;
        fs::write(&target_file, "old-value")?;

        let timestamp = filetime::FileTime::from_unix_time(1_700_000_000, 0);
        filetime::set_file_mtime(&source_file, timestamp)?;
        filetime::set_file_mtime(&target_file, timestamp)?;

        let mut cli = Cli::for_test(source.path(), target.path());
        cli.strict = true;
        let config = SyncConfig::try_from(cli)?;

        let summary = crate::run_sync(config)?;

        assert_eq!(fs::read_to_string(target_file)?, "new-value");
        assert_eq!(summary.copied_files, 1);
        assert_eq!(summary.blake3_compared_files, 1);
        Ok(())
    }

    #[test]
    fn fast_compare_trusts_same_metadata() -> std::result::Result<(), Box<dyn std::error::Error>> {
        let source = tempdir()?;
        let target = tempdir()?;
        let source_file = source.path().join("a.txt");
        let target_file = target.path().join("a.txt");
        fs::write(&source_file, "new-value")?;
        fs::write(&target_file, "old-value")?;

        let timestamp = filetime::FileTime::from_unix_time(1_700_000_000, 0);
        filetime::set_file_mtime(&source_file, timestamp)?;
        filetime::set_file_mtime(&target_file, timestamp)?;

        let cli = Cli::for_test(source.path(), target.path());
        let config = SyncConfig::try_from(cli)?;

        let summary = crate::run_sync(config)?;

        assert_eq!(fs::read_to_string(target_file)?, "old-value");
        assert_eq!(summary.copied_files, 0);
        assert_eq!(summary.blake3_compared_files, 0);
        Ok(())
    }

    #[test]
    fn delete_flag_removes_obsolete_target_file()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let source = tempdir()?;
        let target = tempdir()?;
        fs::write(source.path().join("kept.txt"), "keep")?;
        fs::write(target.path().join("stale.txt"), "stale")?;

        let mut cli = Cli::for_test(source.path(), target.path());
        cli.delete = true;
        let config = SyncConfig::try_from(cli)?;

        let summary = crate::run_sync(config)?;

        assert!(!target.path().join("stale.txt").exists());
        assert_eq!(summary.deleted_files, 1);
        Ok(())
    }

    #[test]
    fn sync_creates_missing_target_root_and_nested_directories()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let source = tempdir()?;
        let target_parent = tempdir()?;
        let target = target_parent.path().join("missing-target");
        fs::create_dir(source.path().join("nested"))?;
        fs::write(source.path().join("nested").join("a.txt"), "hello")?;

        let cli = Cli::for_test(source.path(), &target);
        let config = SyncConfig::try_from(cli)?;

        let summary = crate::run_sync(config)?;

        assert_eq!(
            fs::read_to_string(target.join("nested").join("a.txt"))?,
            "hello"
        );
        assert_eq!(summary.created_dirs, 1);
        assert_eq!(summary.copied_files, 1);
        Ok(())
    }

    #[test]
    fn delete_flag_removes_obsolete_nested_directory_tree()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let source = tempdir()?;
        let target = tempdir()?;
        let stale_dir = target.path().join("stale");
        fs::create_dir(&stale_dir)?;
        fs::write(stale_dir.join("old.txt"), "old")?;

        let mut cli = Cli::for_test(source.path(), target.path());
        cli.delete = true;
        let config = SyncConfig::try_from(cli)?;

        let summary = crate::run_sync(config)?;

        assert!(!stale_dir.exists());
        assert_eq!(summary.deleted_files, 1);
        assert_eq!(summary.deleted_dirs, 1);
        Ok(())
    }

    #[test]
    fn delete_disabled_preserves_obsolete_target_file()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let source = tempdir()?;
        let target = tempdir()?;
        let stale_file = target.path().join("stale.txt");
        fs::write(&stale_file, "stale")?;

        let cli = Cli::for_test(source.path(), target.path());
        let config = SyncConfig::try_from(cli)?;

        let summary = crate::run_sync(config)?;

        assert_eq!(fs::read_to_string(stale_file)?, "stale");
        assert_eq!(summary.deleted_files, 0);
        assert_eq!(summary.planned_operations, 0);
        Ok(())
    }

    #[test]
    fn verify_all_counts_all_source_files_after_sync()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let source = tempdir()?;
        let target = tempdir()?;
        fs::write(source.path().join("a.txt"), "alpha")?;
        fs::write(source.path().join("b.txt"), "beta")?;

        let mut cli = Cli::for_test(source.path(), target.path());
        cli.verify = crate::config::VerifyMode::All;
        let config = SyncConfig::try_from(cli)?;

        let summary = crate::run_sync(config)?;

        assert_eq!(summary.copied_files, 2);
        assert_eq!(summary.verified_files, 2);
        Ok(())
    }

    #[test]
    fn path_type_conflict_errors_when_source_file_matches_target_directory()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let source = tempdir()?;
        let target = tempdir()?;
        fs::write(source.path().join("item"), "file")?;
        fs::create_dir(target.path().join("item"))?;

        let cli = Cli::for_test(source.path(), target.path());
        let config = SyncConfig::try_from(cli)?;

        let error = crate::run_sync(config).expect_err("type conflict should fail");

        assert!(error.to_string().contains("item"));
        Ok(())
    }

    #[test]
    fn no_atomic_write_overwrites_changed_file()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let source = tempdir()?;
        let target = tempdir()?;
        fs::write(source.path().join("a.txt"), "new-content")?;
        fs::write(target.path().join("a.txt"), "old")?;

        let mut cli = Cli::for_test(source.path(), target.path());
        cli.atomic_write = false;
        let config = SyncConfig::try_from(cli)?;

        let summary = crate::run_sync(config)?;

        assert_eq!(
            fs::read_to_string(target.path().join("a.txt"))?,
            "new-content"
        );
        assert_eq!(summary.copied_files, 1);
        Ok(())
    }
}