editer
This commit is contained in:
1 parent
ad987111a3
commit
c9e61f38c5
89 files changed
+11775
-3155
No files matched your search
@@ -0,0 +1,168 @@
|
||||
//! 整库 / 目录导出为 zip。
|
||||
//!
|
||||
//! # 与快照备份的区别
|
||||
//!
|
||||
//! `backup.rs` 的 zip 是**给同步服务用的**(固定文件名前缀、上传到远端、轮转),
|
||||
//! 本模块的 zip 是**给用户拿走的**(用户选保存位置、可以只导出某个目录)。
|
||||
//! 两者都打包 `.md` 与 `assets/`,但排除规则不同:用户导出时**包含**点号开头的
|
||||
//! 普通目录(除了 `.editor/`)—— 因为「我库里有 `.foo/` 目录,为什么导出后没了」
|
||||
//! 是个更难解释的问题;而同步必须排除它们(避免把本机私有状态推给别人)。
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use super::library;
|
||||
|
||||
/// 打包范围。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Scope {
|
||||
/// 整个库
|
||||
All,
|
||||
/// 只打包库内某个目录(连同库根的 `assets/`)
|
||||
Dir,
|
||||
}
|
||||
|
||||
/// 按范围打包,返回 `(zip 字节, 文件数)`。
|
||||
pub fn zip_scope(root: &Path, dir_rel: &str) -> Result<(Vec<u8>, u32), String> {
|
||||
let scope = if dir_rel.trim().is_empty() {
|
||||
Scope::All
|
||||
} else {
|
||||
Scope::Dir
|
||||
};
|
||||
// 目录模式下先确认目标目录存在且仍在库内(`safe_join` 拒绝越界)
|
||||
let filter_prefix = if scope == Scope::Dir {
|
||||
let dir = library::safe_join(root, dir_rel)?;
|
||||
if !dir.is_dir() {
|
||||
return Err(format!("目录不存在:{dir_rel}"));
|
||||
}
|
||||
Some(library::rel_string(root, &dir))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let cursor = std::io::Cursor::new(Vec::new());
|
||||
let mut writer = zip::ZipWriter::new(cursor);
|
||||
let options: zip::write::FileOptions<'_, ()> =
|
||||
zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
|
||||
let mut files = 0u32;
|
||||
for entry in walkdir::WalkDir::new(root)
|
||||
.max_depth(library::MAX_DEPTH)
|
||||
.into_iter()
|
||||
.filter_map(Result::ok)
|
||||
{
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
let rel = library::rel_string(root, entry.path());
|
||||
if rel.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// 私有目录(索引 + 同步基线)任何情况下都不导出
|
||||
if rel == ".editor" || rel.starts_with(".editor/") {
|
||||
continue;
|
||||
}
|
||||
if let Some(prefix) = &filter_prefix {
|
||||
// 目录模式:只收该目录下的文件,外加库根 assets/
|
||||
let in_scope = rel == *prefix
|
||||
|| rel.starts_with(&format!("{prefix}/"))
|
||||
|| rel.starts_with(&format!("{}/", library::ASSETS_DIR));
|
||||
if !in_scope {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let bytes = match std::fs::read(entry.path()) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) => {
|
||||
crate::logger::log_warn("editor", &format!("导出跳过 {rel}(读取失败: {e})"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
writer
|
||||
.start_file(rel, options)
|
||||
.map_err(|e| format!("写入 zip 条目失败: {e}"))?;
|
||||
writer
|
||||
.write_all(&bytes)
|
||||
.map_err(|e| format!("写入 zip 内容失败: {e}"))?;
|
||||
files += 1;
|
||||
}
|
||||
|
||||
let cursor = writer.finish().map_err(|e| format!("完成 zip 打包失败: {e}"))?;
|
||||
Ok((cursor.into_inner(), files))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn temp_lib(tag: &str) -> PathBuf {
|
||||
let root = std::env::temp_dir().join(format!("thing-notes-export-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(root.join("assets")).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
fn names(bytes: Vec<u8>) -> Vec<String> {
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
(0..archive.len())
|
||||
.map(|i| archive.by_index(i).unwrap().name().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_export_skips_private_dir_only() {
|
||||
let root = temp_lib("all");
|
||||
std::fs::create_dir_all(root.join(".editor")).unwrap();
|
||||
std::fs::create_dir_all(root.join(".custom")).unwrap();
|
||||
std::fs::write(root.join("a.md"), "A").unwrap();
|
||||
std::fs::write(root.join(".editor/editor.db"), "x").unwrap();
|
||||
std::fs::write(root.join(".custom/keep.md"), "保留").unwrap();
|
||||
std::fs::write(root.join("assets/p.png"), [1u8]).unwrap();
|
||||
|
||||
let (bytes, count) = zip_scope(&root, "").unwrap();
|
||||
assert_eq!(count, 3, "a.md + .custom/keep.md + assets/p.png");
|
||||
let list = names(bytes);
|
||||
assert!(list.contains(&"a.md".to_string()), "{list:?}");
|
||||
assert!(
|
||||
list.contains(&".custom/keep.md".to_string()),
|
||||
"普通点号目录应被导出: {list:?}"
|
||||
);
|
||||
assert!(
|
||||
!list.iter().any(|n| n.starts_with(".editor")),
|
||||
"私有目录不该导出: {list:?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dir_export_limits_scope_but_keeps_assets() {
|
||||
let root = temp_lib("dir");
|
||||
std::fs::create_dir_all(root.join("work")).unwrap();
|
||||
std::fs::create_dir_all(root.join("personal")).unwrap();
|
||||
std::fs::write(root.join("work/a.md"), "A").unwrap();
|
||||
std::fs::write(root.join("personal/b.md"), "B").unwrap();
|
||||
std::fs::write(root.join("assets/p.png"), [1u8]).unwrap();
|
||||
|
||||
let (bytes, count) = zip_scope(&root, "work").unwrap();
|
||||
assert_eq!(count, 2, "work/a.md + assets/p.png");
|
||||
let list = names(bytes);
|
||||
assert!(list.contains(&"work/a.md".to_string()), "{list:?}");
|
||||
assert!(list.contains(&"assets/p.png".to_string()), "{list:?}");
|
||||
assert!(
|
||||
!list.contains(&"personal/b.md".to_string()),
|
||||
"范围外文件不该导出: {list:?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dir_export_rejects_escape_and_missing() {
|
||||
let root = temp_lib("escape");
|
||||
assert!(zip_scope(&root, "../..").is_err(), "越界路径必须被拒");
|
||||
assert!(zip_scope(&root, "不存在").is_err());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user