fastsync 0.10.1

A fast, safe one-way directory synchronization tool for local folders and network transfers.
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
use std::path::PathBuf;

use clap::{ValueEnum, builder::PossibleValue};

use crate::cli::Cli;
use crate::error::{FastSyncError, Result};
use crate::filter::PathFilter;
use crate::i18n::{tr_current, tr_value};

/// 文件内容比较策略。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompareMode {
    /// 元数据一致时信任元数据;元数据不一致但大小一致时再使用 BLAKE3 确认内容。
    Fast,
    /// 大小一致时始终使用 BLAKE3 确认内容,即使元数据一致。
    Strict,
}

/// 复制后验证强度。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VerifyMode {
    /// 不做复制后校验。
    None,
    /// 只校验发生复制或覆盖的文件。
    Changed,
    /// 校验源目录中所有普通文件。
    All,
}

impl VerifyMode {
    /// 判断是否需要校验复制或覆盖过的文件。
    pub fn verify_changed_files(self) -> bool {
        match self {
            Self::Changed | Self::All => true,
            Self::None => false,
        }
    }

    /// 判断是否需要在同步后全量校验源目录普通文件。
    pub fn verify_all_files(self) -> bool {
        match self {
            Self::All => true,
            Self::None | Self::Changed => false,
        }
    }
}

/// 元数据保留策略。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PreserveMode {
    /// 按平台能力自动保留。
    Auto,
    /// 强制保留。
    True,
    /// 不保留。
    False,
}

impl PreserveMode {
    /// `auto` 采用“尽力保留”的策略,失败会返回错误而不是静默忽略。
    pub fn enabled(self) -> bool {
        match self {
            Self::Auto | Self::True => true,
            Self::False => false,
        }
    }
}

/// 当前实现支持的哈希算法。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HashAlgorithm {
    /// BLAKE3,默认强校验算法。
    Blake3,
}

/// 日志级别。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogLevel {
    Error,
    Warn,
    Info,
    Debug,
    Trace,
}

impl LogLevel {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Error => "error",
            Self::Warn => "warn",
            Self::Info => "info",
            Self::Debug => "debug",
            Self::Trace => "trace",
        }
    }
}

/// 终端/机器输出模式。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputMode {
    Text,
    Json,
}

/// 完整运行配置。
#[derive(Debug, Clone)]
pub struct SyncConfig {
    pub source: PathBuf,
    pub target: PathBuf,
    pub dry_run: bool,
    pub delete: bool,
    pub follow_symlinks: bool,
    pub compare_mode: CompareMode,
    pub hash_algorithm: HashAlgorithm,
    pub verify_mode: VerifyMode,
    pub sync_metadata: bool,
    pub preserve_times: PreserveMode,
    pub preserve_permissions: PreserveMode,
    pub atomic_write: bool,
    pub threads: usize,
    pub queue_size: usize,
    pub max_errors: usize,
    pub stop_on_error: bool,
    pub output: OutputMode,
    pub log_level: LogLevel,
    pub filter: PathFilter,
}

impl SyncConfig {
    /// 判断是否需要为同名文件生成独立的元数据同步任务。
    pub fn syncs_file_metadata(&self) -> bool {
        self.sync_metadata && (self.preserve_times.enabled() || self.preserve_permissions.enabled())
    }
}

impl TryFrom<Cli> for SyncConfig {
    type Error = FastSyncError;

    /// 将 CLI 参数规范化为核心配置,并补齐自动默认值。
    fn try_from(cli: Cli) -> Result<Self> {
        if !cli.source.is_dir() {
            return Err(FastSyncError::InvalidSource(cli.source));
        }

        let threads = match cli.threads.as_deref() {
            #[allow(non_snake_case)]
            None | Some("auto") => default_threads(),
            Some(raw) => raw.parse::<usize>().map_err(|err| FastSyncError::Io {
                context: tr_value("io.parse_threads", raw),
                source: std::io::Error::new(std::io::ErrorKind::InvalidInput, err),
            })?,
        }
        .max(1);

        let queue_size = cli.queue_size.unwrap_or_else(|| threads * 4).max(1);
        let compare_mode = if cli.strict {
            CompareMode::Strict
        } else {
            cli.compare
        };

        let filter = PathFilter::from_config(cli.filter.as_ref())?;

        Ok(Self {
            source: cli.source,
            target: cli.target,
            dry_run: cli.dry_run,
            delete: cli.delete,
            follow_symlinks: cli.follow_symlinks,
            compare_mode,
            hash_algorithm: cli.hash,
            verify_mode: cli.verify,
            sync_metadata: cli.sync_metadata,
            preserve_times: cli.preserve_times,
            preserve_permissions: cli.preserve_permissions,
            atomic_write: cli.atomic_write,
            threads,
            queue_size,
            max_errors: cli.max_errors,
            stop_on_error: cli.stop_on_error,
            output: cli.output,
            log_level: cli.log_level,
            filter,
        })
    }
}

fn default_threads() -> usize {
    std::thread::available_parallelism()
        .map(|value| value.get())
        .unwrap_or(4)
        .clamp(1, 8)
}

const COMPARE_MODE_VARIANTS: [CompareMode; 2] = [CompareMode::Fast, CompareMode::Strict];
const VERIFY_MODE_VARIANTS: [VerifyMode; 3] =
    [VerifyMode::None, VerifyMode::Changed, VerifyMode::All];
const PRESERVE_MODE_VARIANTS: [PreserveMode; 3] =
    [PreserveMode::Auto, PreserveMode::True, PreserveMode::False];
const HASH_ALGORITHM_VARIANTS: [HashAlgorithm; 1] = [HashAlgorithm::Blake3];
const LOG_LEVEL_VARIANTS: [LogLevel; 5] = [
    LogLevel::Error,
    LogLevel::Warn,
    LogLevel::Info,
    LogLevel::Debug,
    LogLevel::Trace,
];
const OUTPUT_MODE_VARIANTS: [OutputMode; 2] = [OutputMode::Text, OutputMode::Json];

impl ValueEnum for CompareMode {
    fn value_variants<'a>() -> &'a [Self] {
        &COMPARE_MODE_VARIANTS
    }

    fn to_possible_value(&self) -> Option<PossibleValue> {
        match self {
            Self::Fast => Some(PossibleValue::new("fast").help(tr_current("value.compare.fast"))),
            Self::Strict => {
                Some(PossibleValue::new("strict").help(tr_current("value.compare.strict")))
            }
        }
    }
}

impl ValueEnum for VerifyMode {
    fn value_variants<'a>() -> &'a [Self] {
        &VERIFY_MODE_VARIANTS
    }

    fn to_possible_value(&self) -> Option<PossibleValue> {
        match self {
            Self::None => Some(PossibleValue::new("none").help(tr_current("value.verify.none"))),
            Self::Changed => {
                Some(PossibleValue::new("changed").help(tr_current("value.verify.changed")))
            }
            Self::All => Some(PossibleValue::new("all").help(tr_current("value.verify.all"))),
        }
    }
}

impl ValueEnum for PreserveMode {
    fn value_variants<'a>() -> &'a [Self] {
        &PRESERVE_MODE_VARIANTS
    }

    fn to_possible_value(&self) -> Option<PossibleValue> {
        match self {
            Self::Auto => Some(PossibleValue::new("auto").help(tr_current("value.preserve.auto"))),
            Self::True => Some(PossibleValue::new("true").help(tr_current("value.preserve.true"))),
            Self::False => {
                Some(PossibleValue::new("false").help(tr_current("value.preserve.false")))
            }
        }
    }
}

impl ValueEnum for HashAlgorithm {
    fn value_variants<'a>() -> &'a [Self] {
        &HASH_ALGORITHM_VARIANTS
    }

    fn to_possible_value(&self) -> Option<PossibleValue> {
        match self {
            Self::Blake3 => {
                Some(PossibleValue::new("blake3").help(tr_current("value.hash.blake3")))
            }
        }
    }
}

impl ValueEnum for LogLevel {
    fn value_variants<'a>() -> &'a [Self] {
        &LOG_LEVEL_VARIANTS
    }

    fn to_possible_value(&self) -> Option<PossibleValue> {
        match self {
            Self::Error => Some(PossibleValue::new("error")),
            Self::Warn => Some(PossibleValue::new("warn")),
            Self::Info => Some(PossibleValue::new("info")),
            Self::Debug => Some(PossibleValue::new("debug")),
            Self::Trace => Some(PossibleValue::new("trace")),
        }
    }
}

impl ValueEnum for OutputMode {
    fn value_variants<'a>() -> &'a [Self] {
        &OUTPUT_MODE_VARIANTS
    }

    fn to_possible_value(&self) -> Option<PossibleValue> {
        match self {
            Self::Text => Some(PossibleValue::new("text")),
            Self::Json => Some(PossibleValue::new("json")),
        }
    }
}

#[cfg(test)]
mod tests {
    use tempfile::tempdir;

    use crate::cli::Cli;
    use crate::error::FastSyncError;

    use super::*;

    #[test]
    fn cli_config_rejects_missing_source() -> std::result::Result<(), Box<dyn std::error::Error>> {
        let root = tempdir()?;
        let missing = root.path().join("missing");
        let target = root.path().join("target");
        let cli = Cli::parse_from([
            "fastsync",
            missing.to_str().expect("temp path should be UTF-8"),
            target.to_str().expect("temp path should be UTF-8"),
        ]);

        let error = SyncConfig::try_from(cli).expect_err("missing source must be rejected");

        assert!(matches!(error, FastSyncError::InvalidSource(path) if path == missing));
        Ok(())
    }

    #[test]
    fn cli_config_normalizes_runtime_options() -> std::result::Result<(), Box<dyn std::error::Error>>
    {
        let source = tempdir()?;
        let target = tempdir()?;
        let cli = Cli::parse_from([
            "fastsync",
            source.path().to_str().expect("temp path should be UTF-8"),
            target.path().to_str().expect("temp path should be UTF-8"),
            "--strict",
            "--verify",
            "all",
            "--no-sync-metadata",
            "--preserve-times",
            "false",
            "--preserve-permissions",
            "true",
            "--no-atomic-write",
            "--threads",
            "0",
            "--queue-size",
            "0",
            "--max-errors",
            "3",
            "--stop-on-error",
            "--output",
            "json",
            "--log-level",
            "debug",
        ]);

        let config = SyncConfig::try_from(cli)?;

        assert_eq!(config.compare_mode, CompareMode::Strict);
        assert_eq!(config.verify_mode, VerifyMode::All);
        assert!(!config.sync_metadata);
        assert_eq!(config.preserve_times, PreserveMode::False);
        assert_eq!(config.preserve_permissions, PreserveMode::True);
        assert!(!config.atomic_write);
        assert_eq!(config.threads, 1);
        assert_eq!(config.queue_size, 1);
        assert_eq!(config.max_errors, 3);
        assert!(config.stop_on_error);
        assert_eq!(config.output, OutputMode::Json);
        assert_eq!(config.log_level, LogLevel::Debug);
        Ok(())
    }

    #[test]
    fn syncs_file_metadata_requires_enabled_metadata_and_preserve_mode() {
        let mut config = SyncConfig {
            source: "source".into(),
            target: "target".into(),
            dry_run: false,
            delete: false,
            follow_symlinks: false,
            compare_mode: CompareMode::Fast,
            hash_algorithm: HashAlgorithm::Blake3,
            verify_mode: VerifyMode::Changed,
            sync_metadata: true,
            preserve_times: PreserveMode::False,
            preserve_permissions: PreserveMode::False,
            atomic_write: true,
            threads: 1,
            queue_size: 1,
            max_errors: 1,
            stop_on_error: false,
            output: OutputMode::Text,
            log_level: LogLevel::Info,
            filter: PathFilter::disabled(),
        };

        assert!(!config.syncs_file_metadata());
        config.preserve_times = PreserveMode::Auto;
        assert!(config.syncs_file_metadata());
        config.sync_metadata = false;
        assert!(!config.syncs_file_metadata());
    }
}