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
//! General library for Rust

mod error;

pub mod cli;
pub mod conf;

pub use cli::Command;
pub use conf::Config;
pub use error::Fail;

// Version string
static mut VERSION: &str = "";

/// Get version (unsafe, but should be safe unless VERSION is being modified)
pub fn version() -> &'static str {
    unsafe { VERSION }
}

/// Get version string from a Cargo.toml (unsafe, modifies VERSION)
pub fn init_version(cargo_toml: &'static str) -> &str {
    // split by "
    let blocks: Vec<&str> = cargo_toml.split('"').collect();

    // get fourth string
    let version_string = match blocks.get(3) {
        Some(version_string) => {
            // check if contains two dots
            if version_string.split('.').count() == 3 {
                // check if it is actually version
                if blocks[2].contains("version") {
                    // return correct version
                    version_string
                } else {
                    check_version(&blocks, 0)
                }
            } else {
                // check first version
                check_version(&blocks, 0)
            }
        }
        None => check_version(&blocks, 0),
    };

    // modifiy VERSION and return
    unsafe {
        VERSION = version_string;
    }
    version()
}

// Return version string else check next
fn check_version(blocks: &[&'static str], index: usize) -> &'static str {
    // get string at index
    match blocks.get(index) {
        Some(version_string) => {
            // check if contains two dots
            if version_string.split('.').count() == 3 {
                // check if it is actually version
                match blocks.get(index - 1) {
                    Some(previous) => {
                        if previous.contains("version") {
                            // return correct version
                            version_string
                        } else {
                            check_version(&blocks, index + 1)
                        }
                    }
                    None => check_version(&blocks, index + 1),
                }
            } else {
                // check next version
                check_version(blocks, index + 1)
            }
        }
        None => "0.0.0",
    }
}