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
// Copyright (c) 2016 vergen developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! Defines the `vergen` function.
//!
//! `vergen` when used in conjunction with the
//! [build script support](http://doc.crates.io/build-script.html) from
//! cargo, generates a file in `OUT_DIR` (defined by cargo) with three functions
//! defined (now, sha, and semver).  This file can then be use with include!
//! to pull the functions into your source for use.
//!
//! # Example Cargo.toml
//! ```toml
//! [package]
//! build = "build.rs"
//!
//! [build-dependencies]
//! vergen = "*"
//! ```
//!
//! # Example build.rs
//! ```ignore
//! // build.rs
//! extern crate vergen;
//!
//! use vergen::vergen;
//!
//! fn main() {
//!     vergen();
//! }
//! ```
//!
//! # Example Usage
//! ```ignore
//! extern crate vergen;
//!
//! include!(concat!(env!("OUT_DIR"), "/version.rs"));
//!
//! fn main() {
//!     version();
//! }
//!
//! // Example version function
//! fn version() -> String {
//!    format!("{} {} blah {}", now(), sha(), semver())
//! }
//! ```
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
#![cfg_attr(feature="clippy", deny(clippy, clippy_pedantic))]
#![deny(missing_docs)]
extern crate time;
#[macro_use]
extern crate bitflags;

use std::env;
use std::fmt;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use std::process::Command;

bitflags!(
/// Output Functions Bitflags
    pub flags OutputFns: u32 {
/// Generate the now fn.
        const NOW         = 0x00000001,
/// Generate the short_now fn.
        const SHORT_NOW   = 0x00000010,
/// Generate the sha fn.
        const SHA         = 0x00000100,
/// Generate the short_sha fn.
        const SHORT_SHA   = 0x00001000,
/// Generate the commit_date fn.
        const COMMIT_DATE = 0x00010000,
/// Generate the target fn.
        const TARGET      = 0x00100000,
/// Generate the semver fn.
        const SEMVER      = 0x01000000,
    }
);

#[derive(Debug, Default)]
/// An error generated by the vergen function.
pub struct VergenError {
    desc: String,
    detail: String,
}

/// Implemented as 'self.desc: self.detail'.
impl fmt::Display for VergenError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}: {}", self.desc, self.detail)
    }
}

impl VergenError {
    /// Create a VergenError struct from the given description and detail.
    pub fn new<T>(desc: &str, detail: T) -> VergenError
        where T: fmt::Display
    {
        VergenError {
            desc: desc.to_owned(),
            detail: format!("{}", detail),
        }
    }
}

impl From<std::env::VarError> for VergenError {
    fn from(e: std::env::VarError) -> VergenError {
        VergenError::new("VarError", e)
    }
}

impl From<std::io::Error> for VergenError {
    fn from(e: std::io::Error) -> VergenError {
        VergenError::new("IOError", e)
    }
}

fn gen_now_fn() -> String {
    let mut now_fn = String::from("/// Generate a timestamp representing now (UTC) in RFC3339 \
                                   format.\n");
    now_fn.push_str("pub fn now() -> &'static str {\n");

    let now = time::now_utc();
    let now_str = format!("{}", now.rfc3339());

    now_fn.push_str("    \"");
    now_fn.push_str(&now_str[..]);
    now_fn.push_str("\"\n");
    now_fn.push_str("}\n\n");

    now_fn
}

fn gen_short_now_fn() -> String {
    let mut now_fn = String::from("/// Generate a timstamp string representing now (UTC).\n");
    now_fn.push_str("pub fn short_now() -> &'static str {\n");

    let now = time::now_utc();
    let now_str = match time::strftime("%F", &now) {
        Ok(n) => n,
        Err(e) => format!("{}", e),
    };

    now_fn.push_str("    \"");
    now_fn.push_str(&now_str[..]);
    now_fn.push_str("\"\n");
    now_fn.push_str("}\n\n");

    now_fn
}

fn gen_sha_fn() -> String {
    let mut sha_fn = String::from("/// Generate a SHA string\n");
    sha_fn.push_str("pub fn sha() -> &'static str {\n");
    sha_fn.push_str("    \"");

    let mut sha_cmd = Command::new("git");
    sha_cmd.args(&["rev-parse", "HEAD"]);

    if let Ok(o) = sha_cmd.output() {
        let po = String::from_utf8_lossy(&o.stdout[..]);
        sha_fn.push_str(po.trim());
    } else {
        sha_fn.push_str("UNKNOWN");
    }

    sha_fn.push_str("\"\n");
    sha_fn.push_str("}\n\n");

    sha_fn
}

fn gen_short_sha_fn() -> String {
    let mut sha_fn = String::from("/// Generate a short SHA string\n");
    sha_fn.push_str("pub fn short_sha() -> &'static str {\n");
    sha_fn.push_str("    \"");

    let mut sha_cmd = Command::new("git");
    sha_cmd.args(&["rev-parse", "--short", "HEAD"]);

    if let Ok(o) = sha_cmd.output() {
        let po = String::from_utf8_lossy(&o.stdout[..]);
        sha_fn.push_str(po.trim());
    } else {
        sha_fn.push_str("UNKNOWN");
    }

    sha_fn.push_str("\"\n");
    sha_fn.push_str("}\n\n");

    sha_fn
}

fn gen_commit_date_fn() -> String {
    let mut commit_date_fn = String::from("/// Generate the commit date string\n");
    commit_date_fn.push_str("pub fn commit_date() -> &'static str {\n");
    commit_date_fn.push_str("    \"");

    let mut log_cmd = Command::new("git");
    log_cmd.args(&["log", "--pretty=format:'%ad'", "-n1", "--date=short"]);

    if let Ok(o) = log_cmd.output() {
        let po = String::from_utf8_lossy(&o.stdout[..]);

        if po.trim().is_empty() {
            commit_date_fn.push_str("");
        } else {
            commit_date_fn.push_str(po.trim().trim_matches('\''));
        }
    } else {
        commit_date_fn.push_str("UNKNOWN");
    }

    commit_date_fn.push_str("\"\n");
    commit_date_fn.push_str("}\n\n");

    commit_date_fn
}

fn gen_target_fn() -> String {
    let mut target_fn = String::from("/// Generate the target triple string\n");

    let target = &(env::var("TARGET").unwrap_or("UNKNOWN".to_owned()))[..];

    target_fn.push_str("pub fn target() -> &'static str {\n");
    target_fn.push_str("    \"");
    target_fn.push_str(target);
    target_fn.push_str("\"\n");
    target_fn.push_str("}\n\n");

    target_fn
}

fn gen_semver_fn() -> String {
    let mut semver_fn = String::from("/// Generate a semver string\n");
    semver_fn.push_str("pub fn semver() -> &'static str {\n");
    semver_fn.push_str("    \"");

    let mut branch_cmd = Command::new("git");
    branch_cmd.args(&["describe"]);

    if let Ok(o) = branch_cmd.output() {
        let po = String::from_utf8_lossy(&o.stdout[..]);
        semver_fn.push_str(po.trim());
    } else {
        semver_fn.push_str("UNKNOWN");
    }

    semver_fn.push_str("\"\n");
    semver_fn.push_str("}\n");

    semver_fn
}

/// Create the `version.rs` file in `OUT_DIR`, and write three functions into it.
///
/// # now
/// ```rust
/// fn now() -> &'static str {
///     // RFC3339 formatted string representing now (UTC)
///     "2015-02-13 11:24:23.613994142-0500"
/// }
/// ```
///
/// # short_now
/// ```rust
/// fn short_now() -> &'static str {
///     // Short string representing now (UTC)
///     "2015-04-07"
/// }
/// ```
///
/// # sha
/// ```rust
/// fn sha() -> &'static str {
///     // Output of the system cmd 'git rev-parse HEAD'
///     "002735cb66437b96cee2a948fcdfc79d9bf96c94"
/// }
/// ```
///
/// # short_sha
/// ```rust
/// fn short_sha() -> &'static str {
///     // Output of the system cmd 'git rev-parse --short HEAD'
///     "002735c"
/// }
/// ```
///
/// # commit_date
/// ```rust
/// fn commit_date() -> &'static str {
///     // Output of the system cmd
///     // 'git log --pretty=format:"%ad" -n1 --date=short'
///     "2015-04-07"
/// }
/// ```
///
/// # target
/// ```rust
/// fn target() -> &'static str {
///     // env::var("TARGET"), set by cargo
///     "x86_64-unknown-linux-gnu"
/// }
/// ```
///
/// # semver
/// ```rust
/// fn semver() -> &'static str {
///     // Output of the system cmd 'git describe'
///     // Note this works best if you create a tag
///     // at each version bump named 'vX.X.X-pre'
///     // and a tag at release named 'vX.X.X'
///     "v0.0.1-pre-24-g002735c"
/// }
/// ```
pub fn vergen(flags: OutputFns) -> Result<(), VergenError> {
    let out = try!(env::var("OUT_DIR"));
    let dst = PathBuf::from(out);
    let mut f = try!(File::create(&dst.join("version.rs")));

    if flags.contains(NOW) {
        try!(f.write_all(gen_now_fn().as_bytes()));
    }

    if flags.contains(SHORT_NOW) {
        try!(f.write_all(gen_short_now_fn().as_bytes()));
    }

    if flags.contains(SHA) {
        try!(f.write_all(gen_sha_fn().as_bytes()));
    }

    if flags.contains(SHORT_SHA) {
        try!(f.write_all(gen_short_sha_fn().as_bytes()));
    }

    if flags.contains(COMMIT_DATE) {
        try!(f.write_all(gen_commit_date_fn().as_bytes()));
    }

    if flags.contains(TARGET) {
        try!(f.write_all(gen_target_fn().as_bytes()));
    }

    if flags.contains(SEMVER) {
        try!(f.write_all(gen_semver_fn().as_bytes()));
    }

    Ok(())
}