cargo-version-info 0.0.16

Cargo subcommand for unified version management across CI/CD, Rust code, and shell scripts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! Post-bump hook for cog integration command.
//!
//! This command is designed to be used as a post-bump hook with cocogitto
//! (cog). It verifies that the version bump was successful after cog has
//! updated Cargo.toml.
//!
//! # Integration with cog
//!
//! Configure in `cog.toml`:
//!
//! ```toml
//! [hooks]
//! post-bump-hook = "cargo version-info post-bump-hook"
//! ```
//!
//! # Examples
//!
//! ```bash
//! # Verify version bump succeeded
//! cargo version-info post-bump-hook
//!
//! # With target and previous versions (from cog)
//! COG_VERSION=1.0.0 COG_LATEST=0.9.0 cargo version-info post-bump-hook
//!
//! # Warn only, don't fail (for testing)
//! cargo version-info post-bump-hook --exit-on-error false
//! ```

use std::path::PathBuf;

use anyhow::{
    Context,
    Result,
};
use cargo_plugin_utils::common::get_package_version_from_manifest;
use clap::Parser;

/// Arguments for the `post-bump-hook` command.
#[derive(Parser, Debug)]
pub struct PostBumpHookArgs {
    /// Path to the Cargo.toml manifest file (standard cargo flag).
    ///
    /// When running as a cargo subcommand, this is automatically handled.
    #[arg(long)]
    manifest_path: Option<PathBuf>,

    /// Path to the git repository.
    ///
    /// Defaults to the current directory. Currently unused but reserved for
    /// future validation against git tags.
    #[arg(long, default_value = ".")]
    repo_path: PathBuf,

    /// Target version that cog bumped to.
    ///
    /// Typically provided by cog via the `{{version}}` template variable.
    /// If set, the command verifies that Cargo.toml matches this version.
    #[arg(long, env = "COG_VERSION")]
    target_version: Option<String>,

    /// Previous version before the bump.
    ///
    /// Typically provided by cog via the `{{latest}}` template variable.
    /// If set, the command verifies that the version actually changed.
    #[arg(long, env = "COG_LATEST")]
    previous_version: Option<String>,

    /// Whether to exit with an error code if verification fails.
    ///
    /// - `true`: Exit with non-zero code if bump verification fails (default)
    /// - `false`: Only print warnings, don't fail the hook
    #[arg(long, default_value = "true")]
    exit_on_error: bool,
}

/// Post-bump hook for cocogitto (cog) integration.
///
/// Verifies that cog successfully bumped the version in Cargo.toml. Performs
/// the following checks:
///
/// 1. **Target Version Match**: If `target_version` is provided, verifies that
///    Cargo.toml contains the expected version after the bump.
/// 2. **Version Change**: If `previous_version` is provided, verifies that the
///    version actually changed (not still the same).
///
/// This hook can be configured in `cog.toml` to run automatically after version
/// bumps, ensuring the bump was applied correctly and catching any failures.
///
/// # Errors
///
/// Returns an error if:
/// - The manifest file cannot be read
/// - No version field is found in Cargo.toml
/// - Target version doesn't match Cargo.toml (and `exit_on_error` is `true`)
/// - Version didn't change from previous (and `exit_on_error` is `true`)
///
/// # Examples
///
/// ```no_run
/// use cargo_version_info::commands::{
///     PostBumpHookArgs,
///     post_bump_hook,
/// };
/// use clap::Parser;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Parse from command line args
/// let args = PostBumpHookArgs::parse_from(&["cargo", "version-info", "post-bump-hook"]);
/// post_bump_hook(args)?;
/// # Ok(())
/// # }
/// ```
///
/// # Example Output
///
/// When bump verification succeeds:
/// ```text
/// ✓ Version bump verified: 1.0.0
///   Previous version: 0.9.0
///   New version: 1.0.0
/// ```
///
/// When target version doesn't match (with `--exit-on-error true`):
/// ```text
/// ❌ Error: Cargo.toml version (0.9.1) doesn't match expected target (1.0.0)
/// Error: Version bump verification failed
/// ```
///
/// When version didn't change (with `--exit-on-error true`):
/// ```text
/// ✓ Post-bump check passed
///   Current version: 0.9.0
/// ⚠️  Warning: Version didn't change (still 0.9.0)
/// Error: Version bump appears to have failed
/// ```
pub fn post_bump_hook(args: PostBumpHookArgs) -> Result<()> {
    let mut logger = cargo_plugin_utils::logger::Logger::new();

    logger.status("Reading", "package version");
    // Get current version from Cargo.toml (after cog bump) using cargo_metadata
    let manifest_path = args
        .manifest_path
        .as_deref()
        .unwrap_or_else(|| std::path::Path::new("./Cargo.toml"));
    let cargo_version = get_package_version_from_manifest(manifest_path)
        .with_context(|| format!("Failed to get version from {}", manifest_path.display()))?;
    logger.finish();

    // If target version is provided, verify it matches
    if let Some(target) = &args.target_version {
        let target_trimmed = target.trim();
        if cargo_version != target_trimmed {
            eprintln!(
                "❌ Error: Cargo.toml version ({}) doesn't match expected target ({})",
                cargo_version, target_trimmed
            );
            if args.exit_on_error {
                anyhow::bail!("Version bump verification failed");
            }
        } else {
            logger.print_message(&format!("✓ Version bump verified: {}", cargo_version));
        }
    } else {
        logger.print_message("✓ Post-bump check passed");
        logger.print_message(&format!("  Current version: {}", cargo_version));
    }

    // Verify version changed from previous
    if let Some(previous) = &args.previous_version {
        let previous_trimmed = previous.trim();
        if cargo_version == previous_trimmed {
            eprintln!(
                "⚠️  Warning: Version didn't change (still {})",
                cargo_version
            );
            if args.exit_on_error {
                anyhow::bail!("Version bump appears to have failed");
            }
        } else {
            logger.print_message(&format!("  Previous version: {}", previous_trimmed));
            logger.print_message(&format!("  New version: {}", cargo_version));
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn create_temp_cargo_project(content: &str) -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        let manifest_path = dir.path().join("Cargo.toml");
        std::fs::write(&manifest_path, content).unwrap();

        // Create src directory with a minimal lib.rs for cargo metadata to work
        let src_dir = dir.path().join("src");
        std::fs::create_dir_all(&src_dir).unwrap();
        std::fs::write(src_dir.join("lib.rs"), "// Test library\n").unwrap();

        dir
    }

    #[test]
    #[serial_test::serial]
    fn test_post_bump_hook_success() {
        let _dir = create_temp_cargo_project(
            r#"
[package]
name = "test"
version = "1.0.0"
"#,
        );
        let manifest_path = _dir.path().join("Cargo.toml");
        let args = PostBumpHookArgs {
            manifest_path: Some(manifest_path),
            repo_path: ".".into(),
            target_version: Some("1.0.0".to_string()),
            previous_version: Some("0.9.0".to_string()),
            exit_on_error: true,
        };
        assert!(post_bump_hook(args).is_ok());
    }

    #[test]
    #[serial_test::serial]
    fn test_post_bump_hook_version_mismatch() {
        let _dir = create_temp_cargo_project(
            r#"
[package]
name = "test"
version = "0.9.1"
"#,
        );
        let manifest_path = _dir.path().join("Cargo.toml");
        let args = PostBumpHookArgs {
            manifest_path: Some(manifest_path),
            repo_path: ".".into(),
            target_version: Some("1.0.0".to_string()),
            previous_version: Some("0.9.0".to_string()),
            exit_on_error: true,
        };
        assert!(post_bump_hook(args).is_err());
    }

    #[test]
    #[serial_test::serial]
    fn test_post_bump_hook_version_unchanged() {
        let _dir = create_temp_cargo_project(
            r#"
[package]
name = "test"
version = "0.9.0"
"#,
        );
        let manifest_path = _dir.path().join("Cargo.toml");
        let args = PostBumpHookArgs {
            manifest_path: Some(manifest_path),
            repo_path: ".".into(),
            target_version: None,
            previous_version: Some("0.9.0".to_string()),
            exit_on_error: true,
        };
        assert!(post_bump_hook(args).is_err());
    }

    #[test]
    #[serial_test::serial]
    fn test_post_bump_hook_no_target_version() {
        let _dir = create_temp_cargo_project(
            r#"
[package]
name = "test"
version = "2.0.0"
"#,
        );
        let manifest_path = _dir.path().join("Cargo.toml");
        let args = PostBumpHookArgs {
            manifest_path: Some(manifest_path),
            repo_path: ".".into(),
            target_version: None,
            previous_version: None,
            exit_on_error: true,
        };
        assert!(post_bump_hook(args).is_ok());
    }

    #[test]
    #[serial_test::serial]
    fn test_post_bump_hook_no_previous_version() {
        let _dir = create_temp_cargo_project(
            r#"
[package]
name = "test"
version = "1.5.0"
"#,
        );
        let manifest_path = _dir.path().join("Cargo.toml");
        let args = PostBumpHookArgs {
            manifest_path: Some(manifest_path),
            repo_path: ".".into(),
            target_version: Some("1.5.0".to_string()),
            previous_version: None,
            exit_on_error: true,
        };
        assert!(post_bump_hook(args).is_ok());
    }

    #[test]
    #[serial_test::serial]
    fn test_post_bump_hook_file_not_found() {
        let args = PostBumpHookArgs {
            manifest_path: Some("/nonexistent/Cargo.toml".into()),
            repo_path: ".".into(),
            target_version: None,
            previous_version: None,
            exit_on_error: true,
        };
        assert!(post_bump_hook(args).is_err());
    }

    #[test]
    #[serial_test::serial]
    fn test_post_bump_hook_no_version() {
        // Cargo defaults to "0.0.0" when no version is specified, so this should
        // succeed
        let _dir = create_temp_cargo_project(
            r#"
[package]
name = "test"
"#,
        );
        let manifest_path = _dir.path().join("Cargo.toml");
        let args = PostBumpHookArgs {
            manifest_path: Some(manifest_path),
            repo_path: ".".into(),
            target_version: None,
            previous_version: None,
            exit_on_error: true,
        };
        // Cargo defaults to 0.0.0, so this should succeed
        assert!(post_bump_hook(args).is_ok());
    }

    #[test]
    #[serial_test::serial]
    fn test_post_bump_hook_exit_on_error_false() {
        let _dir = create_temp_cargo_project(
            r#"
[package]
name = "test"
version = "0.9.1"
"#,
        );
        let manifest_path = _dir.path().join("Cargo.toml");
        let args = PostBumpHookArgs {
            manifest_path: Some(manifest_path),
            repo_path: ".".into(),
            target_version: Some("1.0.0".to_string()),
            previous_version: Some("0.9.0".to_string()),
            exit_on_error: false, // Should warn but not fail
        };
        // Should succeed even with mismatch when exit_on_error is false
        let result = post_bump_hook(args);
        // May succeed (just prints warning) or fail depending on implementation
        let _ = result;
    }

    #[test]
    #[serial_test::serial]
    fn test_post_bump_hook_workspace_version() {
        let _dir = tempfile::tempdir().unwrap();
        // Create workspace root Cargo.toml (no [package] section)
        std::fs::write(
            _dir.path().join("Cargo.toml"),
            r#"
[workspace.package]
version = "2.1.0"

[workspace]
members = ["member1"]
"#,
        )
        .unwrap();

        // Create member package
        let member_dir = _dir.path().join("member1");
        std::fs::create_dir_all(member_dir.join("src")).unwrap();
        std::fs::write(
            member_dir.join("Cargo.toml"),
            r#"
[package]
name = "member1"
version.workspace = true
"#,
        )
        .unwrap();
        std::fs::write(member_dir.join("src").join("lib.rs"), "// Test library\n").unwrap();
        let manifest_path = _dir.path().join("Cargo.toml");
        let args = PostBumpHookArgs {
            manifest_path: Some(manifest_path),
            repo_path: ".".into(),
            target_version: Some("2.1.0".to_string()),
            previous_version: Some("2.0.0".to_string()),
            exit_on_error: true,
        };
        assert!(post_bump_hook(args).is_ok());
    }
}