Skip to main content

qtcloud_devops_cli/release/
publish.rs

1use std::path::Path;
2
3use super::util::{self, Registry};
4use crate::contract;
5
6/// 发布版本。
7///
8/// 内部处理流程:
9/// 1. 校验版本号格式
10/// 2. 从 contract.yaml 获取 scope 子目录
11/// 3. 自动更新 Cargo.toml / pyproject.toml 版本号
12/// 4. 自动生成 CHANGELOG(如有需要)并提交
13/// 5. 校验 CHANGELOG 包含对应版本记录
14/// 6. 用户确认(除非 `yes = true`)
15/// 7. 创建 git tag → 推送 → 创建 GitHub Release
16pub fn publish(
17    version: &str,
18    repo_path: &Path,
19    yes: bool,
20    registry: Option<Registry>,
21) -> Result<(), Box<dyn std::error::Error>> {
22    if !util::validate_version(version) {
23        return Err(format!("版本号格式错误: {}", version).into());
24    }
25
26    let ver = util::normalize_version(version);
27
28    // 从 version 提取 scope 前缀,从契约获取子目录
29    let scope_dir = resolve_scope_dir(version, repo_path);
30
31    // 自动更新配置文件版本(scope 子目录下)
32    update_config_version(&scope_dir, &ver);
33    // git add 配置文件,让 ensure_changelog 的 commit 一并提交
34    for f in &["Cargo.toml", "pyproject.toml"] {
35        let path = scope_dir.join(f);
36        if path.exists() {
37            std::process::Command::new("git")
38                .args(["add", f])
39                .current_dir(repo_path)
40                .output()
41                .ok();
42        }
43    }
44
45    // 自动生成 CHANGELOG(scope 子目录下)
46    if let Err(e) = super::ensure_changelog(&scope_dir, version) {
47        eprintln!(
48            "⚠ CHANGELOG 生成失败: {}\n   发布将继续,但请确保 CHANGELOG.md 包含版本 {} 的记录。",
49            e, version
50        );
51    }
52
53    let changelog_path = scope_dir.join("CHANGELOG.md");
54    let precheck_errors = util::precheck_version_changelog(version, &changelog_path);
55    if !precheck_errors.is_empty() {
56        return Err(precheck_errors.join("\n").into());
57    }
58
59    if !yes && !util::confirm_release(version, false) {
60        return Err("已取消发布".into());
61    }
62
63    if !util::create_tag(version, repo_path) {
64        return Err(format!("创建标签 {} 失败", version).into());
65    }
66    if !util::push_tag(version, repo_path) {
67        util::rollback_tag(version, repo_path);
68        return Err(format!("推送标签 {} 失败", version).into());
69    }
70    println!("✓ 标签 {} 已创建并推送", version);
71
72    let notes = util::extract_notes(version, &changelog_path);
73    if let Some(repo) = util::get_remote_repo(repo_path) {
74        if !util::create_release(version, notes.as_deref().unwrap_or(""), &repo) {
75            util::rollback_tag(version, repo_path);
76            return Err("创建 GitHub Release 失败".into());
77        }
78        println!("✓ GitHub Release {} 已创建", version);
79        println!("  https://github.com/{}/releases/tag/{}", repo, version);
80    }
81    if let Some(reg) = registry {
82        println!("  {:?} 由 CI 自动发布,无需本地操作", reg);
83    }
84    println!("✓ 版本 {} 已发布", version);
85    Ok(())
86}
87
88/// 从 version 字符串提取 scope,查契约得到子目录。
89fn resolve_scope_dir(version: &str, repo_path: &Path) -> std::path::PathBuf {
90    // "cli/v0.6.0" → scope="cli", "v0.1.0" → scope="(root)"
91    let scope_name = if version.contains('/') {
92        version.split('/').next().unwrap_or("")
93    } else {
94        "(root)"
95    };
96    if scope_name == "(root)" || scope_name.is_empty() {
97        return repo_path.to_path_buf();
98    }
99    // 从契约查找 scope
100    let scopes = contract::load_scopes(repo_path);
101    if let Some(s) = scopes.iter().find(|s| s.name == scope_name) {
102        let d = repo_path.join(&s.dir);
103        if d.exists() {
104            return d;
105        }
106    }
107    // 回退:scope 名作为子目录
108    let d = repo_path.join(scope_name);
109    if d.is_dir() {
110        d
111    } else {
112        repo_path.to_path_buf()
113    }
114}
115
116/// 更新 Cargo.toml / pyproject.toml 中的版本号。
117fn update_config_version(repo_path: &Path, version: &str) {
118    for filename in &["Cargo.toml", "pyproject.toml"] {
119        let path = repo_path.join(filename);
120        let content = match std::fs::read_to_string(&path) {
121            Ok(c) => c,
122            Err(_) => continue,
123        };
124        let updated = update_version_in_content(&content, version);
125        if updated != content {
126            std::fs::write(&path, &updated).ok();
127            println!("✓ {} 版本已更新为 {}", filename, version);
128        }
129    }
130}
131
132fn update_version_in_content(content: &str, new_ver: &str) -> String {
133    let mut result = String::new();
134    for line in content.lines() {
135        let trimmed = line.trim();
136        if trimmed.starts_with("version = \"") {
137            let indent = &line[..line.find("version = \"").unwrap()];
138            result.push_str(&format!("{}version = \"{}\"\n", indent, new_ver));
139        } else if trimmed.starts_with("\"version\":") {
140            let indent = &line[..line.find("\"version\":").unwrap()];
141            result.push_str(&format!("{}\"version\": \"{}\",\n", indent, new_ver));
142        } else {
143            result.push_str(line);
144            result.push('\n');
145        }
146    }
147    result
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153    use std::path::Path;
154
155    fn git_init(path: &Path) {
156        std::process::Command::new("git")
157            .args(["init", "-b", "main"])
158            .current_dir(path)
159            .output()
160            .unwrap();
161        std::process::Command::new("git")
162            .args(["config", "user.email", "test@test.com"])
163            .current_dir(path)
164            .output()
165            .unwrap();
166        std::process::Command::new("git")
167            .args(["config", "user.name", "Test"])
168            .current_dir(path)
169            .output()
170            .unwrap();
171    }
172
173    fn git_commit(path: &Path, msg: &str) {
174        std::fs::write(path.join("file"), msg).unwrap();
175        std::process::Command::new("git")
176            .args(["add", "."])
177            .current_dir(path)
178            .output()
179            .unwrap();
180        std::process::Command::new("git")
181            .args(["commit", "-m", msg])
182            .current_dir(path)
183            .output()
184            .unwrap();
185    }
186
187    #[test]
188    fn test_publish_rejects_invalid_version() {
189        assert!(publish("bad", tempfile::tempdir().unwrap().path(), true, None).is_err());
190    }
191    #[test]
192    fn test_publish_auto_generates_changelog() {
193        let d = tempfile::tempdir().unwrap();
194        git_init(d.path());
195        git_commit(d.path(), "init");
196        let result = publish("v1.0.0", d.path(), true, None);
197        assert!(result.is_ok());
198        let changelog = std::fs::read_to_string(d.path().join("CHANGELOG.md")).unwrap_or_default();
199        assert!(changelog.contains("## [1.0.0]"));
200    }
201    #[test]
202    fn test_publish_formal_with_yes() {
203        let d = tempfile::tempdir().unwrap();
204        let r = publish("v1.0.0", d.path(), true, None);
205        assert!(r.is_ok() || r.is_err());
206    }
207    #[test]
208    fn test_publish_prerelease_with_yes() {
209        let d = tempfile::tempdir().unwrap();
210        git_init(d.path());
211        git_commit(d.path(), "init");
212        std::fs::write(
213            d.path().join("CHANGELOG.md"),
214            "## [1.0.0-rc.1]\n\ncontent\n",
215        )
216        .unwrap();
217        let r = publish("v1.0.0-rc.1", d.path(), true, None);
218        assert!(r.is_ok() || r.is_err());
219    }
220    #[test]
221    fn test_update_version_in_content_toml() {
222        let content = "name = \"foo\"\nversion = \"0.1.0\"\n";
223        assert_eq!(
224            update_version_in_content(content, "0.2.0"),
225            "name = \"foo\"\nversion = \"0.2.0\"\n"
226        );
227    }
228    #[test]
229    fn test_update_version_in_content_json() {
230        let content = "{\n  \"version\": \"1.0.0\",\n}\n";
231        let result = update_version_in_content(content, "2.0.0");
232        assert!(result.contains("\"version\": \"2.0.0\""));
233    }
234}