File: test.rs

package info (click to toggle)
rust-git2 0.13.11-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 1,076 kB
  • sloc: makefile: 6
file content (79 lines) | stat: -rw-r--r-- 2,349 bytes parent folder | download | duplicates (2)
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
use std::fs::File;
use std::io;
use std::path::{Path, PathBuf};
#[cfg(unix)]
use std::ptr;
use tempfile::TempDir;
use url::Url;

use crate::{Oid, Repository};

macro_rules! t {
    ($e:expr) => {
        match $e {
            Ok(e) => e,
            Err(e) => panic!("{} failed with {}", stringify!($e), e),
        }
    };
}

pub fn repo_init() -> (TempDir, Repository) {
    let td = TempDir::new().unwrap();
    let repo = Repository::init(td.path()).unwrap();
    {
        let mut config = repo.config().unwrap();
        config.set_str("user.name", "name").unwrap();
        config.set_str("user.email", "email").unwrap();
        let mut index = repo.index().unwrap();
        let id = index.write_tree().unwrap();

        let tree = repo.find_tree(id).unwrap();
        let sig = repo.signature().unwrap();
        repo.commit(Some("HEAD"), &sig, &sig, "initial", &tree, &[])
            .unwrap();
    }
    (td, repo)
}

pub fn commit(repo: &Repository) -> (Oid, Oid) {
    let mut index = t!(repo.index());
    let root = repo.path().parent().unwrap();
    t!(File::create(&root.join("foo")));
    t!(index.add_path(Path::new("foo")));

    let tree_id = t!(index.write_tree());
    let tree = t!(repo.find_tree(tree_id));
    let sig = t!(repo.signature());
    let head_id = t!(repo.refname_to_id("HEAD"));
    let parent = t!(repo.find_commit(head_id));
    let commit = t!(repo.commit(Some("HEAD"), &sig, &sig, "commit", &tree, &[&parent]));
    (commit, tree_id)
}

pub fn path2url(path: &Path) -> String {
    Url::from_file_path(path).unwrap().to_string()
}

#[cfg(windows)]
pub fn realpath(original: &Path) -> io::Result<PathBuf> {
    Ok(original.to_path_buf())
}
#[cfg(unix)]
pub fn realpath(original: &Path) -> io::Result<PathBuf> {
    use libc::c_char;
    use std::ffi::{CStr, CString, OsString};
    use std::os::unix::prelude::*;
    extern "C" {
        fn realpath(name: *const c_char, resolved: *mut c_char) -> *mut c_char;
    }
    unsafe {
        let cstr = CString::new(original.as_os_str().as_bytes())?;
        let ptr = realpath(cstr.as_ptr(), ptr::null_mut());
        if ptr.is_null() {
            return Err(io::Error::last_os_error());
        }
        let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
        libc::free(ptr as *mut _);
        Ok(PathBuf::from(OsString::from_vec(bytes)))
    }
}