Final Release of Version 1.0

This commit is contained in:
Breadway 2026-05-13 22:01:42 +08:00
parent d44ece3649
commit 9a471f3158
34 changed files with 3129 additions and 567 deletions

View file

@ -133,3 +133,125 @@ pub fn expand_path(path: &str) -> PathBuf {
}
PathBuf::from(path)
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
fn sample_config() -> SyncConfig {
SyncConfig {
remote: RemoteConfig {
url: "git@github.com:user/repo.git".to_string(),
branch: "main".to_string(),
},
machine: MachineConfig {
name: "host".to_string(),
tags: vec!["mobile".to_string()],
},
packages: PackagesConfig::default(),
delegates: DelegatesConfig::default(),
}
}
#[test]
fn save_and_load_round_trip() {
let tmp = TempDir::new().unwrap();
let cfg = sample_config();
cfg.save(tmp.path()).unwrap();
assert!(tmp.path().join("sync.toml").exists());
let loaded = SyncConfig::load(tmp.path()).unwrap();
assert_eq!(loaded.remote.url, cfg.remote.url);
assert_eq!(loaded.remote.branch, cfg.remote.branch);
assert_eq!(loaded.machine.name, cfg.machine.name);
assert_eq!(loaded.machine.tags, cfg.machine.tags);
}
#[test]
fn load_missing_config_returns_helpful_error() {
let tmp = TempDir::new().unwrap();
let err = SyncConfig::load(tmp.path()).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("sync not initialized") || msg.contains("bread sync init"),
"expected init hint, got: {msg}",
);
}
#[test]
fn load_invalid_toml_returns_parse_error() {
let tmp = TempDir::new().unwrap();
std::fs::write(tmp.path().join("sync.toml"), "this is not [valid toml").unwrap();
let err = SyncConfig::load(tmp.path()).unwrap_err();
let msg = format!("{err:#}");
assert!(msg.to_lowercase().contains("parse"), "got: {msg}");
}
#[test]
fn packages_config_default_includes_all_managers() {
let cfg = PackagesConfig::default();
assert!(cfg.enabled);
assert!(cfg.managers.contains(&"pacman".to_string()));
assert!(cfg.managers.contains(&"pip".to_string()));
assert!(cfg.managers.contains(&"npm".to_string()));
assert!(cfg.managers.contains(&"cargo".to_string()));
}
#[test]
fn remote_branch_defaults_to_main_when_omitted() {
let raw = r#"
[remote]
url = "git@example.com:r.git"
[machine]
name = "host"
"#;
let cfg: SyncConfig = toml::from_str(raw).unwrap();
assert_eq!(cfg.remote.branch, "main");
}
#[test]
fn delegates_default_is_empty() {
let cfg = DelegatesConfig::default();
assert!(cfg.include.is_empty());
assert!(cfg.exclude.is_empty());
}
#[test]
fn local_repo_path_resolves_to_data_dir() {
let path = SyncConfig::local_repo_path();
// Must include the bread sync-repo segment at the end.
let suffix = path.iter().rev().take(2).collect::<Vec<_>>();
assert_eq!(
suffix,
vec![
std::ffi::OsStr::new("sync-repo"),
std::ffi::OsStr::new("bread")
]
);
}
#[test]
fn expand_path_passes_through_absolute_paths() {
assert_eq!(expand_path("/etc/bread"), PathBuf::from("/etc/bread"));
assert_eq!(expand_path("relative/path"), PathBuf::from("relative/path"));
}
#[test]
fn expand_path_expands_tilde_alone_to_home() {
let home = dirs::home_dir().or_else(|| std::env::var("HOME").ok().map(PathBuf::from));
if let Some(home) = home {
assert_eq!(expand_path("~"), home);
}
}
#[test]
fn expand_path_expands_tilde_prefix() {
let home = dirs::home_dir().or_else(|| std::env::var("HOME").ok().map(PathBuf::from));
if let Some(home) = home {
assert_eq!(expand_path("~/.config"), home.join(".config"));
}
}
}

View file

@ -23,7 +23,11 @@ fn sync_dir_inner(src: &Path, dst: &Path, root: &Path, patterns: &[Pattern]) ->
if dst.exists() {
for entry in fs::read_dir(dst)? {
let entry = entry?;
let rel = entry.path().strip_prefix(dst).unwrap_or(&entry.path()).to_path_buf();
let rel = entry
.path()
.strip_prefix(dst)
.unwrap_or(&entry.path())
.to_path_buf();
let src_counterpart = src.join(&rel);
if !src_counterpart.exists() {
let p = entry.path();
@ -107,3 +111,137 @@ pub fn resolve_include_paths(includes: &[String]) -> Vec<(String, PathBuf)> {
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::TempDir;
#[test]
fn sync_dir_copies_nested_tree() {
let src = TempDir::new().unwrap();
let dst = TempDir::new().unwrap();
fs::create_dir_all(src.path().join("a/b/c")).unwrap();
fs::write(src.path().join("a/b/c/leaf.txt"), "hello").unwrap();
fs::write(src.path().join("root.txt"), "root").unwrap();
sync_dir(src.path(), dst.path(), &[]).unwrap();
assert_eq!(
fs::read_to_string(dst.path().join("a/b/c/leaf.txt")).unwrap(),
"hello"
);
assert_eq!(
fs::read_to_string(dst.path().join("root.txt")).unwrap(),
"root"
);
}
#[test]
fn sync_dir_overwrites_existing_files() {
let src = TempDir::new().unwrap();
let dst = TempDir::new().unwrap();
fs::write(src.path().join("f"), "new").unwrap();
fs::write(dst.path().join("f"), "old").unwrap();
sync_dir(src.path(), dst.path(), &[]).unwrap();
assert_eq!(fs::read_to_string(dst.path().join("f")).unwrap(), "new");
}
#[test]
fn sync_dir_removes_files_no_longer_in_src() {
let src = TempDir::new().unwrap();
let dst = TempDir::new().unwrap();
fs::write(dst.path().join("orphan.txt"), "to remove").unwrap();
fs::write(src.path().join("keeper.txt"), "stay").unwrap();
sync_dir(src.path(), dst.path(), &[]).unwrap();
assert!(!dst.path().join("orphan.txt").exists());
assert!(dst.path().join("keeper.txt").exists());
}
#[test]
fn sync_dir_removes_directories_no_longer_in_src() {
let src = TempDir::new().unwrap();
let dst = TempDir::new().unwrap();
fs::create_dir_all(dst.path().join("ghost-dir")).unwrap();
fs::write(dst.path().join("ghost-dir/x"), "").unwrap();
sync_dir(src.path(), dst.path(), &[]).unwrap();
assert!(!dst.path().join("ghost-dir").exists());
}
#[test]
fn sync_dir_exclude_filters_by_basename_pattern() {
let src = TempDir::new().unwrap();
let dst = TempDir::new().unwrap();
fs::write(src.path().join("keep.lua"), "lua").unwrap();
fs::write(src.path().join("trash.cache"), "").unwrap();
sync_dir(src.path(), dst.path(), &["**/*.cache".to_string()]).unwrap();
assert!(dst.path().join("keep.lua").exists());
assert!(!dst.path().join("trash.cache").exists());
}
#[test]
fn sync_dir_exclude_filters_nested_directory_by_name() {
let src = TempDir::new().unwrap();
let dst = TempDir::new().unwrap();
fs::create_dir_all(src.path().join(".git/objects")).unwrap();
fs::write(src.path().join(".git/objects/abc"), "").unwrap();
fs::write(src.path().join("init.lua"), "lua").unwrap();
sync_dir(src.path(), dst.path(), &["**/.git".to_string()]).unwrap();
assert!(dst.path().join("init.lua").exists());
assert!(!dst.path().join(".git").exists());
}
#[test]
fn sync_dir_creates_destination_if_missing() {
let src = TempDir::new().unwrap();
let dst_parent = TempDir::new().unwrap();
let dst = dst_parent.path().join("brand-new");
fs::write(src.path().join("hi"), "hi").unwrap();
sync_dir(src.path(), &dst, &[]).unwrap();
assert!(dst.join("hi").exists());
}
#[test]
fn sync_dir_empty_src_clears_dst() {
let src = TempDir::new().unwrap();
let dst = TempDir::new().unwrap();
fs::write(dst.path().join("a"), "").unwrap();
fs::write(dst.path().join("b"), "").unwrap();
sync_dir(src.path(), dst.path(), &[]).unwrap();
let remaining: Vec<_> = fs::read_dir(dst.path()).unwrap().collect();
assert!(remaining.is_empty());
}
// ─── resolve_include_paths ────────────────────────────────────────────
#[test]
fn resolve_include_paths_uses_basename_as_key() {
let includes = vec!["/etc/foo/bar".to_string(), "/var/lib/quux".to_string()];
let resolved = resolve_include_paths(&includes);
assert_eq!(resolved.len(), 2);
assert_eq!(resolved[0].0, "bar");
assert_eq!(resolved[0].1, PathBuf::from("/etc/foo/bar"));
assert_eq!(resolved[1].0, "quux");
}
#[test]
fn resolve_include_paths_expands_tilde_in_source() {
let home = dirs::home_dir().or_else(|| std::env::var("HOME").ok().map(PathBuf::from));
if let Some(home) = home {
let resolved = resolve_include_paths(&["~/Documents".to_string()]);
assert_eq!(resolved.len(), 1);
assert_eq!(resolved[0].1, home.join("Documents"));
assert_eq!(resolved[0].0, "Documents");
}
}
}

View file

@ -201,9 +201,7 @@ impl SyncRepo {
let mut out = Vec::new();
for entry in statuses.iter() {
let s = entry.status();
let ch = if s.contains(git2::Status::INDEX_NEW)
|| s.contains(git2::Status::WT_NEW)
{
let ch = if s.contains(git2::Status::INDEX_NEW) || s.contains(git2::Status::WT_NEW) {
'A'
} else if s.contains(git2::Status::INDEX_DELETED)
|| s.contains(git2::Status::WT_DELETED)

View file

@ -77,3 +77,91 @@ pub fn hostname() -> String {
.or_else(|_| std::env::var("HOST"))
.unwrap_or_else(|_| "unknown".to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[test]
fn write_creates_machines_dir_if_missing() {
let tmp = TempDir::new().unwrap();
let machines = tmp.path().join("does/not/exist/yet");
let profile = MachineProfile::new("host".to_string(), vec![]);
profile.write(&machines).unwrap();
assert!(machines.join("host.toml").exists());
}
#[test]
fn write_overwrites_existing_profile() {
let tmp = TempDir::new().unwrap();
let p1 = MachineProfile::new("host".to_string(), vec!["a".to_string()]);
p1.write(tmp.path()).unwrap();
let p2 = MachineProfile::new("host".to_string(), vec!["b".to_string(), "c".to_string()]);
p2.write(tmp.path()).unwrap();
let loaded = MachineProfile::read(tmp.path(), "host").unwrap();
assert_eq!(loaded.tags, vec!["b", "c"]);
}
#[test]
fn list_returns_empty_when_dir_missing() {
let tmp = TempDir::new().unwrap();
let missing = tmp.path().join("nope");
assert!(MachineProfile::list(&missing).unwrap().is_empty());
}
#[test]
fn list_returns_sorted_profiles_only_for_toml_files() {
let tmp = TempDir::new().unwrap();
MachineProfile::new("zebra".to_string(), vec![])
.write(tmp.path())
.unwrap();
MachineProfile::new("alpha".to_string(), vec![])
.write(tmp.path())
.unwrap();
MachineProfile::new("middle".to_string(), vec![])
.write(tmp.path())
.unwrap();
// Non-toml file should be ignored.
std::fs::write(tmp.path().join("notes.txt"), "ignored").unwrap();
let list = MachineProfile::list(tmp.path()).unwrap();
let names: Vec<&str> = list.iter().map(|m| m.name.as_str()).collect();
assert_eq!(names, vec!["alpha", "middle", "zebra"]);
}
#[test]
fn list_skips_invalid_toml_files_without_failing() {
let tmp = TempDir::new().unwrap();
MachineProfile::new("valid".to_string(), vec![])
.write(tmp.path())
.unwrap();
std::fs::write(tmp.path().join("garbage.toml"), "not valid [toml").unwrap();
let list = MachineProfile::list(tmp.path()).unwrap();
assert_eq!(list.len(), 1);
assert_eq!(list[0].name, "valid");
}
#[test]
fn read_returns_helpful_error_when_missing() {
let tmp = TempDir::new().unwrap();
let err = MachineProfile::read(tmp.path(), "ghost").unwrap_err();
assert!(err.to_string().contains("failed to read"));
}
#[test]
fn new_assigns_current_hostname_and_timestamp() {
let p = MachineProfile::new("h".to_string(), vec![]);
assert!(!p.hostname.is_empty());
assert!(chrono::DateTime::parse_from_rfc3339(&p.last_sync).is_ok());
}
#[test]
fn hostname_returns_non_empty_string() {
// Whether libc or env fallback fires, the result must be non-empty.
assert!(!hostname().is_empty());
}
}

View file

@ -19,10 +19,7 @@ pub fn snapshot(manager: &str, dest: &Path) -> Result<bool> {
};
let Some(content) = content else {
eprintln!(
"bread: package manager '{}' not found, skipping",
manager
);
eprintln!("bread: package manager '{}' not found, skipping", manager);
return Ok(false);
};
@ -86,18 +83,15 @@ pub fn parse_cargo(content: &str) -> Vec<String> {
content
.lines()
.filter(|l| !l.starts_with(' ') && !l.trim().is_empty())
.map(|l| {
l.split_whitespace()
.next()
.unwrap_or(l)
.to_string()
})
.map(|l| l.split_whitespace().next().unwrap_or(l).to_string())
.collect()
}
fn run_pacman() -> Result<Option<String>> {
match Command::new("pacman").arg("-Qe").output() {
Ok(out) if out.status.success() => Ok(Some(String::from_utf8_lossy(&out.stdout).to_string())),
Ok(out) if out.status.success() => {
Ok(Some(String::from_utf8_lossy(&out.stdout).to_string()))
}
Ok(_) => Ok(None),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
@ -127,7 +121,9 @@ fn run_npm() -> Result<Option<String>> {
.args(["list", "-g", "--depth=0", "--parseable"])
.output()
{
Ok(out) if out.status.success() => Ok(Some(String::from_utf8_lossy(&out.stdout).to_string())),
Ok(out) if out.status.success() => {
Ok(Some(String::from_utf8_lossy(&out.stdout).to_string()))
}
Ok(_) => Ok(None),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
@ -136,9 +132,114 @@ fn run_npm() -> Result<Option<String>> {
fn run_cargo() -> Result<Option<String>> {
match Command::new("cargo").args(["install", "--list"]).output() {
Ok(out) if out.status.success() => Ok(Some(String::from_utf8_lossy(&out.stdout).to_string())),
Ok(out) if out.status.success() => {
Ok(Some(String::from_utf8_lossy(&out.stdout).to_string()))
}
Ok(_) => Ok(None),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
#[cfg(test)]
mod tests {
use super::*;
// ─── parse_pacman ─────────────────────────────────────────────────────
#[test]
fn pacman_parses_each_line_to_first_field() {
let input = "firefox 128.0-1\ncurl 8.7.1-1\nrustup 1.27.1-1\n";
assert_eq!(parse_pacman(input), vec!["firefox", "curl", "rustup"]);
}
#[test]
fn pacman_skips_blank_lines() {
let input = "firefox 1\n\n \ncurl 2\n";
assert_eq!(parse_pacman(input), vec!["firefox", "curl"]);
}
#[test]
fn pacman_handles_empty_input() {
assert!(parse_pacman("").is_empty());
assert!(parse_pacman("\n\n\n").is_empty());
}
#[test]
fn pacman_handles_single_token_lines() {
// A line with no version still yields the package name.
assert_eq!(parse_pacman("firefox\n"), vec!["firefox"]);
}
// ─── parse_pip ────────────────────────────────────────────────────────
#[test]
fn pip_strips_eq_and_ge_specifiers() {
let input = "requests==2.32.3\nnumpy==2.0.1\nblack>=24.0\n";
assert_eq!(parse_pip(input), vec!["requests", "numpy", "black"]);
}
#[test]
fn pip_skips_comments_and_blank_lines() {
let input = "# editable install\n\nflake8==1.0\n# trailing\n";
assert_eq!(parse_pip(input), vec!["flake8"]);
}
#[test]
fn pip_handles_package_without_specifier() {
assert_eq!(parse_pip("requests\nblack\n"), vec!["requests", "black"]);
}
// ─── parse_npm ────────────────────────────────────────────────────────
#[test]
fn npm_extracts_basename_from_paths() {
let input = "/usr/lib/node_modules/npm\n/usr/lib/node_modules/typescript\n/usr/lib/node_modules/yarn\n";
let pkgs = parse_npm(input);
assert!(pkgs.contains(&"npm".to_string()));
assert!(pkgs.contains(&"typescript".to_string()));
assert!(pkgs.contains(&"yarn".to_string()));
}
#[test]
fn npm_skips_root_node_modules_entry() {
let input = "/usr/lib/node_modules\n/usr/lib/node_modules/typescript\n";
assert_eq!(parse_npm(input), vec!["typescript"]);
}
#[test]
fn npm_handles_empty_input() {
assert!(parse_npm("").is_empty());
}
// ─── parse_cargo ──────────────────────────────────────────────────────
#[test]
fn cargo_extracts_crate_names_from_install_list_output() {
let input = "bottom v0.9.6:\n btm\nripgrep v14.0.3:\n rg\nbat v0.24.0:\n bat\n";
assert_eq!(parse_cargo(input), vec!["bottom", "ripgrep", "bat"]);
}
#[test]
fn cargo_skips_binary_lines() {
// Indented lines are binaries inside a crate.
let input = "alpha v1.0.0:\n bin1\n bin2\nbeta v2.0.0:\n bin3\n";
assert_eq!(parse_cargo(input), vec!["alpha", "beta"]);
}
#[test]
fn cargo_handles_empty_input() {
assert!(parse_cargo("").is_empty());
}
// ─── snapshot dispatch ────────────────────────────────────────────────
#[test]
fn snapshot_unknown_manager_returns_false_without_writing() {
let tmp = tempfile::TempDir::new().unwrap();
let dest = tmp.path().join("out.txt");
let wrote = snapshot("definitely-not-a-pkg-mgr", &dest).unwrap();
assert!(!wrote);
assert!(!dest.exists());
}
}