1use std::collections::HashMap;
2use std::path::Path;
3
4use crate::contract;
5
6pub fn status(repo_path: &Path) {
7 let scopes_map = load_scopes_map(repo_path);
8 let latest_tags = get_latest_tags_by_scope(repo_path);
9 let dirty = is_dirty(repo_path);
10
11 let other_scope_dirs: Vec<std::path::PathBuf> = scopes_map
12 .iter()
13 .filter(|(k, _)| *k != "(root)")
14 .map(|(_, v)| repo_path.join(v))
15 .collect();
16
17 println!("发布状态");
18 println!("{}", "─".repeat(40));
19
20 if latest_tags.is_empty() {
21 println!(" 最新标签: (无)");
22 return;
23 }
24
25 for (scope, tag) in &latest_tags {
26 let tag_only = tag.split('/').last().unwrap_or(tag);
27 let ver = tag_only.strip_prefix('v').unwrap_or(tag_only);
28
29 let scope_dir = if scope == "(root)" {
30 repo_path.to_path_buf()
31 } else {
32 match scopes_map.get(scope) {
33 Some(rel) => repo_path.join(rel),
34 None => {
35 let d = repo_path.join(scope);
36 if d.is_dir() {
37 d
38 } else {
39 repo_path.to_path_buf()
40 }
41 }
42 }
43 };
44
45 println!(" [{}]", scope);
46 let rel_path = scopes_map.get(scope).cloned().unwrap_or_else(|| {
47 if scope == "(root)" {
48 ".".to_string()
49 } else {
50 scope.clone()
51 }
52 });
53 println!(" 路径: {}", rel_path);
54 println!(" 最新标签: {}", tag);
55
56 let unreleased = count_unreleased_in_dir(repo_path, tag, &scope_dir);
57 println!(" 未发布提交: {}", unreleased);
58
59 if check_changelog(&scope_dir, ver) {
60 println!(" CHANGELOG: ✅");
61 } else {
62 println!(" CHANGELOG: ❌ 缺少 {} 条目", ver);
63 }
64
65 check_github_release(repo_path, tag, &scope_dir, ver);
66 check_all_configs(&scope_dir, &other_scope_dirs, ver);
67 }
68
69 if dirty {
70 println!(" 工作区: ❌ 有未提交变更");
71 } else {
72 println!(" 工作区: ✅ 干净");
73 }
74}
75
76fn check_github_release(repo_path: &Path, tag: &str, scope_dir: &Path, _version: &str) {
78 let repo = get_github_repo(repo_path);
80 let repo = match repo {
81 Some(r) => r,
82 None => return,
83 };
84
85 let out = std::process::Command::new("gh")
87 .args([
88 "release", "view", tag, "--repo", &repo, "--json", "body", "--jq", ".body",
89 ])
90 .output()
91 .ok();
92
93 let body = match out {
94 Some(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
95 _ => {
96 println!(" GitHub Release: ❌ 不存在");
97 return;
98 }
99 };
100
101 let changelog_path = scope_dir.join("CHANGELOG.md");
103 let notes = super::util::extract_notes(tag, &changelog_path);
104 let notes = notes.unwrap_or_default();
105
106 if body == notes {
107 println!(" GitHub Release: ✅ body 与 CHANGELOG 一致");
108 } else if body.trim().is_empty() {
109 println!(" GitHub Release: ⚠️ body 为空");
110 } else if notes.is_empty() {
111 println!(" GitHub Release: ✅ 已创建 (CHANGELOG 无此版本条目)");
112 } else {
113 println!(" GitHub Release: ⚠️ body 与 CHANGELOG 不同步");
114 }
115}
116
117fn load_scopes_map(repo_path: &Path) -> HashMap<String, String> {
119 let mut map: HashMap<String, String> = contract::load_scopes(repo_path)
120 .into_iter()
121 .map(|s| (s.name, s.dir))
122 .collect();
123 if !map.contains_key("(root)") {
124 map.insert("(root)".to_string(), "".to_string());
125 }
126 map
127}
128
129fn get_latest_tags_by_scope(repo_path: &Path) -> Vec<(String, String)> {
130 let out = std::process::Command::new("git")
131 .args([
132 "-C",
133 &repo_path.to_string_lossy(),
134 "tag",
135 "--sort=-version:refname",
136 ])
137 .output()
138 .ok();
139 let out = match out {
140 Some(o) if o.status.success() => o,
141 _ => return vec![],
142 };
143 let all: Vec<&str> = std::str::from_utf8(&out.stdout)
144 .unwrap_or("")
145 .lines()
146 .collect();
147 collect_latest_tags(&all)
148}
149
150pub fn collect_latest_tags(tags: &[&str]) -> Vec<(String, String)> {
151 let mut scopes: Vec<(String, String)> = Vec::new();
152 for t in tags {
153 let scope = if t.contains('/') {
154 t.split('/').next().unwrap_or("").to_string()
155 } else {
156 "(root)".to_string()
157 };
158 if !scopes.iter().any(|(s, _)| s == &scope) {
159 scopes.push((scope, t.to_string()));
160 }
161 }
162 scopes
163}
164
165fn count_unreleased_in_dir(repo_path: &Path, tag: &str, scope_dir: &Path) -> usize {
166 let range = format!("{}..HEAD", tag);
167 if scope_dir == repo_path {
168 let out = std::process::Command::new("git")
169 .args([
170 "-C",
171 &repo_path.to_string_lossy(),
172 "rev-list",
173 "--count",
174 &range,
175 ])
176 .output()
177 .ok();
178 return match out {
179 Some(o) if o.status.success() => std::str::from_utf8(&o.stdout)
180 .unwrap_or("0")
181 .trim()
182 .parse()
183 .unwrap_or(0),
184 _ => 0,
185 };
186 }
187 let rel = scope_dir.strip_prefix(repo_path).unwrap_or(scope_dir);
188 let rel_str = rel.to_string_lossy().trim_start_matches('/').to_string();
189 let out = std::process::Command::new("git")
190 .args([
191 "-C",
192 &repo_path.to_string_lossy(),
193 "rev-list",
194 "--count",
195 &range,
196 "--",
197 &rel_str,
198 ])
199 .output()
200 .ok();
201 match out {
202 Some(o) if o.status.success() => std::str::from_utf8(&o.stdout)
203 .unwrap_or("0")
204 .trim()
205 .parse()
206 .unwrap_or(0),
207 _ => 0,
208 }
209}
210
211fn get_github_repo(repo_path: &Path) -> Option<String> {
212 let out = std::process::Command::new("git")
213 .args([
214 "-C",
215 &repo_path.to_string_lossy(),
216 "remote",
217 "get-url",
218 "origin",
219 ])
220 .output()
221 .ok()?;
222 if !out.status.success() {
223 return None;
224 }
225 let url = std::str::from_utf8(&out.stdout).ok()?.trim().to_string();
226 let re = regex::Regex::new(r"github\.com[/:]([^/]+/[^/]+?)(?:\.git)?$").ok()?;
227 let caps = re.captures(&url)?;
228 Some(caps.get(1)?.as_str().to_string())
229}
230
231fn check_all_configs(repo_path: &Path, other_scope_dirs: &[std::path::PathBuf], expected: &str) {
232 let checks: [(&str, fn(&str) -> Option<String>); 5] = [
233 ("Cargo.toml", |c| extract_kv(c, "version")),
234 ("pyproject.toml", |c| extract_kv(c, "version")),
235 ("package.json", extract_json_version),
236 ("pubspec.yaml", |c| extract_kv_yaml(c, "version")),
237 ("setup.cfg", |c| extract_kv(c, "version")),
238 ];
239 for (name, extract) in &checks {
240 let content = match std::fs::read_to_string(&repo_path.join(name)) {
241 Ok(c) => c,
242 Err(_) => continue,
243 };
244 match extract(&content) {
245 Some(v) if v == expected => println!(" {:<15} {} ✅", format!("{}:", name), v),
246 Some(v) => println!(
247 " {:<15} {} ❌ (期望 {})",
248 format!("{}:", name),
249 v,
250 expected
251 ),
252 None => println!(" {:<15} (未找到版本字段)", format!("{}:", name)),
253 }
254 }
255 let vf = repo_path.join("VERSION");
256 if let Ok(c) = std::fs::read_to_string(&vf) {
257 let v = c.trim().to_string();
258 if !v.is_empty() {
259 if v == expected {
260 println!(" VERSION {} ✅", v);
261 } else {
262 println!(" VERSION {} ❌ (期望 {})", v, expected);
263 }
264 }
265 }
266 for p in find_go_files(repo_path, other_scope_dirs) {
267 let content = match std::fs::read_to_string(&p) {
268 Ok(c) => c,
269 Err(_) => continue,
270 };
271 for prefix in &[
272 "var Version = \"",
273 "var VERSION = \"",
274 "const Version = \"",
275 "const VERSION = \"",
276 ] {
277 for line in content.lines() {
278 let t = line.trim();
279 if let Some(rest) = t.strip_prefix(prefix) {
280 if let Some(end) = rest.find('"') {
281 let v = rest[..end].to_string();
282 if !v.is_empty() {
283 let rel = p.strip_prefix(repo_path).unwrap_or(&p);
284 let name = rel.to_string_lossy();
285 if v == expected {
286 println!(" {:<15} {} ✅", format!("{}:", name), v);
287 } else {
288 println!(
289 " {:<15} {} ❌ (期望 {})",
290 format!("{}:", name),
291 v,
292 expected
293 );
294 }
295 }
296 }
297 }
298 }
299 }
300 }
301}
302
303fn find_go_files(dir: &Path, excludes: &[std::path::PathBuf]) -> Vec<std::path::PathBuf> {
304 let mut files = Vec::new();
305 let entries = match std::fs::read_dir(dir) {
306 Ok(e) => e,
307 Err(_) => return files,
308 };
309 for entry in entries.flatten() {
310 let p = entry.path();
311 if p.is_dir() {
312 if excludes.iter().any(|e| p == *e) {
313 continue;
314 }
315 let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
316 if !name.starts_with('.')
317 && name != "node_modules"
318 && name != "target"
319 && name != "vendor"
320 {
321 files.extend(find_go_files(&p, excludes));
322 }
323 } else if p.extension().and_then(|e| e.to_str()) == Some("go") {
324 files.push(p);
325 }
326 }
327 files
328}
329
330fn extract_kv(content: &str, key: &str) -> Option<String> {
331 let p1 = format!("{} = \"", key);
332 let p2 = format!("{} = '", key);
333 for line in content.lines() {
334 let t = line.trim();
335 if let Some(r) = t.strip_prefix(&p1) {
336 if let Some(e) = r.find('"') {
337 let v = r[..e].to_string();
338 if !v.is_empty() {
339 return Some(v);
340 }
341 }
342 }
343 if let Some(r) = t.strip_prefix(&p2) {
344 if let Some(e) = r.find('\'') {
345 let v = r[..e].to_string();
346 if !v.is_empty() {
347 return Some(v);
348 }
349 }
350 }
351 }
352 None
353}
354
355fn extract_json_version(content: &str) -> Option<String> {
356 for line in content.lines() {
357 let t = line.trim();
358 if let Some(r) = t.strip_prefix("\"version\":") {
359 let v = r
360 .trim()
361 .trim_matches('"')
362 .trim_matches('\'')
363 .trim_matches(',');
364 if !v.is_empty() {
365 return Some(v.to_string());
366 }
367 }
368 }
369 None
370}
371
372fn extract_kv_yaml(content: &str, key: &str) -> Option<String> {
373 let p = format!("{}:", key);
374 for line in content.lines() {
375 let t = line.trim();
376 if let Some(r) = t.strip_prefix(&p) {
377 let v = r.trim();
378 if !v.is_empty() && !v.starts_with('#') {
379 return Some(v.to_string());
380 }
381 }
382 }
383 None
384}
385
386fn check_changelog(repo_path: &Path, version: &str) -> bool {
387 if version.is_empty() {
388 return false;
389 }
390 std::fs::read_to_string(repo_path.join("CHANGELOG.md"))
391 .unwrap_or_default()
392 .contains(&format!("[{}]", version))
393}
394
395fn is_dirty(repo_path: &Path) -> bool {
396 let out = std::process::Command::new("git")
397 .args(["-C", &repo_path.to_string_lossy(), "status", "--porcelain"])
398 .output()
399 .ok();
400 match out {
401 Some(o) => !o.stdout.is_empty(),
402 None => false,
403 }
404}
405
406#[cfg(test)]
407mod tests {
408 use super::*;
409
410 #[test]
411 fn test_collect_tags_empty() {
412 assert!(collect_latest_tags(&[]).is_empty());
413 }
414
415 #[test]
416 fn test_collect_tags_root_only() {
417 let tags = collect_latest_tags(&["v2.0.0", "v1.0.0"]);
418 assert_eq!(tags.len(), 1);
419 assert_eq!(tags[0].0, "(root)");
420 assert_eq!(tags[0].1, "v2.0.0");
421 }
422
423 #[test]
424 fn test_collect_tags_scoped() {
425 let tags = collect_latest_tags(&["cli/v0.1.0", "web/v0.2.0"]);
426 assert_eq!(tags.len(), 2);
427 assert_eq!(tags[0].0, "cli");
428 assert_eq!(tags[1].0, "web");
429 }
430
431 #[test]
432 fn test_collect_tags_prerelease_is_kept() {
433 let tags = collect_latest_tags(&["cli/v0.2.0-rc.1", "cli/v0.1.0"]);
435 assert_eq!(tags.len(), 1);
436 assert_eq!(tags[0].1, "cli/v0.2.0-rc.1");
437 }
438
439 #[test]
440 fn test_collect_tags_prerelease_as_fallback() {
441 let tags = collect_latest_tags(&["cli/v0.1.0-rc.2", "cli/v0.1.0-rc.1"]);
442 assert_eq!(tags.len(), 1);
443 assert_eq!(tags[0].1, "cli/v0.1.0-rc.2");
444 }
445
446 fn with_mock_path<F: FnOnce(&Path) -> R, R>(scripts: &[(&str, &str)], f: F) -> R {
448 let dir = tempfile::tempdir().unwrap();
449 let bin = dir.path().join("bin");
450 std::fs::create_dir(&bin).unwrap();
451 for (name, body) in scripts {
452 let path = bin.join(name);
453 std::fs::write(&path, body).unwrap();
454 #[cfg(unix)]
455 std::process::Command::new("chmod")
456 .args(["+x", path.to_str().unwrap()])
457 .output()
458 .unwrap();
459 }
460 let old_path = std::env::var("PATH").unwrap_or_default();
461 std::env::set_var("PATH", format!("{}:{}", bin.display(), old_path));
462 let result = f(dir.path());
463 std::env::set_var("PATH", &old_path);
464 result
465 }
466
467 const GH_NOT_FOUND: &str = "#!/bin/sh\nexit 1\n";
468 const GH_WITH_BODY: &str = "#!/bin/sh\necho '{\"body\":\"content\"}'\n";
469
470 #[test]
471 fn test_status_gh_not_found() {
472 let dir = tempfile::tempdir().unwrap();
474 git_init_test(dir.path());
475 git_tag_test(dir.path(), "v1.0.0");
476 set_remote(dir.path());
477 with_mock_path(&[("gh", GH_NOT_FOUND)], |_| {
478 status(dir.path());
479 });
480 }
481
482 #[test]
483 fn test_status_gh_with_body() {
484 let dir = tempfile::tempdir().unwrap();
486 git_init_test(dir.path());
487 std::fs::write(dir.path().join("CHANGELOG.md"), "## [1.0.0]\n\ncontent\n").unwrap();
488 git_commit_test(dir.path());
489 git_tag_test(dir.path(), "v1.0.0");
490 set_remote(dir.path());
491 with_mock_path(&[("gh", GH_WITH_BODY)], |_| {
492 status(dir.path());
493 });
494 }
495
496 #[test]
497 fn test_status_custom_tags() {
498 let dir = tempfile::tempdir().unwrap();
500 git_init_test(dir.path());
502 git_tag_test(dir.path(), "cli/v0.1.0");
503 git_tag_test(dir.path(), "web/v0.2.0");
504 set_remote(dir.path());
505 with_mock_path(&[("gh", GH_NOT_FOUND)], |_| {
506 status(dir.path());
507 });
508 }
509
510 fn git_init_test(path: &Path) {
513 std::process::Command::new("git")
514 .args(["init", "-b", "main"])
515 .current_dir(path)
516 .output()
517 .unwrap();
518 std::process::Command::new("git")
519 .args(["config", "user.email", "t@t"])
520 .current_dir(path)
521 .output()
522 .unwrap();
523 std::process::Command::new("git")
524 .args(["config", "user.name", "t"])
525 .current_dir(path)
526 .output()
527 .unwrap();
528 std::fs::write(path.join("f"), "").unwrap();
529 std::process::Command::new("git")
530 .args(["add", "."])
531 .current_dir(path)
532 .output()
533 .unwrap();
534 std::process::Command::new("git")
535 .args(["commit", "-m", "init"])
536 .current_dir(path)
537 .output()
538 .unwrap();
539 }
540
541 fn git_commit_test(path: &Path) {
542 std::fs::write(path.join("f"), "x").unwrap();
543 std::process::Command::new("git")
544 .args(["add", "."])
545 .current_dir(path)
546 .output()
547 .unwrap();
548 std::process::Command::new("git")
549 .args(["commit", "-m", "x"])
550 .current_dir(path)
551 .output()
552 .unwrap();
553 }
554
555 fn git_tag_test(path: &Path, tag: &str) {
556 std::process::Command::new("git")
557 .args(["-C", path.to_str().unwrap(), "tag", tag])
558 .output()
559 .unwrap();
560 }
561
562 fn set_remote(path: &Path) {
563 std::process::Command::new("git")
564 .args([
565 "-C",
566 path.to_str().unwrap(),
567 "remote",
568 "add",
569 "origin",
570 "https://github.com/owner/repo.git",
571 ])
572 .output()
573 .unwrap();
574 }
575
576 #[test]
577 fn test_collect_tags_mixed_root_and_scoped() {
578 let tags = collect_latest_tags(&["v1.0.0", "cli/v0.2.0", "cli/v0.1.0"]);
579 assert_eq!(tags.len(), 2);
580 let root = tags.iter().find(|(s, _)| s == "(root)").unwrap();
581 assert_eq!(root.1, "v1.0.0");
582 let cli = tags.iter().find(|(s, _)| s == "cli").unwrap();
583 assert_eq!(cli.1, "cli/v0.2.0");
584 }
585}