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
use std::ascii::AsciiExt;
use std::collections::HashMap;
use std::char::from_digit;
use std::convert::TryFrom;
use std::error::Error;
use std::fmt;
use std::io::{self, Read};
use std::str::from_utf8_unchecked;
use std::sync::Mutex;

use data_encoding::HEXLOWER_PERMISSIVE;
use either::{Either, Left, Right};
use reqwest::header::{Accept, qitem};
use reqwest::{self, Client, StatusCode};
use serde::{ser, de};

lazy_static! {
    static ref KNOWN_COMMITS: Mutex<HashMap<String, [u8; 40]>> = Default::default();
}

/// Git commit from the rust-lang/rust repository.
#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Commit {
    bytes: [u8; 20],
}
impl Commit {
    pub(crate) fn write_to(&self, buf: &mut [u8]) -> usize {
        assert!(buf.len() >= 40, "buffer size too short");
        self.render(buf);
        40
    }
    pub(crate) fn render(&self, buf: &mut [u8]) {
        for (src, dest) in self.bytes.iter().zip(buf.chunks_mut(2)) {
            dest[0] = from_digit(u32::from((src & 0xF0) >> 4), 16).unwrap() as u8;
            if dest.len() > 1 {
                dest[1] = from_digit(u32::from(src & 0x0F), 16).unwrap() as u8;
            }
        }
    }

    fn fetch_full(s: &str) -> Result<[u8; 40], ParseCommitError> {
        if let Ok(kc) = KNOWN_COMMITS.lock() {
            if kc.contains_key(s) {
                return Ok(kc[s].clone());
            }
        }
        let mut res = do catch {
            Client::new()?
                .get(&format!("https://api.github.com/repos/rust-lang/rust/commits/{}", s))?
                .header(Accept(vec![
                    qitem(
                        "application/vnd.github.VERSION.sha".parse().unwrap()
                    ),
                ]))
                .send()?
                .error_for_status()
        }.map_err(|e| {
            match e.status() {
                Some(StatusCode::NotFound) => ParseCommitError::Nonexistent(s.as_bytes()),
                Some(StatusCode::Forbidden) => ParseCommitError::RateLimit(s.as_bytes()),
                _ => ParseCommitError::GitHub(Left(e)),
            }
        })?;

        let mut buf = [0; 40];
        res.read_exact(&mut buf[..]).map_err(|e| {
            ParseCommitError::GitHub(Right(e))
        })?;

        if let Ok(mut kc) = KNOWN_COMMITS.lock() {
            kc.insert(s.to_owned(), buf.clone());
        }

        Ok(buf)
    }

    fn parse_buf(bytes: &[u8]) -> Result<Self, ParseCommitError> {
        let mut buf = [0; 20];
        if HEXLOWER_PERMISSIVE.decode_mut(bytes, &mut buf).is_ok() {
            Ok(Commit { bytes: buf })
        } else {
            Err(ParseCommitError::Format(bytes))
        }
    }
}
/// Copies from the raw commit.
impl<'a> From<&'a [u8; 20]> for Commit {
    fn from(bytes: &'a [u8; 20]) -> Commit {
        Commit { bytes: bytes.clone() }
    }
}
/// Constructs directly from the raw commit.
impl From<[u8; 20]> for Commit {
    fn from(bytes: [u8; 20]) -> Commit {
        Commit { bytes }
    }
}
/// Returns the bytes of the commit.
impl From<Commit> for [u8; 20] {
    fn from(c: Commit) -> [u8; 20] {
        c.bytes
    }
}
/// Returns all 40 digits of the hex string.
impl From<Commit> for [u8; 40] {
    fn from(c: Commit) -> [u8; 40] {
        let mut buf = [0; 40];
        c.render(&mut buf);
        buf
    }
}

impl fmt::Debug for Commit {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}
impl fmt::Display for Commit {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut buf = [0; 40];
        self.render(&mut buf);
        f.pad(unsafe { from_utf8_unchecked(&buf) })
    }
}

impl<'a> TryFrom<&'a [u8]> for Commit {
    type Error = ParseCommitError<'a>;
    fn try_from(bytes: &'a [u8]) -> Result<Commit, ParseCommitError<'a>> {
        if bytes.len() == 20 {
            let mut buf = [0; 20];
            buf.copy_from_slice(bytes);
            Ok(Commit { bytes: buf })
        } else if bytes.len() > 40 {
            Err(ParseCommitError::Length(bytes))
        } else if bytes.iter().any(|b| !b.is_ascii_hexdigit()) {
            Err(ParseCommitError::Format(bytes))
        } else if bytes.len() < 40 {
            let buf = Self::fetch_full(unsafe { from_utf8_unchecked(bytes) })?;
            Self::parse_buf(&buf).map_err(|_| ParseCommitError::Format(bytes))
        } else {
            Self::parse_buf(bytes)
        }
    }
}
impl<'a> TryFrom<&'a str> for Commit {
    type Error = ParseCommitError<'a>;
    fn try_from(s: &'a str) -> Result<Commit, ParseCommitError<'a>> {
        if s.len() == 20 {
            Commit::try_from({
                let mut c = s.chars();
                c.next_back();
                c.as_str()
            })
        } else {
            Commit::try_from(s.as_bytes())
        }
    }
}

impl ser::Serialize for Commit {
    fn serialize<S: ser::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.collect_str(self)
    }
}
impl<'de> de::Deserialize<'de> for Commit {
    fn deserialize<D: de::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        struct CommitVisitor;
        impl<'de> de::Visitor<'de> for CommitVisitor {
            type Value = Commit;
            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a Rust commit")
            }
            fn visit_str<E: de::Error>(self, value: &str) -> Result<Commit, E> {
                Commit::try_from(value)
                    .map_err(|_| E::invalid_value(de::Unexpected::Str(value), &self))
            }
            fn visit_bytes<E: de::Error>(self, value: &[u8]) -> Result<Commit, E> {
                Commit::try_from(value)
                    .map_err(|_| E::invalid_value(de::Unexpected::Bytes(value), &self))
            }
        }
        d.deserialize_any(CommitVisitor)
    }
}

/// Error encountered when parsing a [`Commit`].
///
/// [`Commit`]: struct.Commit.html
pub enum ParseCommitError<'a> {
    /// The given string was too long.
    Length(&'a [u8]),

    /// Could not parse the given bytes as a number in hexadecimal.
    Format(&'a [u8]),

    /// Only a partial commit was given, but the commit didn't exist.
    Nonexistent(&'a [u8]),

    /// A partial commit was given and GitHub rate-limited the request.
    RateLimit(&'a [u8]),

    /// A partial commit was given but it couldn't be fetched from GitHub due to an error.
    GitHub(Either<reqwest::Error, io::Error>),
}
impl<'a> fmt::Debug for ParseCommitError<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ParseCommitError::Length(bytes) => {
                f.debug_tuple("ParseCommitError::Length")
                    .field(&String::from_utf8_lossy(bytes))
                    .finish()
            }
            ParseCommitError::Format(bytes) => {
                f.debug_tuple("ParseCommitError::Format")
                    .field(&String::from_utf8_lossy(bytes))
                    .finish()
            }
            ParseCommitError::Nonexistent(bytes) => {
                f.debug_tuple("ParseCommitError::Nonexistent")
                    .field(&String::from_utf8_lossy(bytes))
                    .finish()
            }
            ParseCommitError::RateLimit(bytes) => {
                f.debug_tuple("ParseCommitError::RateLimit")
                    .field(&String::from_utf8_lossy(bytes))
                    .finish()
            }
            ParseCommitError::GitHub(ref err) => {
                f.debug_tuple("ParseCommitError::GitHub")
                    .field(err)
                    .finish()
            }
        }
    }
}
impl<'a> fmt::Display for ParseCommitError<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ParseCommitError::Length(bytes) => {
                write!(
                    f,
                    "{:?} was too long to be a commit string",
                    String::from_utf8_lossy(bytes)
                )
            }
            ParseCommitError::Format(bytes) => {
                write!(
                    f,
                    "{:?} was not a valid commit string",
                    String::from_utf8_lossy(bytes)
                )
            }
            ParseCommitError::Nonexistent(bytes) => {
                write!(
                    f,
                    "{:?} is not a full commit string, and the commit does not exist",
                    String::from_utf8_lossy(bytes)
                )
            }
            ParseCommitError::RateLimit(bytes) => {
                write!(
                    f,
                    "{:?} is not a full commit string, and GitHub rate-limited",
                    String::from_utf8_lossy(bytes)
                )
            }
            ParseCommitError::GitHub(ref err) => {
                write!(
                    f,
                    "fetching a commit from GitHub failed: {}",
                    err
                )
            }
        }
    }
}
impl<'a> Error for ParseCommitError<'a> {
    fn description(&self) -> &str {
        match *self {
            ParseCommitError::Length(_) => "was too long to be a commit string",
            ParseCommitError::Format(_) => "was not a valid commit string",
            ParseCommitError::Nonexistent(_) => {
                "was not a full commit string, and the commit does not exist"
            }
            ParseCommitError::RateLimit(_) => {
                "was not a full commit string, and GitHub rate-limited"
            }
            ParseCommitError::GitHub(_) => "fetching a commit from GitHub failed",
        }
    }
    fn cause(&self) -> Option<&Error> {
        match *self {
            ParseCommitError::Length(_) |
            ParseCommitError::Format(_) |
            ParseCommitError::Nonexistent(_) |
            ParseCommitError::RateLimit(_) => None,
            ParseCommitError::GitHub(Left(ref err)) => Some(err),
            ParseCommitError::GitHub(Right(ref err)) => Some(err),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::convert::TryFrom;

    use serde_test::{assert_tokens, assert_de_tokens, Token};

    use super::{Commit, ParseCommitError};

    #[test]
    fn parse_display() {
        let orig = "1234567890abcdef1234567890abcdef12345678";
        assert_eq!(Commit::try_from(orig).unwrap().to_string(), orig);
    }

    #[test]
    fn parse_invalid() {
        match Commit::try_from("1234567890abcdef123456789xabcdef12345678") {
            Err(ParseCommitError::Format(b"1234567890abcdef123456789xabcdef12345678")) => (),
            e => panic!("{:?}", e),
        }
        match Commit::try_from("whoops") {
            Err(ParseCommitError::Format(b"whoops")) => (),
            e => panic!("{:?}", e),
        }
        match Commit::try_from("1234567890abcdef1234567890abcdef12345678x") {
            Err(ParseCommitError::Length(b"1234567890abcdef1234567890abcdef12345678x")) => (),
            e => panic!("{:?}", e),
        }
        match Commit::try_from("1234567890abcdef1234567890abcdef123456789") {
            Err(ParseCommitError::Length(b"1234567890abcdef1234567890abcdef123456789")) => (),
            e => panic!("{:?}", e),
        }
    }

    #[test]
    fn partial_valid() {
        // repeat several times to check that caching is working
        for _ in 0..(61 + 1) {
            assert_eq!(
                Commit::try_from("f3d6973f4").unwrap().to_string(),
                "f3d6973f41a7d1fb83029c9c0ceaf0f5d4fd7208"
            );
        }
    }

    #[test]
    fn partial_invalid() {
        match Commit::try_from("123456789") {
            Err(ParseCommitError::Nonexistent(b"123456789")) => (),
            e => panic!("{:?}", e),
        }
    }

    #[test]
    fn serde() {
        assert_tokens(&Commit::try_from("1234567890abcdef1234567890abcdef12345678").unwrap(), &[
            Token::Str("1234567890abcdef1234567890abcdef12345678"),
        ]);
    }

    #[test]
    fn de() {
        assert_de_tokens(&Commit::try_from("f3d6973f4").unwrap(), &[
            Token::Str("f3d6973f4"),
        ]);
        assert_de_tokens(&Commit::try_from(&b"f3d6973f4"[..]).unwrap(), &[
            Token::Bytes(b"f3d6973f4"),
        ]);
        assert_de_tokens(&Commit::try_from(&b"1234567890abcdef1234567890abcdef12345678"[..]).unwrap(), &[
            Token::Bytes(b"1234567890abcdef1234567890abcdef12345678"),
        ]);
    }
}