1use std::ffi::CString;
2use std::marker;
3use std::str;
4
5use crate::util::Binding;
6use crate::{raw, Buf, Direction, Error};
7
8pub struct Refspec<'remote> {
14    raw: *const raw::git_refspec,
15    _marker: marker::PhantomData<&'remote raw::git_remote>,
16}
17
18impl<'remote> Refspec<'remote> {
19    pub fn direction(&self) -> Direction {
21        match unsafe { raw::git_refspec_direction(self.raw) } {
22            raw::GIT_DIRECTION_FETCH => Direction::Fetch,
23            raw::GIT_DIRECTION_PUSH => Direction::Push,
24            n => panic!("unknown refspec direction: {}", n),
25        }
26    }
27
28    pub fn dst(&self) -> Option<&str> {
32        str::from_utf8(self.dst_bytes()).ok()
33    }
34
35    pub fn dst_bytes(&self) -> &[u8] {
37        unsafe { crate::opt_bytes(self, raw::git_refspec_dst(self.raw)).unwrap() }
38    }
39
40    pub fn dst_matches(&self, refname: &str) -> bool {
42        let refname = CString::new(refname).unwrap();
43        unsafe { raw::git_refspec_dst_matches(self.raw, refname.as_ptr()) == 1 }
44    }
45
46    pub fn src(&self) -> Option<&str> {
50        str::from_utf8(self.src_bytes()).ok()
51    }
52
53    pub fn src_bytes(&self) -> &[u8] {
55        unsafe { crate::opt_bytes(self, raw::git_refspec_src(self.raw)).unwrap() }
56    }
57
58    pub fn src_matches(&self, refname: &str) -> bool {
60        let refname = CString::new(refname).unwrap();
61        unsafe { raw::git_refspec_src_matches(self.raw, refname.as_ptr()) == 1 }
62    }
63
64    pub fn is_force(&self) -> bool {
66        unsafe { raw::git_refspec_force(self.raw) == 1 }
67    }
68
69    pub fn str(&self) -> Option<&str> {
73        str::from_utf8(self.bytes()).ok()
74    }
75
76    pub fn bytes(&self) -> &[u8] {
78        unsafe { crate::opt_bytes(self, raw::git_refspec_string(self.raw)).unwrap() }
79    }
80
81    pub fn transform(&self, name: &str) -> Result<Buf, Error> {
83        let name = CString::new(name).unwrap();
84        unsafe {
85            let buf = Buf::new();
86            try_call!(raw::git_refspec_transform(
87                buf.raw(),
88                self.raw,
89                name.as_ptr()
90            ));
91            Ok(buf)
92        }
93    }
94
95    pub fn rtransform(&self, name: &str) -> Result<Buf, Error> {
97        let name = CString::new(name).unwrap();
98        unsafe {
99            let buf = Buf::new();
100            try_call!(raw::git_refspec_rtransform(
101                buf.raw(),
102                self.raw,
103                name.as_ptr()
104            ));
105            Ok(buf)
106        }
107    }
108}
109
110impl<'remote> Binding for Refspec<'remote> {
111    type Raw = *const raw::git_refspec;
112
113    unsafe fn from_raw(raw: *const raw::git_refspec) -> Refspec<'remote> {
114        Refspec {
115            raw,
116            _marker: marker::PhantomData,
117        }
118    }
119    fn raw(&self) -> *const raw::git_refspec {
120        self.raw
121    }
122}