|
| 1 | +/* |
| 2 | + * This Source Code Form is subject to the |
| 3 | + * terms of the Mozilla Public License, v. |
| 4 | + * 2.0. If a copy of the MPL was not |
| 5 | + * distributed with this file, You can |
| 6 | + * obtain one at |
| 7 | + * http://mozilla.org/MPL/2.0/. |
| 8 | + */ |
| 9 | + |
| 10 | +use std::process::{Command, Stdio}; |
| 11 | + |
| 12 | +use anyhow::Error; |
| 13 | + |
| 14 | +#[derive(Debug)] |
| 15 | +pub struct Commit { |
| 16 | + info: String, |
| 17 | + splits: [usize; 2], |
| 18 | +} |
| 19 | + |
| 20 | +impl Commit { |
| 21 | + pub fn rev_parse(what: &str) -> Result<Self, Error> { |
| 22 | + let output = Command::new("git") |
| 23 | + .args([ |
| 24 | + "--git-dir=.git", |
| 25 | + "show", |
| 26 | + "-s", |
| 27 | + "--format=%H%x00%h%x00%ci", |
| 28 | + what, |
| 29 | + ]) |
| 30 | + .stderr(Stdio::inherit()) |
| 31 | + .stdin(Stdio::null()) |
| 32 | + .output() |
| 33 | + .expect("Failed to get commit info"); |
| 34 | + if !output.status.success() { |
| 35 | + return Err(Error::msg(format!( |
| 36 | + "Git exited with status {} while getting commit info", |
| 37 | + output.status |
| 38 | + ))); |
| 39 | + } |
| 40 | + let mut info = String::from_utf8(output.stdout).expect("Commit info is not valid UTF-8??"); |
| 41 | + let trimmed_len = info.trim_end().len(); |
| 42 | + info.truncate(trimmed_len); |
| 43 | + |
| 44 | + let first_split = info |
| 45 | + .find('\0') |
| 46 | + .expect("Failed to split hash and short hash"); |
| 47 | + let second_split = info[first_split + 1..] |
| 48 | + .find('\0') |
| 49 | + .expect("Failed to split short hash and timestamp") |
| 50 | + + first_split |
| 51 | + + 1; |
| 52 | + |
| 53 | + Ok(Self { |
| 54 | + info, |
| 55 | + splits: [first_split, second_split], |
| 56 | + }) |
| 57 | + } |
| 58 | + |
| 59 | + pub fn hash(&self) -> &str { |
| 60 | + &self.info[..self.splits[0]] |
| 61 | + } |
| 62 | + |
| 63 | + pub fn short_hash(&self) -> &str { |
| 64 | + &self.info[self.splits[0] + 1..self.splits[1]] |
| 65 | + } |
| 66 | + |
| 67 | + pub fn timestamp(&self) -> &str { |
| 68 | + &self.info[self.splits[1] + 1..] |
| 69 | + } |
| 70 | +} |
0 commit comments