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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
use std::ascii::AsciiExt;
use std::char::from_digit;
use std::convert::TryFrom;
use std::error::Error;
use std::fmt;
use std::str::from_utf8_unchecked;
use std::sync::RwLock;
use std::sync::atomic::{AtomicBool, Ordering};
use std::path::PathBuf;

use app_dirs::{AppDataType, AppInfo, app_root};
use git2 as git;
use radix_trie::{Trie, TrieCommon};
use serde::{ser, de};

lazy_static! {
    static ref KNOWN_COMMITS: RwLock<Trie<Vec<u8>, Commit>> = RwLock::new(Trie::new());
    static ref CACHE_DIR: RwLock<Option<PathBuf>> = RwLock::new(None);
}

fn cache_dir() -> Result<PathBuf, git::Error> {
    app_root(
        AppDataType::UserCache,
        &AppInfo { name: "rust-repo-cache", author: "rust-lang" },
    ).map_err(|e| git::Error::from_str(&*e.to_string()))
}

struct BytesNum(usize);
impl fmt::Display for BytesNum {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.0 < 1024 {
            write!(f, "{:7} B", self.0)
        } else if self.0 < 1024 * 1024 {
            write!(f, "{:7.2} kiB", self.0 as f32 / 1024.)
        } else if self.0 < 1024 * 1024 * 1024{
            write!(f, "{:7.2} MiB", self.0 as f32 / 1024. / 1024.)
        } else {
            write!(f, "{:7.2} GiB", self.0 as f32 / 1024. / 1024. / 1024.)
        }
    }
}

/// Refreshes the cache associated with the commit parser.
///
/// This returns more specific errors than simply parsing a commit would.
pub fn freshen_git_cache() -> Result<(), git::Error> {
    {
        let mut cache = CACHE_DIR.write().expect("cache directory lock was poisoned");
        if cache.is_none() {
            *cache = Some(cache_dir()?);
        }
    }
    let repo = {
        let dir = CACHE_DIR.read().expect("cache directory lock was poisoned");
        git::Repository::init_bare(&**dir.as_ref().unwrap())?
    };

    let mut remote = repo.find_remote("origin")
        .or_else(|_| repo.remote("origin", "https://github.com/rust-lang/rust.git"))?;
    let _ = repo.remote_set_url("origin", "https://github.com/rust-lang/rust.git")?;

    eprint!("Connecting to github.com...");
    remote.connect(git::Direction::Fetch)?;
    eprintln!("done.");

    eprint!("Downloading objects from rust-lang/rust.git...");
    remote.fetch(
        &[],
        Some(
            git::FetchOptions::new()
                .download_tags(git::AutotagOption::All)
                .prune(git::FetchPrune::On)
                .remote_callbacks({
                    let mut cbs = git::RemoteCallbacks::new();
                    let first = AtomicBool::new(false);
                    cbs.transfer_progress(move |prog| {
                        if prog.received_objects() < prog.total_objects() {
                            eprint!(
                                "\rDownloaded {:6.2}% of objects ({}) from rust-lang/rust.git...",
                                (prog.received_objects() * 100) as f64 / prog.total_objects() as f64,
                                BytesNum(prog.received_bytes())
                            );
                        } else {
                            if first.swap(false, Ordering::SeqCst) {
                                eprintln!();
                            }
                            eprint!(
                                "\rIndexed {:6.2}% of objects ({}) from rust-lang/rust.git...",
                                (prog.indexed_objects() * 100) as f64 / prog.total_objects() as f64,
                                BytesNum(prog.received_bytes())
                            );
                        }
                        true
                    });
                    cbs
                })
        ),
        None,
    )?;
    remote.disconnect();
    eprintln!("done.");

    eprint!("Updating commit cache...");
    let mut walk = repo.revwalk()?;
    for refer in repo.references()? {
        let refer = refer?;
        if refer.is_tag() || refer.is_remote() {
            let oid = refer.peel(git::ObjectType::Commit)?.id();
            walk.push(oid)?;
        }
    }

    {
        let map = KNOWN_COMMITS.read().expect("commit cache was poisoned");
        for commit in map.values() {
            walk.hide(git::Oid::from_bytes(&commit.bytes)?)?;
        }
    }

    {
        let mut map = KNOWN_COMMITS.write().expect("commit cache was poisoned");
        for oid in walk {
            let oid = oid?;

            let mut raw = [0; 20];
            raw.copy_from_slice(oid.as_bytes());

            let commit = Commit { bytes: raw };

            let mut render = [0; 40];
            commit.render(&mut render);

            map.insert(render.to_vec(), commit);
        }
    }
    eprintln!("done.");

    Ok(())
}

/// 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<Commit, ParseCommitError> {
        for freshened in &[false, true] {
            {
                let kc = KNOWN_COMMITS.read().expect("KNOWN_COMMITS was poisoned");
                if !kc.is_empty() {
                    if let Some(sub) = kc.get_raw_descendant(s.as_bytes()) {
                        let mut it = sub.values();
                        let sha = it.next()
                            .expect("valid sha prefix should always contain at least one commit sha");

                        if it.next().is_some() {
                            return Err(ParseCommitError::Ambiguous(s.as_bytes()));
                        } else {
                            return Ok(sha.clone());
                        }
                    }
                }
            }
            if !freshened {
                match freshen_git_cache() {
                    Ok(()) => (),
                    Err(e) => {
                        eprintln!("git fetch error: {}", e);
                        return Err(ParseCommitError::Fetch);
                    }
                }
            }
        }
        Err(ParseCommitError::Nonexistent(s.as_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);

            let commit = Commit { bytes: buf };

            let render = [0; 40];
            commit.render(&mut buf);

            Commit::fetch_full(unsafe { from_utf8_unchecked(&render) }).map_err(|e| e.with(bytes))?;

            Ok(commit)
        } else if bytes.len() > 40 {
            Err(ParseCommitError::Length(bytes))
        } else if bytes.iter().any(|b| !b.is_ascii_hexdigit()) {
            Err(ParseCommitError::Format(bytes))
        } else {
            Self::fetch_full(unsafe { from_utf8_unchecked(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
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
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]),

    /// Only a partial commit was given, and it was ambiguous.
    Ambiguous(&'a [u8]),

    /// Could not fetch list of commits from GitHub.
    Fetch,
}
impl<'a> ParseCommitError<'a> {
    fn with<'b>(&self, bytes: &'b [u8]) -> ParseCommitError<'b> {
        match *self {
            ParseCommitError::Length(_) => ParseCommitError::Length(bytes),
            ParseCommitError::Format(_) => ParseCommitError::Format(bytes),
            ParseCommitError::Nonexistent(_) => ParseCommitError::Nonexistent(bytes),
            ParseCommitError::Ambiguous(_) => ParseCommitError::Ambiguous(bytes),
            ParseCommitError::Fetch => ParseCommitError::Fetch,
        }
    }
}
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::Ambiguous(bytes) => {
                f.debug_tuple("ParseCommitError::Ambiguous")
                    .field(&String::from_utf8_lossy(bytes))
                    .finish()
            }
            ParseCommitError::Fetch => {
                f.pad("ParseCommitError::Fetch")
            }
        }
    }
}
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,
                    "{:?} was not a commit",
                    String::from_utf8_lossy(bytes)
                )
            }
            ParseCommitError::Ambiguous(bytes) => {
                write!(
                    f,
                    "{:?} represents multiple commits",
                    String::from_utf8_lossy(bytes)
                )
            }
            ParseCommitError::Fetch => f.pad("failed to fetch commits from GitHub"),
        }
    }
}
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 commit",
            ParseCommitError::Ambiguous(_) => "represents multiple commits",
            ParseCommitError::Fetch => "failed to fetch commits from GitHub",
        }
    }
}

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

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

    use super::{Commit, ParseCommitError, freshen_git_cache};

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

    #[test]
    fn parse_invalid() {
        assert_eq!(Commit::try_from("1234567890abcdef123456789xabcdef12345678"), Err(ParseCommitError::Format(b"1234567890abcdef123456789xabcdef12345678")));
        assert_eq!(Commit::try_from("whoops"), Err(ParseCommitError::Format(b"whoops")));
        assert_eq!(Commit::try_from("1234567890abcdef1234567890abcdef12345678x"), Err(ParseCommitError::Length(b"1234567890abcdef1234567890abcdef12345678x")));
        assert_eq!(Commit::try_from("1234567890abcdef1234567890abcdef123456789"), Err(ParseCommitError::Length(b"1234567890abcdef1234567890abcdef123456789")));
    }

    #[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_ambiguous() {
        assert_eq!(
            Commit::try_from("fcae"),
            Err(ParseCommitError::Ambiguous(b"fcae"))
        );
        assert_eq!(
            Commit::try_from("fcae2"),
            Err(ParseCommitError::Nonexistent(b"fcae2"))
        );
    }

    #[test]
    fn partial_invalid() {
        assert_eq!(Commit::try_from("123456789"), Err(ParseCommitError::Nonexistent(b"123456789")));
    }

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

    #[test]
    fn freshen_up() {
        freshen_git_cache().unwrap();
    }

    #[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"f3d6973f41a7d1fb83029c9c0ceaf0f5d4fd7208"[..]).unwrap(), &[
            Token::Bytes(b"f3d6973f41a7d1fb83029c9c0ceaf0f5d4fd7208"),
        ]);
    }
}