pkg-version-parser 0.1.1

A utility for extracting the version of a package in various programming languages
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
use regex::Regex;
use serde_json::Value;
use std::fs;
use std::path::Path;
use thiserror::Error;
use toml::Value as TomlValue;

#[derive(Error, Debug)]
pub enum VersionError {
    #[error("Invalid language specified")]
    InvalidLanguage,
    #[error("File not found")]
    FileNotFound,
    #[error("Failed to parse file: {0}")]
    ParseError(String),
    #[error("Version not found in file")]
    VersionNotFound,
    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),
}

/// Extracts the version number from package management files of different programming languages.
///
/// # Arguments
/// * `language` - The programming language as a lowercase string (e.g., "python", "typescript")
/// * `file_path` - Path to the package management file
///
/// # Returns
/// * `Result<String, VersionError>` - The version number if found, or an error
///
/// # Example
/// ```
/// use pkg_version_parser::get_version;
///
/// match get_version("python", "path/to/pyproject.toml") {
///     Ok(version) => println!("Python project version: {}", version),
///     Err(e) => eprintln!("Error: {}", e),
/// }
/// ```
pub fn get_version(language: &str, file_path: impl AsRef<Path>) -> Result<String, VersionError> {
    match language {
        "python" => parse_python_version(file_path),
        "typescript" => parse_typescript_version(file_path),
        "go" => parse_go_version(file_path),
        "ruby" => parse_ruby_version(file_path),
        "java" => parse_java_version(file_path),
        "rust" => parse_rust_version(file_path),
        _ => Err(VersionError::InvalidLanguage),
    }
}

fn parse_python_version(file_path: impl AsRef<Path>) -> Result<String, VersionError> {
    let content = fs::read_to_string(file_path).map_err(|_| VersionError::FileNotFound)?;

    let parsed: TomlValue =
        toml::from_str(&content).map_err(|e| VersionError::ParseError(e.to_string()))?;

    parsed
        .get("project")
        .and_then(|project| project.get("version"))
        .and_then(|version| version.as_str())
        .map(String::from)
        .ok_or(VersionError::VersionNotFound)
}

fn parse_typescript_version(file_path: impl AsRef<Path>) -> Result<String, VersionError> {
    let content = fs::read_to_string(file_path).map_err(|_| VersionError::FileNotFound)?;

    let parsed: Value =
        serde_json::from_str(&content).map_err(|e| VersionError::ParseError(e.to_string()))?;

    parsed
        .get("version")
        .and_then(|v| v.as_str())
        .map(String::from)
        .ok_or(VersionError::VersionNotFound)
}

fn parse_go_version(file_path: impl AsRef<Path>) -> Result<String, VersionError> {
    let content = fs::read_to_string(file_path).map_err(|_| VersionError::FileNotFound)?;

    let re = Regex::new(r"go (\d+\.\d+(?:\.\d+)?)")
        .map_err(|e| VersionError::ParseError(e.to_string()))?;

    re.captures(&content)
        .and_then(|caps| caps.get(1))
        .map(|m| m.as_str().to_string())
        .ok_or(VersionError::VersionNotFound)
}

fn parse_ruby_version(file_path: impl AsRef<Path>) -> Result<String, VersionError> {
    let content = fs::read_to_string(file_path).map_err(|_| VersionError::FileNotFound)?;

    let re = Regex::new(r#"ruby\s*["']([\d.]+)["']"#)
        .map_err(|e| VersionError::ParseError(e.to_string()))?;

    re.captures(&content)
        .and_then(|caps| caps.get(1))
        .map(|m| m.as_str().to_string())
        .ok_or(VersionError::VersionNotFound)
}

fn parse_java_version(file_path: impl AsRef<Path>) -> Result<String, VersionError> {
    let content = fs::read_to_string(file_path).map_err(|_| VersionError::FileNotFound)?;

    // Pattern 1: Root level version declaration
    let root_version_re = Regex::new(r#"(?m)^\s*version\s*=?\s*['"]([^'"]+)['"]"#)
        .map_err(|e| VersionError::ParseError(e.to_string()))?;

    // Pattern 2: Version inside publishing block
    let publishing_version_re =
        Regex::new(r#"(?s)publishing\s*\{[^}]*version\s*=\s*['"]([^'"]+)['"]"#)
            .map_err(|e| VersionError::ParseError(e.to_string()))?;

    // Try finding version in root level first
    if let Some(caps) = root_version_re.captures(&content) {
        if let Some(version) = caps.get(1) {
            let version_str = version.as_str();
            if !version_str.starts_with('$') {
                return Ok(version_str.to_string());
            }
        }
    }

    // If not found in root level or if it was a variable, try finding in publishing block
    if let Some(caps) = publishing_version_re.captures(&content) {
        if let Some(version) = caps.get(1) {
            let version_str = version.as_str();
            // If the version is a variable reference (e.g. "$version"),
            // try to find its definition in the root level
            if let Some(var_name) = version_str.strip_prefix('$') {
                let var_pattern = format!(r#"(?m)^\s*{}\s*=?\s*['"]([^'"]+)['"]"#, var_name);
                let var_re = Regex::new(&var_pattern)
                    .map_err(|e| VersionError::ParseError(e.to_string()))?;

                if let Some(var_caps) = var_re.captures(&content) {
                    if let Some(resolved_version) = var_caps.get(1) {
                        return Ok(resolved_version.as_str().to_string());
                    }
                }
            } else {
                return Ok(version_str.to_string());
            }
        }
    }

    Err(VersionError::VersionNotFound)
}

fn parse_rust_version(file_path: impl AsRef<Path>) -> Result<String, VersionError> {
    let content = fs::read_to_string(file_path).map_err(|_| VersionError::FileNotFound)?;

    let parsed: TomlValue =
        toml::from_str(&content).map_err(|e| VersionError::ParseError(e.to_string()))?;

    parsed
        .get("package")
        .and_then(|package| package.get("version"))
        .and_then(|version| version.as_str())
        .map(String::from)
        .ok_or(VersionError::VersionNotFound)
}

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

    fn create_test_file(
        dir: &TempDir,
        filename: &str,
        content: &str,
    ) -> std::io::Result<std::path::PathBuf> {
        let file_path = dir.path().join(filename);
        let mut file = File::create(&file_path)?;
        file.write_all(content.as_bytes())?;
        Ok(file_path)
    }

    #[test]
    fn test_invalid_language() {
        let dir = TempDir::new().unwrap();
        let file_path = dir.path().join("dummy.txt");
        let result = get_version("invalid", file_path);
        assert!(matches!(result, Err(VersionError::InvalidLanguage)));
    }

    #[test]
    fn test_file_not_found() {
        let dir = TempDir::new().unwrap();
        let file_path = dir.path().join("nonexistent.toml");
        let result = get_version("python", file_path);
        assert!(matches!(result, Err(VersionError::FileNotFound)));
    }

    #[test]
    fn test_python_version() {
        let dir = TempDir::new().unwrap();

        // Test standard format
        let content = r#"
[project]
name = "example"
version = "1.2.3"
"#;
        let file_path = create_test_file(&dir, "pyproject.toml", content).unwrap();
        assert_eq!(get_version("python", file_path).unwrap(), "1.2.3");

        // Test with development status classifier
        let content = r#"
[project]
name = "example"
version = "0.1.0-alpha.1"
"#;
        let file_path = create_test_file(&dir, "pyproject.toml", content).unwrap();
        assert_eq!(get_version("python", file_path).unwrap(), "0.1.0-alpha.1");

        // Test invalid TOML
        let content = r#"
[project
name = "example"
version = "1.2.3"
"#;
        let file_path = create_test_file(&dir, "pyproject.toml", content).unwrap();
        assert!(matches!(
            get_version("python", file_path),
            Err(VersionError::ParseError(_))
        ));
    }

    #[test]
    fn test_typescript_version() {
        let dir = TempDir::new().unwrap();

        // Test standard format
        let content = r#"
{
    "name": "example",
    "version": "1.2.3",
    "dependencies": {}
}
"#;
        let file_path = create_test_file(&dir, "package.json", content).unwrap();
        assert_eq!(get_version("typescript", file_path).unwrap(), "1.2.3");

        // Test with pre-release version
        let content = r#"
{
    "name": "example",
    "version": "2.0.0-beta.1"
}
"#;
        let file_path = create_test_file(&dir, "package.json", content).unwrap();
        assert_eq!(
            get_version("typescript", file_path).unwrap(),
            "2.0.0-beta.1"
        );

        // Test invalid JSON
        let content = r#"
{
    "name": "example",
    "version": "1.2.3",
    missing_quote: "value"
}
"#;
        let file_path = create_test_file(&dir, "package.json", content).unwrap();
        assert!(matches!(
            get_version("typescript", file_path),
            Err(VersionError::ParseError(_))
        ));
    }

    #[test]
    fn test_go_version() {
        let dir = TempDir::new().unwrap();

        // Test standard format
        let content = r#"
module example.com/mymodule

go 1.20
require (
    github.com/example/pkg v1.0.0
)
"#;
        let file_path = create_test_file(&dir, "go.mod", content).unwrap();
        assert_eq!(get_version("go", file_path).unwrap(), "1.20");

        // Test with patch version
        let content = "module example.com/mymodule\n\ngo 1.20.5\n";
        let file_path = create_test_file(&dir, "go.mod", content).unwrap();
        assert_eq!(get_version("go", file_path).unwrap(), "1.20.5");

        // Test missing version
        let content = "module example.com/mymodule\n";
        let file_path = create_test_file(&dir, "go.mod", content).unwrap();
        assert!(matches!(
            get_version("go", file_path),
            Err(VersionError::VersionNotFound)
        ));
    }

    #[test]
    fn test_ruby_version() {
        let dir = TempDir::new().unwrap();

        // Test standard format with double quotes
        let content = r#"
source 'https://rubygems.org'
ruby "3.2.0"
gem 'rails', '7.0.0'
"#;
        let file_path = create_test_file(&dir, "Gemfile", content).unwrap();
        assert_eq!(get_version("ruby", file_path).unwrap(), "3.2.0");

        // Test with single quotes
        let content = "source 'https://rubygems.org'\nruby '3.1.2'\n";
        let file_path = create_test_file(&dir, "Gemfile", content).unwrap();
        assert_eq!(get_version("ruby", file_path).unwrap(), "3.1.2");

        // Test missing version
        let content = "source 'https://rubygems.org'\ngem 'rails'\n";
        let file_path = create_test_file(&dir, "Gemfile", content).unwrap();
        assert!(matches!(
            get_version("ruby", file_path),
            Err(VersionError::VersionNotFound)
        ));

        // Test with whitespace variations
        let content = "source 'https://rubygems.org'\nruby     '3.1.3'   \n";
        let file_path = create_test_file(&dir, "Gemfile", content).unwrap();
        assert_eq!(get_version("ruby", file_path).unwrap(), "3.1.3");
    }

    #[test]
    fn test_java_gradle_versions() {
        let dir = TempDir::new().unwrap();

        // Test version in publishing block
        let content = r#"
plugins {
    id 'java-library'
    id 'maven-publish'
}
publishing {
    publications {
        maven(MavenPublication) {
            groupId = 'com.example'
            artifactId = 'library'
            version = '1.0.15'
        }
    }
}
"#;
        let file_path = create_test_file(&dir, "build.gradle", content).unwrap();
        assert_eq!(get_version("java", file_path).unwrap(), "1.0.15");

        // Test root level version
        let content = r#"
plugins {
    id 'java-library'
}
version = '2.1.0'
"#;
        let file_path = create_test_file(&dir, "build.gradle", content).unwrap();
        assert_eq!(get_version("java", file_path).unwrap(), "2.1.0");

        // Test version with no equals sign
        let content = r#"
plugins {
    id 'java-library'
}
version '3.0.0-SNAPSHOT'
"#;
        let file_path = create_test_file(&dir, "build.gradle", content).unwrap();
        assert_eq!(get_version("java", file_path).unwrap(), "3.0.0-SNAPSHOT");

        // Test complex Gradle file with both versions (should return root level version)
        let content = r#"
plugins {
    id 'java-library'
    id 'maven-publish'
}
version = '4.0.0'
publishing {
    publications {
        maven(MavenPublication) {
            version = '1.0.15'
        }
    }
}
"#;
        let file_path = create_test_file(&dir, "build.gradle", content).unwrap();
        assert_eq!(get_version("java", file_path).unwrap(), "4.0.0");

        // Test file with no version
        let content = r#"
plugins {
    id 'java-library'
}
sourceCompatibility = 1.8
"#;
        let file_path = create_test_file(&dir, "build.gradle", content).unwrap();
        assert!(matches!(
            get_version("java", file_path),
            Err(VersionError::VersionNotFound)
        ));

        // Test with variable interpolation
        let content = r#"
plugins {
    id 'java-library'
    id 'maven-publish'
}
publishing {
    publications {
        maven(MavenPublication) {
            version = "5.0.1"
        }
    }
}
version = '5.0.0'
"#;
        let file_path = create_test_file(&dir, "build.gradle", content).unwrap();
        assert_eq!(get_version("java", file_path).unwrap(), "5.0.1");
    }

    #[test]
    fn test_rust_version() {
        let dir = TempDir::new().unwrap();

        // Test standard format
        let content = r#"
[package]
name = "example"
version = "1.2.3"
edition = "2021"
"#;
        let file_path = create_test_file(&dir, "Cargo.toml", content).unwrap();
        assert_eq!(get_version("rust", file_path).unwrap(), "1.2.3");

        // Test with pre-release version
        let content = r#"
[package]
name = "example"
version = "0.1.0-alpha.1"
edition = "2021"
"#;
        let file_path = create_test_file(&dir, "Cargo.toml", content).unwrap();
        assert_eq!(get_version("rust", file_path).unwrap(), "0.1.0-alpha.1");

        // Test with build metadata
        let content = r#"
[package]
name = "example"
version = "1.0.0+build.123"
edition = "2021"
"#;
        let file_path = create_test_file(&dir, "Cargo.toml", content).unwrap();
        assert_eq!(get_version("rust", file_path).unwrap(), "1.0.0+build.123");

        // Test invalid TOML
        let content = r#"
[package
name = "example"
version = "1.2.3"
"#;
        let file_path = create_test_file(&dir, "Cargo.toml", content).unwrap();
        assert!(matches!(
            get_version("rust", file_path),
            Err(VersionError::ParseError(_))
        ));

        // Test missing version
        let content = r#"
[package]
name = "example"
edition = "2021"
"#;
        let file_path = create_test_file(&dir, "Cargo.toml", content).unwrap();
        assert!(matches!(
            get_version("rust", file_path),
            Err(VersionError::VersionNotFound)
        ));
    }

    #[test]
    fn test_version_formats() {
        let dir = TempDir::new().unwrap();

        // Test various version formats across different languages
        let test_cases = vec![
            // Standard versions
            ("1.0.0", true),
            ("1.2.3", true),
            // Pre-release versions
            ("1.0.0-alpha", true),
            ("1.0.0-beta.1", true),
            ("1.0.0-rc.1", true),
            // Build metadata
            ("1.0.0+build.123", true),
            ("1.0.0-alpha+build.123", true),
            // Invalid versions should still be parsed as they appear in the file
            ("invalid.version", true),
            ("1.0", true),
            ("1", true),
        ];

        // Test each version format for each language's typical file
        for (version, should_parse) in test_cases {
            // Test in package.json (TypeScript)
            let ts_content = format!(r#"{{ "name": "test", "version": "{version}" }}"#);
            let file_path = create_test_file(&dir, "package.json", &ts_content).unwrap();
            let result = get_version("typescript", file_path);
            assert_eq!(
                result.is_ok(),
                should_parse,
                "TypeScript version: {}",
                version
            );

            // Test in Cargo.toml (Rust)
            let rust_content = format!(
                r#"[package]
name = "test"
version = "{version}"
"#
            );
            let file_path = create_test_file(&dir, "Cargo.toml", &rust_content).unwrap();
            let result = get_version("rust", file_path);
            assert_eq!(result.is_ok(), should_parse, "Rust version: {}", version);
        }
    }
}