fetchium_core/collab/
sync.rs1use crate::collab::workspace::SyncMethod;
4use crate::error::FetchiumError;
5use std::path::Path;
6
7pub fn sync_workspace(
12 workspace_path: &Path,
13 method: &SyncMethod,
14) -> Result<SyncReport, FetchiumError> {
15 match method {
16 SyncMethod::Local { shared_dir } => sync_local(workspace_path, shared_dir),
17 SyncMethod::Git { remote_url } => sync_git(workspace_path, remote_url),
18 }
19}
20
21#[derive(Debug)]
22pub struct SyncReport {
23 pub method: String,
24 pub files_synced: usize,
25 pub message: String,
26}
27
28fn sync_local(src: &Path, dst: &Path) -> Result<SyncReport, FetchiumError> {
29 std::fs::create_dir_all(dst)?;
30 let count = copy_changed(src, dst)?;
31 Ok(SyncReport {
32 method: "local".into(),
33 files_synced: count,
34 message: format!("Synced {count} file(s) to {:?}", dst),
35 })
36}
37
38fn sync_git(workspace_path: &Path, remote_url: &str) -> Result<SyncReport, FetchiumError> {
39 let git_dir = workspace_path.join(".git");
40 if !git_dir.exists() {
41 run_git(workspace_path, &["init"])?;
42 run_git(workspace_path, &["remote", "add", "origin", remote_url])?;
43 }
44 run_git(workspace_path, &["add", "-A"])?;
45 let timestamp = chrono::Utc::now().format("%Y-%m-%d %H:%M:%S").to_string();
46 run_git(
47 workspace_path,
48 &[
49 "commit",
50 "-m",
51 &format!("fetchium workspace sync {timestamp}"),
52 ],
53 )?;
54 run_git(workspace_path, &["push", "-u", "origin", "HEAD"])?;
55 Ok(SyncReport {
56 method: "git".into(),
57 files_synced: 0,
58 message: format!("Pushed to {remote_url}"),
59 })
60}
61
62fn run_git(dir: &Path, args: &[&str]) -> Result<(), FetchiumError> {
63 let status = std::process::Command::new("git")
64 .args(args)
65 .current_dir(dir)
66 .status()?;
67 if !status.success() {
68 return Err(FetchiumError::Config(format!(
69 "git {} failed",
70 args.join(" ")
71 )));
72 }
73 Ok(())
74}
75
76fn copy_changed(src: &Path, dst: &Path) -> Result<usize, FetchiumError> {
77 let mut count = 0;
78 for entry in std::fs::read_dir(src)? {
79 let entry = entry?;
80 let src_path = entry.path();
81 let dst_path = dst.join(entry.file_name());
82 if src_path.is_dir() {
83 if entry.file_name() == ".git" {
84 continue;
85 }
86 count += copy_changed(&src_path, &dst_path)?;
87 } else {
88 let should_copy = if dst_path.exists() {
89 let src_meta = std::fs::metadata(&src_path)?;
90 let dst_meta = std::fs::metadata(&dst_path)?;
91 src_meta.len() != dst_meta.len()
92 } else {
93 true
94 };
95 if should_copy {
96 if let Some(parent) = dst_path.parent() {
97 std::fs::create_dir_all(parent)?;
98 }
99 std::fs::copy(&src_path, &dst_path)?;
100 count += 1;
101 }
102 }
103 }
104 Ok(count)
105}