l-s 0.5.2

Summary any file‘s meta.
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
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use anyhow::Result;
#[cfg(not(unix))]
use anyhow::{anyhow, Context};
use serde::{Deserialize, Serialize};

#[cfg(unix)]
use super::file::calc_xxh128_from_file_with_callback;
#[cfg(not(unix))]
use super::file::calc_xxh128_with_callback;
use super::file::FileMeta;
use super::progress::ProgressTracker;
use crate::constants::META_VERSION;
#[cfg(not(unix))]
use crate::utils::{basename, should_skip_dir, should_skip_file};

#[cfg(not(unix))]
use std::fs;
#[cfg(not(unix))]
use std::fs::File;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DirSnapshot {
    pub dir_name: String,
    pub dirs: Vec<DirSnapshot>,
    pub files: Vec<FileMeta>,
    // 如果 Option::is_none(即该字段为 None),序列化为 JSON 时会跳过(不输出)该字段
    #[serde(skip_serializing_if = "Option::is_none")]
    pub v: Option<String>,
}

impl DirSnapshot {
    pub fn build_root(path: &Path) -> Result<Self> {
        let total_files = count_files(path)?;
        let tracker = ProgressTracker::new(total_files, "构建中...");

        let mut node = Self::build_node(path, &tracker)?;
        node.v = Some(META_VERSION.to_string());

        tracker.finish("构建完成");
        Ok(node)
    }

    pub fn from_reader<R: std::io::Read>(reader: R) -> Result<Self> {
        Ok(serde_json::from_reader(reader)?)
    }

    #[cfg(unix)]
    fn build_node(path: &Path, tracker: &ProgressTracker) -> Result<Self> {
        unix_walk::build_node(path, tracker)
    }

    #[cfg(not(unix))]
    fn build_node(path: &Path, tracker: &ProgressTracker) -> Result<Self> {
        let dir_name = path
            .file_name()
            .map(basename)
            .unwrap_or_else(|| path.to_string_lossy().to_string());

        let mut dirs = Vec::new();
        let mut files = Vec::new();

        let mut entries = fs::read_dir(path)
            .with_context(|| format!("无法遍历目录: {}", path.display()))?
            .collect::<Result<Vec<_>, _>>()
            .with_context(|| format!("读取目录失败: {}", path.display()))?;

        entries.sort_unstable_by_key(|e| e.file_name());

        for entry in entries {
            let file_name = entry.file_name();
            let name = file_name.to_string_lossy().to_string();
            let full_path = entry.path();
            let file_type = entry
                .file_type()
                .with_context(|| format!("无法读取类型: {}", full_path.display()))?;

            if file_type.is_symlink() {
                continue;
            }

            if file_type.is_dir() {
                if should_skip_dir(&name) {
                    continue;
                }
                let sub_meta = full_path.join("meta.json");
                if sub_meta.exists() {
                    dirs.push(Self::verify_and_load(&full_path, tracker)?);
                } else {
                    dirs.push(Self::build_node(&full_path, tracker)?);
                }
                continue;
            }

            if should_skip_file(&name) {
                continue;
            }

            // 获取文件大小并开始跟踪
            let file_size = entry.metadata().map(|m| m.len()).unwrap_or(0);
            tracker.start_file(file_size, &name);

            let on_bytes = tracker.bytes_callback();
            let on_iop = tracker.iop_callback();
            let meta = FileMeta::from_path_with_callback(&full_path, on_bytes, on_iop)?;
            files.push(meta);
            tracker.finish_file();
        }

        Ok(Self {
            dir_name,
            dirs,
            files,
            v: None,
        })
    }

    pub fn collect_file_map(&self, root: &Path) -> BTreeMap<PathBuf, FileMeta> {
        let mut map = BTreeMap::new();
        self.collect_into(root.to_path_buf(), &mut map);
        map
    }

    fn collect_into(&self, current: PathBuf, map: &mut BTreeMap<PathBuf, FileMeta>) {
        for file in &self.files {
            map.insert(current.join(&file.basename), file.clone());
        }

        for dir in &self.dirs {
            let next = current.join(&dir.dir_name);
            dir.collect_into(next, map);
        }
    }

    /// 加载子目录的 meta.json 并通过 xxh128 快速校验。
    /// 校验通过则返回已有的 DirSnapshot,否则返回 Err 终止流程。
    #[cfg(not(unix))]
    fn verify_and_load(path: &Path, tracker: &ProgressTracker) -> Result<Self> {
        let meta_path = path.join("meta.json");
        let meta_file =
            File::open(&meta_path).with_context(|| format!("无法读取: {}", meta_path.display()))?;
        let mut snapshot: Self = serde_json::from_reader(meta_file)
            .with_context(|| format!("无法解析: {}", meta_path.display()))?;

        let mut stored = snapshot.collect_file_map(path);
        let mut current = BTreeMap::new();
        walk_dir_with_progress(path, &mut current, tracker)?;

        for (file_path, hash) in current {
            if let Some(meta) = stored.remove(&file_path) {
                if hash != meta.xxh128 {
                    return Err(anyhow!(
                        "校验失败: {}\n  期望: {}\n  当前: {}",
                        file_path.display(),
                        meta.xxh128,
                        hash
                    ));
                }
            } else {
                return Err(anyhow!("文件新增: {}", file_path.display()));
            }
        }

        if let Some((missing_path, _)) = stored.into_iter().next() {
            return Err(anyhow!("文件缺失: {}", missing_path.display()));
        }

        // 须通过 MultiProgress::suspend:先清屏进度区再打印,否则 stderr 上的独立 eprintln
        // 会被下一次 tick 的光标移动覆盖,看起来像「只有进度条在往上刷」。
        let msg = format!("✓ 校验通过: {}", path.display());
        if let Some(multi) = tracker.multi() {
            multi.suspend(|| {
                eprintln!("{msg}");
            });
        } else {
            eprintln!("{msg}");
        }
        snapshot.dir_name = path
            .file_name()
            .map(basename)
            .unwrap_or_else(|| path.to_string_lossy().to_string());
        snapshot.v = None;
        Ok(snapshot)
    }
}

pub fn scan_dir_xxh128(path: &Path) -> Result<BTreeMap<PathBuf, String>> {
    let total_files = count_files(path)?;
    let tracker = ProgressTracker::new(total_files, "扫描中...");

    let mut map = BTreeMap::new();
    walk_dir_with_progress(path, &mut map, &tracker)?;

    tracker.finish("扫描完成");
    Ok(map)
}

fn count_files(path: &Path) -> Result<u64> {
    #[cfg(unix)]
    {
        unix_walk::count_files(path)
    }

    #[cfg(not(unix))]
    {
        let mut count = 0u64;
        count_files_recursive(path, &mut count)?;
        Ok(count)
    }
}

#[cfg(not(unix))]
fn count_files_recursive(path: &Path, count: &mut u64) -> Result<()> {
    let entries = fs::read_dir(path)
        .with_context(|| format!("无法遍历目录: {}", path.display()))?
        .collect::<Result<Vec<_>, _>>()
        .with_context(|| format!("读取目录失败: {}", path.display()))?;

    for entry in entries {
        let file_name = entry.file_name();
        let name = file_name.to_string_lossy().to_string();
        let full_path = entry.path();
        let file_type = entry
            .file_type()
            .with_context(|| format!("无法读取类型: {}", full_path.display()))?;

        if file_type.is_symlink() {
            continue;
        }

        if file_type.is_dir() {
            if should_skip_dir(&name) {
                continue;
            }
            count_files_recursive(&full_path, count)?;
        } else if !should_skip_file(&name) {
            *count += 1;
        }
    }

    Ok(())
}

fn walk_dir_with_progress(
    path: &Path,
    map: &mut BTreeMap<PathBuf, String>,
    tracker: &ProgressTracker,
) -> Result<()> {
    #[cfg(unix)]
    {
        unix_walk::walk_dir_with_progress(path, map, tracker)
    }

    #[cfg(not(unix))]
    {
        let mut entries = fs::read_dir(path)
            .with_context(|| format!("无法遍历目录: {}", path.display()))?
            .collect::<Result<Vec<_>, _>>()
            .with_context(|| format!("读取目录失败: {}", path.display()))?;
        entries.sort_unstable_by_key(|e| e.file_name());

        for entry in entries {
            let file_name = entry.file_name();
            let name = file_name.to_string_lossy().to_string();
            let full_path = entry.path();
            let file_type = entry
                .file_type()
                .with_context(|| format!("无法读取类型: {}", full_path.display()))?;

            if file_type.is_symlink() {
                continue;
            }

            if file_type.is_dir() {
                if should_skip_dir(&name) {
                    continue;
                }
                walk_dir_with_progress(&full_path, map, tracker)?;
                continue;
            }

            if should_skip_file(&name) {
                continue;
            }

            // 获取文件大小并开始跟踪
            let file_size = entry.metadata().map(|m| m.len()).unwrap_or(0);
            tracker.start_file(file_size, &name);

            let on_bytes = tracker.bytes_callback();
            let on_iop = tracker.iop_callback();
            let hash = calc_xxh128_with_callback(&full_path, on_bytes, on_iop)?;
            map.insert(full_path, hash);
            tracker.finish_file();
        }

        Ok(())
    }
}

#[cfg(unix)]
mod unix_walk {
    use std::collections::BTreeMap;
    use std::ffi::{CStr, CString, OsStr, OsString};
    use std::fs::File;
    use std::io;
    use std::mem::MaybeUninit;
    use std::os::fd::{AsRawFd, FromRawFd, RawFd};
    use std::os::unix::ffi::{OsStrExt, OsStringExt};
    use std::os::unix::fs::MetadataExt;
    use std::path::{Path, PathBuf};

    use anyhow::{anyhow, Context, Result};

    use super::{calc_xxh128_from_file_with_callback, DirSnapshot, FileMeta, ProgressTracker};
    use crate::utils::{basename, should_skip_dir, should_skip_file};

    struct DirHandle {
        file: File,
    }

    struct DirEntryInfo {
        name: OsString,
        stat: libc::stat,
    }

    enum EntryKind {
        Directory,
        RegularFile,
        Symlink,
        Other,
    }

    impl DirHandle {
        fn open_path(path: &Path) -> Result<Self> {
            let c_path = cstring_from_path(path)?;
            let fd = unsafe { libc::open(c_path.as_ptr(), dir_open_flags()) };
            if fd == -1 {
                return Err(io::Error::last_os_error())
                    .with_context(|| format!("无法打开目录: {}", path.display()));
            }

            Ok(Self {
                file: unsafe { File::from_raw_fd(fd) },
            })
        }

        fn raw_fd(&self) -> RawFd {
            self.file.as_raw_fd()
        }

        fn entries(&self, path: &Path) -> Result<Vec<DirEntryInfo>> {
            let dup_fd = unsafe { libc::dup(self.raw_fd()) };
            if dup_fd == -1 {
                return Err(io::Error::last_os_error())
                    .with_context(|| format!("无法遍历目录: {}", path.display()));
            }

            let dir = unsafe { libc::fdopendir(dup_fd) };
            if dir.is_null() {
                let err = io::Error::last_os_error();
                unsafe {
                    libc::close(dup_fd);
                }
                return Err(err).with_context(|| format!("无法遍历目录: {}", path.display()));
            }

            let _stream = DirStream(dir);
            let mut entries = Vec::new();
            loop {
                let entry = unsafe { libc::readdir(dir) };
                if entry.is_null() {
                    break;
                }

                let name_bytes = unsafe { CStr::from_ptr((*entry).d_name.as_ptr()) }.to_bytes();
                if name_bytes == b"." || name_bytes == b".." {
                    continue;
                }

                let name = OsString::from_vec(name_bytes.to_vec());
                let full_path = path.join(&name);
                if let Some(stat) = self.stat_child(&name, &full_path)? {
                    entries.push(DirEntryInfo { name, stat });
                }
            }

            entries.sort_unstable_by(|left, right| left.name.cmp(&right.name));
            Ok(entries)
        }

        fn stat_child(&self, name: &OsStr, path: &Path) -> Result<Option<libc::stat>> {
            let c_name = cstring_from_os_str(name, path)?;
            let mut stat = MaybeUninit::<libc::stat>::uninit();
            let code = unsafe {
                libc::fstatat(
                    self.raw_fd(),
                    c_name.as_ptr(),
                    stat.as_mut_ptr(),
                    libc::AT_SYMLINK_NOFOLLOW,
                )
            };

            if code == -1 {
                let err = io::Error::last_os_error();
                if err.kind() == io::ErrorKind::NotFound {
                    return Ok(None);
                }
                return Err(err).with_context(|| format!("无法读取类型: {}", path.display()));
            }

            Ok(Some(unsafe { stat.assume_init() }))
        }

        fn has_regular_child(&self, name: &OsStr, path: &Path) -> Result<bool> {
            Ok(matches!(
                self.stat_child(name, path)?
                    .map(|stat| kind_from_mode(stat.st_mode)),
                Some(EntryKind::RegularFile)
            ))
        }

        fn open_child_dir(&self, entry: &DirEntryInfo, path: &Path) -> Result<Self> {
            let c_name = cstring_from_os_str(&entry.name, path)?;
            let fd = unsafe { libc::openat(self.raw_fd(), c_name.as_ptr(), dir_open_flags()) };
            if fd == -1 {
                return Err(io::Error::last_os_error())
                    .with_context(|| format!("无法打开目录: {}", path.display()));
            }

            let file = unsafe { File::from_raw_fd(fd) };
            let info = file
                .metadata()
                .with_context(|| format!("无法读取目录信息: {}", path.display()))?;
            if !stat_matches(&info, &entry.stat) {
                return Err(anyhow!("扫描期间目录被替换: {}", path.display()));
            }

            Ok(Self { file })
        }

        fn open_child_file(&self, entry: &DirEntryInfo, path: &Path) -> Result<File> {
            let c_name = cstring_from_os_str(&entry.name, path)?;
            let fd = unsafe { libc::openat(self.raw_fd(), c_name.as_ptr(), file_open_flags()) };
            if fd == -1 {
                return Err(io::Error::last_os_error())
                    .with_context(|| format!("无法打开文件: {}", path.display()));
            }

            let file = unsafe { File::from_raw_fd(fd) };
            let info = file
                .metadata()
                .with_context(|| format!("无法读取文件信息: {}", path.display()))?;
            if !info.is_file() {
                return Err(anyhow!("{} 打开后不是普通文件", path.display()));
            }
            if !stat_matches(&info, &entry.stat) {
                return Err(anyhow!("扫描期间文件被替换: {}", path.display()));
            }

            Ok(file)
        }
    }

    struct DirStream(*mut libc::DIR);

    impl Drop for DirStream {
        fn drop(&mut self) {
            unsafe {
                libc::closedir(self.0);
            }
        }
    }

    pub(super) fn build_node(path: &Path, tracker: &ProgressTracker) -> Result<DirSnapshot> {
        let dir = DirHandle::open_path(path)?;
        build_node_at(path, &dir, tracker)
    }

    pub(super) fn count_files(path: &Path) -> Result<u64> {
        let dir = DirHandle::open_path(path)?;
        let mut count = 0u64;
        count_files_at(path, &dir, &mut count)?;
        Ok(count)
    }

    pub(super) fn walk_dir_with_progress(
        path: &Path,
        map: &mut BTreeMap<PathBuf, String>,
        tracker: &ProgressTracker,
    ) -> Result<()> {
        let dir = DirHandle::open_path(path)?;
        walk_dir_with_progress_at(path, &dir, map, tracker)
    }

    fn build_node_at(
        path: &Path,
        dir: &DirHandle,
        tracker: &ProgressTracker,
    ) -> Result<DirSnapshot> {
        let dir_name = path
            .file_name()
            .map(basename)
            .unwrap_or_else(|| path.to_string_lossy().to_string());

        let mut dirs = Vec::new();
        let mut files = Vec::new();

        for entry in dir.entries(path)? {
            let name = entry.name.to_string_lossy().to_string();
            let full_path = path.join(&entry.name);

            match kind_from_mode(entry.stat.st_mode) {
                EntryKind::Symlink => continue,
                EntryKind::Directory => {
                    if should_skip_dir(&name) {
                        continue;
                    }

                    let child = dir.open_child_dir(&entry, &full_path)?;
                    let child_meta_path = full_path.join("meta.json");
                    if child.has_regular_child(OsStr::new("meta.json"), &child_meta_path)? {
                        dirs.push(verify_and_load_at(&full_path, &child, tracker)?);
                    } else {
                        dirs.push(build_node_at(&full_path, &child, tracker)?);
                    }
                }
                EntryKind::RegularFile => {
                    if should_skip_file(&name) {
                        continue;
                    }

                    let file_size = stat_size(&entry.stat);
                    tracker.start_file(file_size, &name);

                    let file = dir.open_child_file(&entry, &full_path)?;
                    let on_bytes = tracker.bytes_callback();
                    let on_iop = tracker.iop_callback();
                    let meta =
                        FileMeta::from_open_file_with_callback(&full_path, file, on_bytes, on_iop)?;
                    files.push(meta);
                    tracker.finish_file();
                }
                EntryKind::Other => {
                    if !should_skip_file(&name) {
                        return Err(anyhow!(
                            "不支持的特殊文件: {} (mode {:o})",
                            full_path.display(),
                            entry.stat.st_mode
                        ));
                    }
                }
            }
        }

        Ok(DirSnapshot {
            dir_name,
            dirs,
            files,
            v: None,
        })
    }

    fn verify_and_load_at(
        path: &Path,
        dir: &DirHandle,
        tracker: &ProgressTracker,
    ) -> Result<DirSnapshot> {
        let meta_name = OsStr::new("meta.json");
        let meta_path = path.join(meta_name);
        let Some(meta_stat) = dir.stat_child(meta_name, &meta_path)? else {
            return build_node_at(path, dir, tracker);
        };
        let meta_entry = DirEntryInfo {
            name: meta_name.to_os_string(),
            stat: meta_stat,
        };
        let meta_file = dir.open_child_file(&meta_entry, &meta_path)?;
        let mut snapshot: DirSnapshot = serde_json::from_reader(meta_file)
            .with_context(|| format!("无法解析: {}", meta_path.display()))?;

        let mut stored = snapshot.collect_file_map(path);
        let mut current = BTreeMap::new();
        walk_dir_with_progress_at(path, dir, &mut current, tracker)?;

        for (file_path, hash) in current {
            if let Some(meta) = stored.remove(&file_path) {
                if hash != meta.xxh128 {
                    return Err(anyhow!(
                        "校验失败: {}\n  期望: {}\n  当前: {}",
                        file_path.display(),
                        meta.xxh128,
                        hash
                    ));
                }
            } else {
                return Err(anyhow!("文件新增: {}", file_path.display()));
            }
        }

        if let Some((missing_path, _)) = stored.into_iter().next() {
            return Err(anyhow!("文件缺失: {}", missing_path.display()));
        }

        let msg = format!("✓ 校验通过: {}", path.display());
        if let Some(multi) = tracker.multi() {
            multi.suspend(|| {
                eprintln!("{msg}");
            });
        } else {
            eprintln!("{msg}");
        }
        snapshot.dir_name = path
            .file_name()
            .map(basename)
            .unwrap_or_else(|| path.to_string_lossy().to_string());
        snapshot.v = None;
        Ok(snapshot)
    }

    fn count_files_at(path: &Path, dir: &DirHandle, count: &mut u64) -> Result<()> {
        for entry in dir.entries(path)? {
            let name = entry.name.to_string_lossy().to_string();
            let full_path = path.join(&entry.name);

            match kind_from_mode(entry.stat.st_mode) {
                EntryKind::Symlink => continue,
                EntryKind::Directory => {
                    if should_skip_dir(&name) {
                        continue;
                    }

                    let child = dir.open_child_dir(&entry, &full_path)?;
                    count_files_at(&full_path, &child, count)?;
                }
                EntryKind::RegularFile => {
                    if !should_skip_file(&name) {
                        *count += 1;
                    }
                }
                EntryKind::Other => {
                    if !should_skip_file(&name) {
                        return Err(anyhow!(
                            "不支持的特殊文件: {} (mode {:o})",
                            full_path.display(),
                            entry.stat.st_mode
                        ));
                    }
                }
            }
        }

        Ok(())
    }

    fn walk_dir_with_progress_at(
        path: &Path,
        dir: &DirHandle,
        map: &mut BTreeMap<PathBuf, String>,
        tracker: &ProgressTracker,
    ) -> Result<()> {
        for entry in dir.entries(path)? {
            let name = entry.name.to_string_lossy().to_string();
            let full_path = path.join(&entry.name);

            match kind_from_mode(entry.stat.st_mode) {
                EntryKind::Symlink => continue,
                EntryKind::Directory => {
                    if should_skip_dir(&name) {
                        continue;
                    }

                    let child = dir.open_child_dir(&entry, &full_path)?;
                    walk_dir_with_progress_at(&full_path, &child, map, tracker)?;
                }
                EntryKind::RegularFile => {
                    if should_skip_file(&name) {
                        continue;
                    }

                    let file_size = stat_size(&entry.stat);
                    tracker.start_file(file_size, &name);

                    let file = dir.open_child_file(&entry, &full_path)?;
                    let on_bytes = tracker.bytes_callback();
                    let on_iop = tracker.iop_callback();
                    let hash =
                        calc_xxh128_from_file_with_callback(&full_path, file, on_bytes, on_iop)?;
                    map.insert(full_path, hash);
                    tracker.finish_file();
                }
                EntryKind::Other => {
                    if !should_skip_file(&name) {
                        return Err(anyhow!(
                            "不支持的特殊文件: {} (mode {:o})",
                            full_path.display(),
                            entry.stat.st_mode
                        ));
                    }
                }
            }
        }

        Ok(())
    }

    fn kind_from_mode(mode: libc::mode_t) -> EntryKind {
        match mode & libc::S_IFMT as libc::mode_t {
            value if value == libc::S_IFDIR as libc::mode_t => EntryKind::Directory,
            value if value == libc::S_IFREG as libc::mode_t => EntryKind::RegularFile,
            value if value == libc::S_IFLNK as libc::mode_t => EntryKind::Symlink,
            _ => EntryKind::Other,
        }
    }

    fn stat_size(stat: &libc::stat) -> u64 {
        if stat.st_size >= 0 {
            stat.st_size as u64
        } else {
            0
        }
    }

    fn stat_matches(info: &std::fs::Metadata, stat: &libc::stat) -> bool {
        info.dev() == stat.st_dev as u64 && info.ino() == stat.st_ino
    }

    fn dir_open_flags() -> libc::c_int {
        libc::O_RDONLY | libc::O_CLOEXEC | libc::O_DIRECTORY | libc::O_NOFOLLOW
    }

    fn file_open_flags() -> libc::c_int {
        libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW
    }

    fn cstring_from_path(path: &Path) -> Result<CString> {
        CString::new(path.as_os_str().as_bytes())
            .with_context(|| format!("路径包含 NUL 字节: {}", path.display()))
    }

    fn cstring_from_os_str(value: &OsStr, path: &Path) -> Result<CString> {
        CString::new(value.as_bytes())
            .with_context(|| format!("路径包含 NUL 字节: {}", path.display()))
    }
}