1 use std::io;
2 use std::path::{Path, PathBuf};
3 #[cfg(unix)]
4 use std::ptr;
5 use tempfile::TempDir;
6 use url::Url;
7 
8 use crate::Repository;
9 
10 macro_rules! t {
11     ($e:expr) => {
12         match $e {
13             Ok(e) => e,
14             Err(e) => panic!("{} failed with {}", stringify!($e), e),
15         }
16     };
17 }
18 
repo_init() -> (TempDir, Repository)19 pub fn repo_init() -> (TempDir, Repository) {
20     let td = TempDir::new().unwrap();
21     let repo = Repository::init(td.path()).unwrap();
22     {
23         let mut config = repo.config().unwrap();
24         config.set_str("user.name", "name").unwrap();
25         config.set_str("user.email", "email").unwrap();
26         let mut index = repo.index().unwrap();
27         let id = index.write_tree().unwrap();
28 
29         let tree = repo.find_tree(id).unwrap();
30         let sig = repo.signature().unwrap();
31         repo.commit(Some("HEAD"), &sig, &sig, "initial", &tree, &[])
32             .unwrap();
33     }
34     (td, repo)
35 }
36 
path2url(path: &Path) -> String37 pub fn path2url(path: &Path) -> String {
38     Url::from_file_path(path).unwrap().to_string()
39 }
40 
41 #[cfg(windows)]
realpath(original: &Path) -> io::Result<PathBuf>42 pub fn realpath(original: &Path) -> io::Result<PathBuf> {
43     Ok(original.to_path_buf())
44 }
45 #[cfg(unix)]
realpath(original: &Path) -> io::Result<PathBuf>46 pub fn realpath(original: &Path) -> io::Result<PathBuf> {
47     use libc::c_char;
48     use std::ffi::{CStr, CString, OsString};
49     use std::os::unix::prelude::*;
50     extern "C" {
51         fn realpath(name: *const c_char, resolved: *mut c_char) -> *mut c_char;
52     }
53     unsafe {
54         let cstr = CString::new(original.as_os_str().as_bytes())?;
55         let ptr = realpath(cstr.as_ptr(), ptr::null_mut());
56         if ptr.is_null() {
57             return Err(io::Error::last_os_error());
58         }
59         let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
60         libc::free(ptr as *mut _);
61         Ok(PathBuf::from(OsString::from_vec(bytes)))
62     }
63 }
64