Skip to main content

qtcloud_devops_cli/code/
sync.rs

1use std::path::PathBuf;
2
3use crate::git::GitSubmoduleEditor;
4
5pub fn sync(root: PathBuf, name: &str) -> Result<(), String> {
6    let editor = GitSubmoduleEditor::new(root);
7    editor.sync_to_parent(name).map_err(|e| format!("同步失败: {}", e))
8}
9
10pub fn sync_all(root: PathBuf) -> Result<(), String> {
11    let editor = GitSubmoduleEditor::new(root);
12    editor.sync_all_to_parent().map_err(|e| format!("同步失败: {}", e))
13}
14
15#[cfg(test)]
16mod tests {
17    fn git_init(path: &std::path::Path) {
18        let repo = git2::Repository::init(path).unwrap();
19        let mut cfg = repo.config().unwrap();
20        cfg.set_str("user.email", "t@t").unwrap();
21        cfg.set_str("user.name", "t").unwrap();
22    }
23
24    fn git_commit(path: &std::path::Path, msg: &str) {
25        std::fs::write(path.join("f"), msg).unwrap();
26        let repo = git2::Repository::open(path).unwrap();
27        let mut index = repo.index().unwrap();
28        index.add_path(std::path::Path::new("f")).unwrap();
29        index.write().unwrap();
30        let tree_id = index.write_tree().unwrap();
31        let tree = repo.find_tree(tree_id).unwrap();
32        let sig = repo.signature().unwrap();
33        let parent = repo.head().and_then(|h| h.peel_to_commit()).ok();
34        let parents: Vec<&git2::Commit> = parent.iter().collect();
35        repo.commit(Some("HEAD"), &sig, &sig, msg, &tree, &parents).unwrap();
36    }
37
38    use super::*;
39
40
41
42    #[test]
43    fn test_sync_nonexistent_name() {
44        let d = tempfile::tempdir().unwrap();
45        git_init(d.path()); git_commit(d.path(), "init");
46        assert!(sync(d.path().to_path_buf(), "no-such-module").is_err());
47    }
48
49    #[test]
50    fn test_sync_non_git_dir() {
51        let d = tempfile::tempdir().unwrap();
52        assert!(sync(d.path().to_path_buf(), "x").is_err());
53    }
54
55    #[test]
56    fn test_sync_all_empty_repo() {
57        let d = tempfile::tempdir().unwrap();
58        git_init(d.path()); git_commit(d.path(), "init");
59        assert!(sync_all(d.path().to_path_buf()).is_ok());
60    }
61}