1use std::path::Path;
4use std::time::{SystemTime, UNIX_EPOCH};
5
6use semver::{BuildMetadata, Prerelease, Version};
7
8use crate::error::{ConfigError, MarsError};
9
10use super::{check, output};
11
12#[derive(Debug, clap::Args)]
14pub struct VersionArgs {
15 pub bump: String,
17 #[arg(long)]
19 pub push: bool,
20 #[arg(long)]
22 pub force: bool,
23}
24
25pub fn run(args: &VersionArgs, ctx: &super::MarsContext, json: bool) -> Result<i32, MarsError> {
27 require_clean_working_tree(&ctx.project_root)?;
28 require_package_check(&ctx.project_root, args.force)?;
29
30 let mut config = crate::config::load(&ctx.project_root)?;
31 let package = config
32 .package
33 .as_mut()
34 .ok_or_else(|| ConfigError::Invalid {
35 message: "mars.toml must contain [package] with name and version".to_string(),
36 })?;
37
38 if package.name.trim().is_empty() {
39 return Err(ConfigError::Invalid {
40 message: "[package].name must not be empty".to_string(),
41 }
42 .into());
43 }
44
45 let current = parse_release_version(&package.version, "[package].version")?;
46 let next = resolve_next_version(&args.bump, ¤t)?;
47
48 if next == current {
49 return Err(ConfigError::Invalid {
50 message: format!(
51 "new version `{}` matches current version `{}`",
52 next, package.version
53 ),
54 }
55 .into());
56 }
57
58 let next_version = next.to_string();
59 let tag = format!("v{next_version}");
60
61 ensure_tag_not_exists(&ctx.project_root, &tag)?;
62
63 package.version = next_version.clone();
64 crate::config::save(&ctx.project_root, &config)?;
65 update_changelog_if_present(&ctx.project_root, &next_version)?;
66
67 crate::platform::process::run_git(
68 &["add", "mars.toml"],
69 &ctx.project_root,
70 "git add mars.toml",
71 )?;
72 if ctx.project_root.join("CHANGELOG.md").is_file() {
73 crate::platform::process::run_git(
74 &["add", "CHANGELOG.md"],
75 &ctx.project_root,
76 "git add CHANGELOG.md",
77 )?;
78 }
79 crate::platform::process::run_git(
80 &["commit", "-m", &tag],
81 &ctx.project_root,
82 &format!("git commit -m {tag}"),
83 )?;
84 crate::platform::process::run_git(
85 &["tag", "-a", &tag, "-m", &tag],
86 &ctx.project_root,
87 &format!("git tag -a {tag} -m {tag}"),
88 )?;
89
90 if args.push {
91 let branch = current_branch(&ctx.project_root)?;
92 crate::platform::process::run_git(
93 &["push", "origin", &branch],
94 &ctx.project_root,
95 &format!("git push origin {branch}"),
96 )?;
97 crate::platform::process::run_git(
98 &["push", "origin", &tag],
99 &ctx.project_root,
100 &format!("git push origin {tag}"),
101 )?;
102 }
103
104 if json {
105 output::print_json(&serde_json::json!({
106 "ok": true,
107 "version": next_version,
108 "tag": tag,
109 "pushed": args.push,
110 }));
111 } else {
112 println!("{tag}");
113 }
114
115 Ok(0)
116}
117
118fn require_clean_working_tree(project_root: &Path) -> Result<(), MarsError> {
119 let output = crate::platform::process::run_git(
120 &["status", "--porcelain"],
121 project_root,
122 "git status --porcelain",
123 )?;
124
125 if !output.is_empty() {
126 return Err(ConfigError::Invalid {
127 message: "working tree must be clean before running `mars version`".to_string(),
128 }
129 .into());
130 }
131
132 Ok(())
133}
134
135fn require_package_check(project_root: &Path, force: bool) -> Result<(), MarsError> {
136 let has_agents = project_root.join("agents").is_dir();
138 let has_skills = project_root.join("skills").is_dir();
139 let has_root_skill = project_root.join("SKILL.md").is_file();
140 if !has_agents && !has_skills && !has_root_skill {
141 return Ok(());
142 }
143
144 match check::check_dir(project_root) {
145 Ok(report) if report.errors.is_empty() => Ok(()),
146 Ok(report) if force => {
147 for error in &report.errors {
148 eprintln!("warning (--force): {error}");
149 }
150 Ok(())
151 }
152 Ok(report) => {
153 let mut message = "package check failed:".to_string();
154 for error in &report.errors {
155 message.push_str(&format!("\n - {error}"));
156 }
157 Err(ConfigError::Invalid { message }.into())
158 }
159 Err(e) if force => {
160 eprintln!("warning (--force): check failed: {e}");
161 Ok(())
162 }
163 Err(e) => Err(e),
164 }
165}
166
167fn parse_release_version(value: &str, field_name: &str) -> Result<Version, MarsError> {
168 let version = Version::parse(value).map_err(|_| ConfigError::Invalid {
169 message: format!("{field_name} must be valid semver (X.Y.Z), got `{value}`"),
170 })?;
171
172 if !version.pre.is_empty() || !version.build.is_empty() {
173 return Err(ConfigError::Invalid {
174 message: format!("{field_name} must be plain X.Y.Z (no prerelease/build): `{value}`"),
175 }
176 .into());
177 }
178
179 Ok(version)
180}
181
182fn resolve_next_version(bump: &str, current: &Version) -> Result<Version, MarsError> {
183 match bump {
184 "patch" => Ok(Version {
185 major: current.major,
186 minor: current.minor,
187 patch: current
188 .patch
189 .checked_add(1)
190 .ok_or_else(|| ConfigError::Invalid {
191 message: "patch version overflow".to_string(),
192 })?,
193 pre: Prerelease::EMPTY,
194 build: BuildMetadata::EMPTY,
195 }),
196 "minor" => Ok(Version {
197 major: current.major,
198 minor: current
199 .minor
200 .checked_add(1)
201 .ok_or_else(|| ConfigError::Invalid {
202 message: "minor version overflow".to_string(),
203 })?,
204 patch: 0,
205 pre: Prerelease::EMPTY,
206 build: BuildMetadata::EMPTY,
207 }),
208 "major" => Ok(Version {
209 major: current
210 .major
211 .checked_add(1)
212 .ok_or_else(|| ConfigError::Invalid {
213 message: "major version overflow".to_string(),
214 })?,
215 minor: 0,
216 patch: 0,
217 pre: Prerelease::EMPTY,
218 build: BuildMetadata::EMPTY,
219 }),
220 explicit => parse_release_version(explicit, "requested version"),
221 }
222}
223
224fn ensure_tag_not_exists(project_root: &Path, tag: &str) -> Result<(), MarsError> {
225 let output = crate::platform::process::run_git(
226 &["tag", "--list", tag],
227 project_root,
228 &format!("git tag --list {tag}"),
229 )?;
230
231 let exists = output.lines().any(|line| line.trim() == tag);
232
233 if exists {
234 return Err(ConfigError::Invalid {
235 message: format!("tag `{tag}` already exists"),
236 }
237 .into());
238 }
239
240 Ok(())
241}
242
243fn current_branch(project_root: &Path) -> Result<String, MarsError> {
244 let branch = crate::platform::process::run_git(
245 &["rev-parse", "--abbrev-ref", "HEAD"],
246 project_root,
247 "git rev-parse --abbrev-ref HEAD",
248 )?;
249 if branch.is_empty() || branch == "HEAD" {
250 return Err(ConfigError::Invalid {
251 message: "cannot push from detached HEAD".to_string(),
252 }
253 .into());
254 }
255
256 Ok(branch)
257}
258
259fn update_changelog_if_present(project_root: &Path, next_version: &str) -> Result<(), MarsError> {
260 let changelog_path = project_root.join("CHANGELOG.md");
261 if !changelog_path.is_file() {
262 return Ok(());
263 }
264
265 let content = std::fs::read_to_string(&changelog_path)?;
266 let Some(updated) = promote_unreleased_changelog(&content, next_version, &today_iso_date())
267 else {
268 return Ok(());
269 };
270
271 if updated.unreleased_was_empty {
272 eprintln!("warning: CHANGELOG.md has no entries under [Unreleased]");
273 }
274
275 std::fs::write(changelog_path, updated.content)?;
276 Ok(())
277}
278
279struct ChangelogPromotion {
280 content: String,
281 unreleased_was_empty: bool,
282}
283
284fn promote_unreleased_changelog(
285 content: &str,
286 next_version: &str,
287 date: &str,
288) -> Option<ChangelogPromotion> {
289 let sections = content.split_inclusive('\n').collect::<Vec<_>>();
290
291 let unreleased_index = sections
292 .iter()
293 .position(|line| is_unreleased_header(line.trim_end()))?;
294 let next_section_index = sections
295 .iter()
296 .enumerate()
297 .skip(unreleased_index + 1)
298 .find_map(|(index, line)| {
299 if line.trim_start().starts_with("## [") {
300 Some(index)
301 } else {
302 None
303 }
304 })
305 .unwrap_or(sections.len());
306
307 let unreleased_was_empty =
308 changelog_section_is_empty(§ions[unreleased_index + 1..next_section_index]);
309
310 let mut promoted = String::new();
311 for line in §ions[..unreleased_index] {
312 promoted.push_str(line);
313 }
314 promoted.push_str("## [Unreleased]\n\n");
315 promoted.push_str(&format!("## [{next_version}] - {date}\n"));
316 for line in §ions[unreleased_index + 1..] {
317 promoted.push_str(line);
318 }
319
320 Some(ChangelogPromotion {
321 content: promoted,
322 unreleased_was_empty,
323 })
324}
325
326fn is_unreleased_header(line: &str) -> bool {
327 let trimmed = line.trim();
328 trimmed.starts_with("## [")
329 && trimmed.ends_with(']')
330 && trimmed
331 .trim_start_matches("## [")
332 .trim_end_matches(']')
333 .eq_ignore_ascii_case("unreleased")
334}
335
336fn changelog_section_is_empty(lines: &[&str]) -> bool {
337 lines.iter().all(|line| {
338 let trimmed = line.trim();
339 trimmed.is_empty() || trimmed.starts_with("###")
340 })
341}
342
343fn today_iso_date() -> String {
344 let days_since_epoch = SystemTime::now()
345 .duration_since(UNIX_EPOCH)
346 .unwrap_or_default()
347 .as_secs()
348 / 86_400;
349 civil_date_from_days(days_since_epoch as i64)
350}
351
352fn civil_date_from_days(days_since_unix_epoch: i64) -> String {
353 let z = days_since_unix_epoch + 719_468;
356 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
357 let doe = z - era * 146_097;
358 let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
359 let y = yoe + era * 400;
360 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
361 let mp = (5 * doy + 2) / 153;
362 let day = doy - (153 * mp + 2) / 5 + 1;
363 let month = mp + if mp < 10 { 3 } else { -9 };
364 let year = y + if month <= 2 { 1 } else { 0 };
365
366 format!("{year:04}-{month:02}-{day:02}")
367}
368
369#[cfg(test)]
370mod tests {
371 use std::ffi::OsStr;
372 use std::path::Path;
373 use std::process::Command;
374
375 use tempfile::TempDir;
376
377 use super::*;
378
379 fn run_git_test<I, S>(cwd: &Path, args: I) -> String
380 where
381 I: IntoIterator<Item = S>,
382 S: AsRef<OsStr>,
383 {
384 let output = Command::new("git")
385 .current_dir(cwd)
386 .args(args)
387 .output()
388 .unwrap();
389 if !output.status.success() {
390 panic!(
391 "git command failed: {}\nstdout:\n{}\nstderr:\n{}",
392 output.status,
393 String::from_utf8_lossy(&output.stdout),
394 String::from_utf8_lossy(&output.stderr)
395 );
396 }
397 String::from_utf8_lossy(&output.stdout).trim().to_string()
398 }
399
400 fn init_repo_with_mars_toml(mars_toml: &str) -> (TempDir, super::super::MarsContext) {
401 let repo = TempDir::new().unwrap();
402 run_git_test(repo.path(), ["init", "."]);
403 run_git_test(repo.path(), ["config", "user.name", "Mars Test"]);
404 run_git_test(repo.path(), ["config", "user.email", "mars@example.com"]);
405
406 std::fs::create_dir_all(repo.path().join(".agents")).unwrap();
407 std::fs::create_dir_all(repo.path().join("agents")).unwrap();
408 std::fs::write(
409 repo.path().join("agents/test-agent.md"),
410 "---\nname: test-agent\ndescription: test\n---\n# Test",
411 )
412 .unwrap();
413 std::fs::write(repo.path().join("mars.toml"), mars_toml).unwrap();
414 run_git_test(repo.path(), ["add", "."]);
415 run_git_test(repo.path(), ["commit", "-m", "init"]);
416
417 let ctx = super::super::MarsContext::for_test(
418 repo.path().to_path_buf(),
419 repo.path().join(".agents"),
420 );
421 (repo, ctx)
422 }
423
424 #[test]
425 fn parse_release_version_accepts_plain_semver() {
426 let parsed = parse_release_version("1.2.3", "field").unwrap();
427 assert_eq!(parsed.to_string(), "1.2.3");
428 }
429
430 #[test]
431 fn parse_release_version_rejects_prerelease() {
432 let err = parse_release_version("1.2.3-alpha.1", "field").unwrap_err();
433 assert!(err.to_string().contains("plain X.Y.Z"));
434 }
435
436 #[test]
437 fn resolve_next_version_bump_kinds() {
438 let current = Version::parse("1.2.3").unwrap();
439
440 assert_eq!(
441 resolve_next_version("patch", ¤t).unwrap().to_string(),
442 "1.2.4"
443 );
444 assert_eq!(
445 resolve_next_version("minor", ¤t).unwrap().to_string(),
446 "1.3.0"
447 );
448 assert_eq!(
449 resolve_next_version("major", ¤t).unwrap().to_string(),
450 "2.0.0"
451 );
452 }
453
454 #[test]
455 fn resolve_next_version_explicit() {
456 let current = Version::parse("1.2.3").unwrap();
457 assert_eq!(
458 resolve_next_version("4.5.6", ¤t).unwrap().to_string(),
459 "4.5.6"
460 );
461 }
462
463 #[test]
464 fn run_patch_updates_version_commits_and_tags() {
465 let (repo, ctx) = init_repo_with_mars_toml(
466 "[package]\nname = \"pkg\"\nversion = \"0.1.0\"\n\n[dependencies]\n",
467 );
468
469 let args = VersionArgs {
470 bump: "patch".to_string(),
471 push: false,
472 force: false,
473 };
474
475 let exit = run(&args, &ctx, true).unwrap();
476 assert_eq!(exit, 0);
477
478 let config = crate::config::load(repo.path()).unwrap();
479 assert_eq!(config.package.unwrap().version, "0.1.1");
480
481 let subject = run_git_test(repo.path(), ["log", "-1", "--pretty=%s"]);
482 assert_eq!(subject, "v0.1.1");
483
484 let tag = run_git_test(repo.path(), ["tag", "--list", "v0.1.1"]);
485 assert_eq!(tag, "v0.1.1");
486 }
487
488 #[test]
489 fn run_promotes_unreleased_in_changelog() {
490 let (repo, ctx) = init_repo_with_mars_toml(
491 "[package]\nname = \"pkg\"\nversion = \"0.1.0\"\n\n[dependencies]\n",
492 );
493 std::fs::write(
494 repo.path().join("CHANGELOG.md"),
495 "# Changelog\n\n## [Unreleased]\n\n### Added\n- New feature X\n\n### Fixed\n- Bug Y\n",
496 )
497 .unwrap();
498 run_git_test(repo.path(), ["add", "CHANGELOG.md"]);
499 run_git_test(repo.path(), ["commit", "-m", "add changelog"]);
500
501 let args = VersionArgs {
502 bump: "patch".to_string(),
503 push: false,
504 force: false,
505 };
506
507 let exit = run(&args, &ctx, true).unwrap();
508 assert_eq!(exit, 0);
509
510 let changelog = std::fs::read_to_string(repo.path().join("CHANGELOG.md")).unwrap();
511 let today = today_iso_date();
512 assert!(changelog.contains("## [Unreleased]\n\n## [0.1.1] - "));
513 assert!(changelog.contains(&format!(
514 "## [0.1.1] - {today}\n\n### Added\n- New feature X"
515 )));
516 assert!(changelog.contains("### Fixed\n- Bug Y"));
517
518 let committed_files =
519 run_git_test(repo.path(), ["show", "--name-only", "--pretty=", "HEAD"]);
520 assert!(committed_files.lines().any(|line| line == "CHANGELOG.md"));
521 }
522
523 #[test]
524 fn run_warns_on_empty_unreleased() {
525 let (repo, ctx) = init_repo_with_mars_toml(
526 "[package]\nname = \"pkg\"\nversion = \"0.1.0\"\n\n[dependencies]\n",
527 );
528 std::fs::write(
529 repo.path().join("CHANGELOG.md"),
530 "# Changelog\n\n## [Unreleased]\n\n### Added\n\n### Fixed\n",
531 )
532 .unwrap();
533 run_git_test(repo.path(), ["add", "CHANGELOG.md"]);
534 run_git_test(repo.path(), ["commit", "-m", "add empty changelog"]);
535
536 let args = VersionArgs {
537 bump: "patch".to_string(),
538 push: false,
539 force: false,
540 };
541
542 let exit = run(&args, &ctx, true).unwrap();
543 assert_eq!(exit, 0);
544
545 let changelog = std::fs::read_to_string(repo.path().join("CHANGELOG.md")).unwrap();
546 assert!(changelog.contains("## [Unreleased]\n\n## [0.1.1] - "));
547 assert!(changelog.contains("## [0.1.1] - "));
548 assert!(
549 promote_unreleased_changelog(
550 "# Changelog\n\n## [Unreleased]\n\n### Added\n\n",
551 "0.1.1",
552 "2026-04-30"
553 )
554 .unwrap()
555 .unreleased_was_empty
556 );
557 }
558
559 #[test]
560 fn run_succeeds_without_changelog() {
561 let (repo, ctx) = init_repo_with_mars_toml(
562 "[package]\nname = \"pkg\"\nversion = \"0.1.0\"\n\n[dependencies]\n",
563 );
564
565 let args = VersionArgs {
566 bump: "patch".to_string(),
567 push: false,
568 force: false,
569 };
570
571 let exit = run(&args, &ctx, true).unwrap();
572 assert_eq!(exit, 0);
573
574 let config = crate::config::load(repo.path()).unwrap();
575 assert_eq!(config.package.unwrap().version, "0.1.1");
576 assert!(!repo.path().join("CHANGELOG.md").exists());
577 }
578
579 #[test]
580 fn run_changelog_preserves_existing_versions() {
581 let (repo, ctx) = init_repo_with_mars_toml(
582 "[package]\nname = \"pkg\"\nversion = \"0.1.0\"\n\n[dependencies]\n",
583 );
584 let prior_section = "## [0.1.0] - 2026-04-01\n\n### Added\n- Initial release\n";
585 std::fs::write(
586 repo.path().join("CHANGELOG.md"),
587 format!("# Changelog\n\n## [Unreleased]\n\n### Fixed\n- Bug Y\n\n{prior_section}"),
588 )
589 .unwrap();
590 run_git_test(repo.path(), ["add", "CHANGELOG.md"]);
591 run_git_test(repo.path(), ["commit", "-m", "add changelog"]);
592
593 let args = VersionArgs {
594 bump: "patch".to_string(),
595 push: false,
596 force: false,
597 };
598
599 let exit = run(&args, &ctx, true).unwrap();
600 assert_eq!(exit, 0);
601
602 let changelog = std::fs::read_to_string(repo.path().join("CHANGELOG.md")).unwrap();
603 assert!(changelog.contains("## [0.1.1] - "));
604 assert!(changelog.contains("### Fixed\n- Bug Y"));
605 assert!(changelog.ends_with(prior_section));
606 }
607
608 #[test]
609 fn run_requires_clean_working_tree() {
610 let (repo, ctx) = init_repo_with_mars_toml(
611 "[package]\nname = \"pkg\"\nversion = \"0.1.0\"\n\n[dependencies]\n",
612 );
613 std::fs::write(repo.path().join("dirty.txt"), "dirty\n").unwrap();
614
615 let args = VersionArgs {
616 bump: "patch".to_string(),
617 push: false,
618 force: false,
619 };
620
621 let err = run(&args, &ctx, true).unwrap_err();
622 assert!(err.to_string().contains("working tree must be clean"));
623
624 let config = crate::config::load(repo.path()).unwrap();
625 assert_eq!(config.package.unwrap().version, "0.1.0");
626 }
627
628 #[test]
629 fn run_requires_package_section() {
630 let (_repo, ctx) =
631 init_repo_with_mars_toml("[dependencies]\nbase = { path = \"../base\" }\n");
632
633 let args = VersionArgs {
634 bump: "patch".to_string(),
635 push: false,
636 force: false,
637 };
638
639 let err = run(&args, &ctx, true).unwrap_err();
640 assert!(err.to_string().contains("must contain [package]"));
641 }
642
643 #[test]
644 fn run_rejects_existing_tag() {
645 let (repo, ctx) = init_repo_with_mars_toml(
646 "[package]\nname = \"pkg\"\nversion = \"0.1.0\"\n\n[dependencies]\n",
647 );
648 run_git_test(repo.path(), ["tag", "-a", "v0.1.1", "-m", "v0.1.1"]);
649
650 let args = VersionArgs {
651 bump: "patch".to_string(),
652 push: false,
653 force: false,
654 };
655
656 let err = run(&args, &ctx, true).unwrap_err();
657 assert!(err.to_string().contains("tag `v0.1.1` already exists"));
658 }
659
660 #[test]
661 fn run_with_push_pushes_branch_and_tag_to_origin() {
662 let (repo, ctx) = init_repo_with_mars_toml(
663 "[package]\nname = \"pkg\"\nversion = \"0.1.0\"\n\n[dependencies]\n",
664 );
665
666 let remote = TempDir::new().unwrap();
667 run_git_test(remote.path(), ["init", "--bare", "."]);
668 run_git_test(
669 repo.path(),
670 ["remote", "add", "origin", remote.path().to_str().unwrap()],
671 );
672
673 let args = VersionArgs {
674 bump: "patch".to_string(),
675 push: true,
676 force: false,
677 };
678
679 let exit = run(&args, &ctx, true).unwrap();
680 assert_eq!(exit, 0);
681
682 let branch = run_git_test(repo.path(), ["rev-parse", "--abbrev-ref", "HEAD"]);
683 let remote_branch = run_git_test(repo.path(), ["ls-remote", "--heads", "origin", &branch]);
684 assert!(remote_branch.contains(&format!("refs/heads/{branch}")));
685
686 let remote_tag = run_git_test(repo.path(), ["ls-remote", "--tags", "origin", "v0.1.1"]);
687 assert!(remote_tag.contains("refs/tags/v0.1.1"));
688 }
689
690 #[test]
693 fn run_aborts_when_package_check_fails() {
694 let (repo, ctx) = init_repo_with_mars_toml(
696 "[package]\nname = \"pkg\"\nversion = \"0.1.0\"\n\n[dependencies]\ndep = { path = \"/nonexistent-dep-xyz-p5\" }\n",
697 );
698
699 let args = VersionArgs {
700 bump: "patch".to_string(),
701 push: false,
702 force: false,
703 };
704
705 let err = run(&args, &ctx, true).unwrap_err();
706 assert!(
707 err.to_string().contains("package check failed"),
708 "expected package check failure: {err}"
709 );
710
711 let config = crate::config::load(repo.path()).unwrap();
712 assert_eq!(
713 config.package.unwrap().version,
714 "0.1.0",
715 "version must not be bumped after check failure"
716 );
717 }
718
719 #[test]
722 fn run_force_bypasses_package_check_errors() {
723 let (repo, ctx) = init_repo_with_mars_toml(
725 "[package]\nname = \"pkg\"\nversion = \"0.1.0\"\n\n[dependencies]\ndep = { path = \"/nonexistent-dep-xyz-p6\" }\n",
726 );
727
728 let args = VersionArgs {
729 bump: "patch".to_string(),
730 push: false,
731 force: true,
732 };
733
734 let exit = run(&args, &ctx, true).unwrap();
735 assert_eq!(exit, 0);
736
737 let config = crate::config::load(repo.path()).unwrap();
738 assert_eq!(
739 config.package.unwrap().version,
740 "0.1.1",
741 "version must be bumped with --force"
742 );
743 }
744}