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
#[macro_use]
extern crate cfg_if;

use std::{
    path::Path,
    process::{Command, ExitStatus},
};

pub struct Version {
    pub crate_name: String,
    pub crate_version: String,
    pub source_version: SourceVersion,
    pub compiler_mode: CompilerMode,
    pub os: String,
    pub arch: String,
    pub compiler_version: String,
}

pub enum CompilerMode {
    Debug,
    Release,
}

pub enum SourceVersion {
    None,
    Git {
        branch: String,
        hash: String,
        dirty: bool,
    },
    // TODO? mercurial?
}

impl Version {
    pub fn new<P: AsRef<Path>>(project_dir: P, crate_name: String, crate_version: String) -> Self {
        let v = Version {
            crate_name,
            crate_version,
            source_version: SourceVersion::extract(project_dir.as_ref()),
            compiler_mode: CompilerMode::guess(),
            os: ::std::env::consts::OS.to_owned(),
            arch: ::std::env::consts::ARCH.to_owned(),
            compiler_version: compiler_version(project_dir),
        };

        if let Ok(target) = std::env::var("TARGET") {
            v.with_target(target)
        } else {
            v
        }
    }

    pub fn with_target<T: AsRef<str>>(mut self, target: T) -> Self {
        if let Some(platform_target) = platforms::find(target) {
            self.arch = platform_target.target_arch.as_str().to_owned();
            self.os = platform_target.target_os.as_str().to_owned();
        }
        self
    }

    pub fn simple(&self) -> String {
        format!(
            "{crate_name} {crate_version}{source_version}",
            crate_name = self.crate_name,
            crate_version = self.crate_version,
            source_version = self.source_version.simple()
        )
    }

    pub fn hash(&self) -> String {
        self.source_version.hash()
    }

    pub fn full(&self) -> String {
        format!(
            "{crate_name} {crate_version} ({source_version}, {compiler_mode}, {os} [{arch}]) - [{compiler_version}]",
            crate_name = self.crate_name,
            crate_version = self.crate_version,
            source_version = self.source_version.full(),
            compiler_mode = self.compiler_mode.simple(),
            os = self.os,
            arch = self.arch,
            compiler_version = self.compiler_version,
        )
    }
}

impl CompilerMode {
    fn simple(&self) -> &'static str {
        match self {
            CompilerMode::Debug => "debug",
            CompilerMode::Release => "release",
        }
    }
}

cfg_if! {
    if #[cfg(debug_assertions)] {
        impl CompilerMode {
            pub fn guess() -> Self {
                CompilerMode::Debug
            }
        }
    } else {
        impl CompilerMode {
            pub fn guess() -> Self {
                CompilerMode::Release
            }
        }
    }
}

impl SourceVersion {
    pub fn extract<P: AsRef<Path>>(path: P) -> Self {
        Self::extract_git(path).unwrap_or(SourceVersion::None)
    }

    fn full(&self) -> String {
        match self {
            SourceVersion::None => "".to_owned(),
            SourceVersion::Git {
                branch,
                hash,
                dirty,
            } => format!(
                "{branch}-{hash}{dirty}",
                branch = branch,
                hash = hash,
                dirty = if *dirty { "+" } else { "" }
            ),
        }
    }

    fn simple(&self) -> String {
        match self {
            SourceVersion::None => "".to_owned(),
            SourceVersion::Git { hash, dirty, .. } => {
                format!("-{}{}", hash, if *dirty { "+" } else { "" })
            }
        }
    }

    fn hash(&self) -> String {
        match self {
            SourceVersion::None => "N/A".to_owned(),
            SourceVersion::Git { hash, .. } => hash.clone(),
        }
    }

    fn extract_git<P: AsRef<Path>>(path: P) -> Option<Self> {
        let rev = read_output(
            Command::new("git")
                .current_dir(path.as_ref())
                .arg("rev-parse")
                .arg("--short")
                .arg("HEAD"),
        )?;
        let branch = read_output(
            Command::new("git")
                .current_dir(path.as_ref())
                .arg("rev-parse")
                .arg("--abbrev-ref")
                .arg("HEAD"),
        )?;
        let dirty = get_status_code(
            Command::new("git")
                .current_dir(path)
                .arg("diff")
                .arg("--quiet")
                .arg("--exit-code")
                .arg("HEAD"),
        )?;

        Some(SourceVersion::Git {
            branch,
            hash: rev,
            dirty: !dirty.success(),
        })
    }
}

pub fn compiler_version<P: AsRef<Path>>(path: P) -> String {
    let compiler = read_output(Command::new("rustc").current_dir(path).arg("--version"));

    match compiler {
        None => "N/A".to_owned(),
        Some(version) => version,
    }
}

fn read_output(cmd: &mut Command) -> Option<String> {
    match cmd.output() {
        Ok(output) => {
            if output.status.success() {
                Some(
                    String::from_utf8_lossy(&output.stdout)
                        .trim_end()
                        .to_string(),
                )
            } else {
                None
            }
        }
        Err(error) => {
            use std::io::ErrorKind;
            match error.kind() {
                ErrorKind::NotFound => None,
                ErrorKind::PermissionDenied => None,
                _ => panic!("error while executing command, {:?}: {}", cmd, error),
            }
        }
    }
}

fn get_status_code(cmd: &mut Command) -> Option<ExitStatus> {
    match cmd.status() {
        Ok(status) => Some(status),
        Err(error) => {
            use std::io::ErrorKind;
            match error.kind() {
                ErrorKind::NotFound => None,
                ErrorKind::PermissionDenied => None,
                _ => panic!("error while executing command, {:?}: {}", cmd, error),
            }
        }
    }
}