jj_release_core 0.5.2

Core library for jj-release: semantic releases for jj-vcs
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! Edit `Cargo.toml` version fields without destroying formatting.

use std::{borrow::ToOwned, fs, path::Path};

use semver::Version;
use serde_json::Value;
use toml_edit::DocumentMut;

use crate::errors::{ReleaseError, Result};
use crate::workspace::WorkspaceManifest;

/// Manages reading and writing version information in project manifests.
///
/// # Example
///
/// ```no_run
/// use jj_release::manifest::{ManifestBackend, CargoManifest};
/// use semver::Version;
/// use std::path::Path;
///
/// let manifest = CargoManifest;
/// let root = Path::new(".");
///
/// let current = manifest.read_version(root).unwrap();
/// println!("Current version: {current}");
///
/// let next = Version::new(current.major, current.minor + 1, 0);
/// manifest.write_version(root, &next).unwrap();
/// ```
pub trait ManifestBackend {
    /// Reads the current version from the project manifest at the given root path.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest file cannot be found, cannot be read due
    /// to permissions, or contains invalid syntax that prevents version extraction.
    fn read_version(&self, root: &Path) -> Result<Version>;

    /// Writes the specified version to the project manifest at the given root path.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest file cannot be read or written due to
    /// permissions, or if serialization of the new version fails.
    fn write_version(&self, root: &Path, version: &Version) -> Result<()>;
}

pub struct CargoManifest;
pub struct GoManifest;
pub struct NpmManifest;

impl ManifestBackend for CargoManifest {
    fn read_version(&self, root: &Path) -> Result<Version> {
        read_version(&root.join("Cargo.toml"))
    }

    fn write_version(&self, root: &Path, version: &Version) -> Result<()> {
        write_version(&root.join("Cargo.toml"), version)
    }
}

impl ManifestBackend for GoManifest {
    fn read_version(&self, _root: &Path) -> Result<Version> {
        // Go modules are versioned by tag only, no manifest version field.
        // Return 0.0.0 so the bump logic computes from scratch.
        Ok(Version::new(0, 0, 0))
    }

    fn write_version(&self, _root: &Path, _version: &Version) -> Result<()> {
        Ok(())
    }
}

impl ManifestBackend for NpmManifest {
    fn read_version(&self, root: &Path) -> Result<Version> {
        let path = root.join("package.json");
        let raw = fs::read_to_string(&path)
            .map_err(|e| ReleaseError::Message(format!("reading {}: {e}", path.display())))?;
        let json: Value = serde_json::from_str(&raw)
            .map_err(|e| ReleaseError::Message(format!("parsing {}: {e}", path.display())))?;
        let version_str = json["version"]
            .as_str()
            .ok_or_else(|| ReleaseError::Message("missing version field in package.json".into()))?;
        Version::parse(version_str).map_err(|_| {
            ReleaseError::Message(format!("invalid semver {version_str:?} in package.json"))
        })
    }

    fn write_version(&self, root: &Path, version: &Version) -> Result<()> {
        let path = root.join("package.json");
        let raw = fs::read_to_string(&path)
            .map_err(|e| ReleaseError::Message(format!("writing {}: {e}", path.display())))?;

        let mut json: Value = serde_json::from_str(&raw)
            .map_err(|e| ReleaseError::Message(format!("parsing {}: {e}", path.display())))?;

        json["version"] = Value::String(version.to_string());
        fs::write(&path, serde_json::to_string_pretty(&json)?)
            .map_err(|e| ReleaseError::Message(format!("writing {}: {e}", path.display())))?;

        Ok(())
    }
}

/// Read the current `[package].version` from `Cargo.toml`.
pub(crate) fn read_version(cargo_toml: &Path) -> Result<Version> {
    let raw = fs::read_to_string(cargo_toml)
        .map_err(|_| ReleaseError::Message(format!("reading {}", cargo_toml.display())))?;

    let doc: DocumentMut = raw
        .parse()
        .map_err(|_| ReleaseError::Message(format!("parsing {}", cargo_toml.display())))?;

    let version_str = doc
        .get("package")
        .and_then(|p| p.get("version"))
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            ReleaseError::Message(format!(
                "missing [package].version in {}",
                cargo_toml.display()
            ))
        })?;

    Version::parse(version_str).map_err(|_| {
        ReleaseError::Message(format!(
            "invalid semver {version_str} in {}",
            cargo_toml.display()
        ))
    })
}

/// Write `new_version` into `[package].version` in `Cargo.toml`, preserving
/// all comments and formatting.
pub(crate) fn write_version(cargo_toml: &Path, new_version: &Version) -> Result<()> {
    let raw = fs::read_to_string(cargo_toml)
        .map_err(|_| ReleaseError::Message(format!("reading {}", cargo_toml.display())))?;

    let mut doc: DocumentMut = raw
        .parse()
        .map_err(|_| ReleaseError::Message(format!("parsing {}", cargo_toml.display())))?;

    // Validate the key exists before mutating.
    if doc["package"]["version"].is_none() {
        return Err(ReleaseError::Message(format!(
            "[package].version not found in {}",
            cargo_toml.display()
        )));
    }

    doc["package"]["version"] = toml_edit::value(new_version.to_string());

    fs::write(cargo_toml, doc.to_string())
        .map_err(|_| ReleaseError::Message(format!("writing {}", cargo_toml.display())))?;

    Ok(())
}

/// Reads the package name from Cargo.toml
///
/// # Errors
/// Returns an error if:
/// - The file can't be read (I/O error)
/// - The TOML syntax is invalid
/// - The `[package].name` field is missing or not a string
pub fn read_name(cargo_toml: &Path) -> Result<String> {
    let raw = fs::read_to_string(cargo_toml)
        .map_err(|_| ReleaseError::Message(format!("reading {}", cargo_toml.display())))?;

    let doc: DocumentMut = raw
        .parse()
        .map_err(|_| ReleaseError::Message(format!("parsing {}", cargo_toml.display())))?;

    doc.get("package")
        .and_then(|p| p.get("name"))
        .and_then(|n| n.as_str())
        .map(ToOwned::to_owned)
        .ok_or_else(|| {
            ReleaseError::Message(format!(
                "missing [package].name in {}",
                cargo_toml.display()
            ))
        })
}

/// Detect and return the appropriate manifest backend for the given root.
/// Returns `WorkspaceManifest` for Rust workspaces, `NpmManifest` for npm,
/// `GoManifest` for Go, and `CargoManifest` as the default.
#[must_use]
pub fn detect_manifest(root: &Path) -> Box<dyn ManifestBackend> {
    let cargo_toml = root.join("Cargo.toml");
    if cargo_toml.exists() {
        if let Ok(content) = std::fs::read_to_string(&cargo_toml)
            && content.contains("[workspace]")
        {
            return Box::new(WorkspaceManifest);
        }
        return Box::new(CargoManifest);
    }
    if root.join("package.json").exists() {
        return Box::new(NpmManifest);
    }
    if root.join("go.mod").exists() {
        return Box::new(GoManifest);
    }
    Box::new(CargoManifest)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    fn make_cargo_toml(content: &str) -> NamedTempFile {
        let mut f = NamedTempFile::new().unwrap();
        f.write_all(content.as_bytes()).unwrap();
        f
    }

    #[test]
    fn read_version_basic() {
        let f = make_cargo_toml(
            r#"[package]
name = "my-crate"
version = "1.2.3"
edition = "2024"
"#,
        );
        let v = read_version(f.path()).unwrap();
        assert_eq!(v, Version::parse("1.2.3").unwrap());
    }

    #[test]
    fn write_version_preserves_formatting() {
        let original = r#"[package]
# Important crate
name = "my-crate"
version = "1.2.3"
edition = "2024"

[dependencies]
anyhow = "1"
"#;
        let f = make_cargo_toml(original);
        let new_v = Version::parse("1.3.0").unwrap();
        write_version(f.path(), &new_v).unwrap();

        let updated = fs::read_to_string(f.path()).unwrap();
        // Comment and other fields must survive.
        assert!(updated.contains("# Important crate"));
        assert!(updated.contains("anyhow = \"1\""));
        assert!(updated.contains("\"1.3.0\""));
        assert!(!updated.contains("\"1.2.3\""));
    }

    #[test]
    fn missing_version_errors() {
        let f = make_cargo_toml("[package]\nname = \"no-version\"\n");
        assert!(read_version(f.path()).is_err());
    }

    #[test]
    fn cargo_manifest_reads_version() {
        let dir = tempfile::tempdir().unwrap();
        let cargo_toml = dir.path().join("Cargo.toml");
        fs::write(
            &cargo_toml,
            r#"[package]
name = "my-crate"
version = "1.2.3"
edition = "2024"
"#,
        )
        .unwrap();
        let manifest = CargoManifest;
        let v = manifest.read_version(dir.path()).unwrap();
        assert_eq!(v, Version::parse("1.2.3").unwrap());
    }

    #[test]
    fn cargo_manifest_writes_version() {
        let dir = tempfile::tempdir().unwrap();
        let cargo_toml = dir.path().join("Cargo.toml");
        fs::write(
            &cargo_toml,
            r#"[package]
name = "my-crate"
version = "1.2.3"
edition = "2024"
"#,
        )
        .unwrap();
        let manifest = CargoManifest;
        manifest
            .write_version(dir.path(), &Version::parse("1.4.0").unwrap())
            .unwrap();
        let updated = std::fs::read_to_string(&cargo_toml).unwrap();
        assert!(updated.contains("\"1.4.0\""));
        assert!(!updated.contains("\"1.2.3\""));
    }

    #[test]
    fn go_manifest_write_version_is_noop() {
        let dir = tempfile::tempdir().unwrap();
        let manifest = GoManifest;
        // should succeed without creating any files
        manifest
            .write_version(dir.path(), &Version::parse("1.2.0").unwrap())
            .unwrap();
        assert!(!dir.path().join("go.mod").exists());
    }

    #[test]
    fn go_manifest_implements_trait() {
        let manifest: &dyn ManifestBackend = &GoManifest;
        let _ = manifest;
    }

    #[test]
    fn npm_manifest_reads_version() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(
            dir.path().join("package.json"),
            r#"{"name": "my-pkg", "version": "1.2.3"}"#,
        )
        .unwrap();
        let manifest = NpmManifest;
        let v = manifest.read_version(dir.path()).unwrap();
        assert_eq!(v, Version::parse("1.2.3").unwrap());
    }

    #[test]
    fn npm_manifest_writes_version() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(
            dir.path().join("package.json"),
            r#"{"name": "my-pkg", "version": "1.2.3"}"#,
        )
        .unwrap();
        let manifest = NpmManifest;
        manifest
            .write_version(dir.path(), &Version::parse("2.0.0").unwrap())
            .unwrap();
        let updated = std::fs::read_to_string(dir.path().join("package.json")).unwrap();
        assert!(updated.contains("\"2.0.0\""));
        assert!(!updated.contains("\"1.2.3\""));
    }

    #[test]
    fn go_manifest_read_returns_zero() {
        let dir = tempfile::tempdir().unwrap();
        let manifest = GoManifest;
        let v = manifest.read_version(dir.path()).unwrap();
        assert_eq!(v, Version::new(0, 0, 0));
    }

    #[test]
    fn go_manifest_write_is_noop() {
        let dir = tempfile::tempdir().unwrap();
        let manifest = GoManifest;
        manifest
            .write_version(dir.path(), &Version::parse("1.0.0").unwrap())
            .unwrap();
        // no files created
        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
    }

    #[test]
    fn npm_manifest_errors_on_missing_package_json() {
        let dir = tempfile::tempdir().unwrap();
        let manifest = NpmManifest;
        assert!(manifest.read_version(dir.path()).is_err());
    }

    #[test]
    fn npm_manifest_errors_on_missing_version_field() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("package.json"), r#"{"name": "no-version"}"#).unwrap();
        let manifest = NpmManifest;
        assert!(manifest.read_version(dir.path()).is_err());
    }
    #[test]
    fn read_name_basic() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            r#"[package]
name = "my-crate"
version = "1.2.3"
edition = "2024"
"#,
        )
        .unwrap();
        assert_eq!(
            read_name(&dir.path().join("Cargo.toml")).unwrap(),
            "my-crate"
        );
    }

    #[test]
    fn read_name_errors_when_missing() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nversion = \"1.0.0\"\n",
        )
        .unwrap();
        assert!(read_name(&dir.path().join("Cargo.toml")).is_err());
    }
    #[test]
    fn detects_workspace_manifest() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("Cargo.toml"), "[workspace]\nmembers = []\n").unwrap();
        let manifest = detect_manifest(dir.path());
        // verify it reads workspace version correctly
        // WorkspaceManifest will fail without [workspace.package] but that's ok
        // just verify it doesn't return CargoManifest
        let _ = manifest; // existence check
    }

    #[test]
    fn detects_npm_manifest() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("package.json"),
            r#"{"name":"test","version":"1.0.0"}"#,
        )
        .unwrap();
        let v = detect_manifest(dir.path())
            .read_version(dir.path())
            .unwrap();
        assert_eq!(v, Version::parse("1.0.0").unwrap());
    }

    #[test]
    fn detects_cargo_manifest() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nname=\"test\"\nversion=\"0.1.0\"\nedition=\"2021\"\n",
        )
        .unwrap();
        let v = detect_manifest(dir.path())
            .read_version(dir.path())
            .unwrap();
        assert_eq!(v, Version::parse("0.1.0").unwrap());
    }
}