Debian Codegraph @

src/util.rs

raw
1 use libc::{c_char, c_int, size_t};
2 use std::cmp::Ordering;
3 use std::ffi::{CString, OsStr, OsString};
4 use std::path::{Component, Path, PathBuf};
5
6 use crate::{raw, Error};
7
8 #[doc(hidden)]
9 pub trait IsNull {
10 fn is_ptr_null(&self) -> bool;
11 }
12 impl<T> IsNull for *const T {
13 fn is_ptr_null(&self) -> bool {
14 self.is_null()
15 }
16 }
17 impl<T> IsNull for *mut T {
18 fn is_ptr_null(&self) -> bool {
19 self.is_null()
20 }
21 }
22
23 /// Provides access to the raw libgit2 pointer to be able to interact with libgit2-sys.
24 ///
25 /// If you are going to depend on this trait on your code, do consider contributing to the git2
26 /// project to add the missing capabilities to git2.
27 pub trait Binding: Sized {
28 /// The raw type that allows you to interact with libgit2-sys.
29 type Raw;
30
31 /// Build a git2 struct from its [Binding::Raw] value.
32 unsafe fn from_raw(raw: Self::Raw) -> Self;
33
34 /// Access the [Binding::Raw] value for a struct.
35 ///
36 /// The returned value is only safe to use while its associated git2 struct is in scope.
37 /// Once the associated git2 struct is destroyed, the raw value can point to an invalid memory address.
38 fn raw(&self) -> Self::Raw;
39
40 /// A null-handling version of [Binding::from_raw].
41 ///
42 /// If the input parameter is null, then the funtion returns None. Otherwise, it
43 /// calls [Binding::from_raw].
44 unsafe fn from_raw_opt<T>(raw: T) -> Option<Self>
45 where
46 T: Copy + IsNull,
47 Self: Binding<Raw = T>,
48 {
49 if raw.is_ptr_null() {
50 None
51 } else {
52 Some(Binding::from_raw(raw))
53 }
54 }
55 }
56
57 /// Converts an iterator of repo paths into a git2-compatible array of cstrings.
58 ///
59 /// Only use this for repo-relative paths or pathspecs.
60 ///
61 /// See `iter2cstrs` for more details.
62 pub fn iter2cstrs_paths<T, I>(
63 iter: I,
64 ) -> Result<(Vec<CString>, Vec<*const c_char>, raw::git_strarray), Error>
65 where
66 T: IntoCString,
67 I: IntoIterator<Item = T>,
68 {
69 let cstrs = iter
70 .into_iter()
71 .map(|i| fixup_windows_path(i.into_c_string()?))
72 .collect::<Result<Vec<CString>, _>>()?;
73 iter2cstrs(cstrs)
74 }
75
76 /// Converts an iterator of things into a git array of c-strings.
77 ///
78 /// Returns a tuple `(cstrings, pointers, git_strarray)`. The first two values
79 /// should not be dropped before `git_strarray`.
80 pub fn iter2cstrs<T, I>(
81 iter: I,
82 ) -> Result<(Vec<CString>, Vec<*const c_char>, raw::git_strarray), Error>
83 where
84 T: IntoCString,
85 I: IntoIterator<Item = T>,
86 {
87 let cstrs = iter
88 .into_iter()
89 .map(|i| i.into_c_string())
90 .collect::<Result<Vec<CString>, _>>()?;
91 let ptrs = cstrs.iter().map(|i| i.as_ptr()).collect::<Vec<_>>();
92 let raw = raw::git_strarray {
93 strings: ptrs.as_ptr() as *mut _,
94 count: ptrs.len() as size_t,
95 };
96 Ok((cstrs, ptrs, raw))
97 }
98
99 #[cfg(unix)]
100 pub fn bytes2path(b: &[u8]) -> &Path {
101 use std::os::unix::prelude::*;
102 Path::new(OsStr::from_bytes(b))
103 }
104 #[cfg(windows)]
105 pub fn bytes2path(b: &[u8]) -> &Path {
106 use std::str;
107 Path::new(str::from_utf8(b).unwrap())
108 }
109
110 /// A class of types that can be converted to C strings.
111 ///
112 /// These types are represented internally as byte slices and it is quite rare
113 /// for them to contain an interior 0 byte.
114 pub trait IntoCString {
115 /// Consume this container, converting it into a CString
116 fn into_c_string(self) -> Result<CString, Error>;
117 }
118
119 impl<'a, T: IntoCString + Clone> IntoCString for &'a T {
120 fn into_c_string(self) -> Result<CString, Error> {
121 self.clone().into_c_string()
122 }
123 }
124
125 impl<'a> IntoCString for &'a str {
126 fn into_c_string(self) -> Result<CString, Error> {
127 Ok(CString::new(self)?)
128 }
129 }
130
131 impl IntoCString for String {
132 fn into_c_string(self) -> Result<CString, Error> {
133 Ok(CString::new(self.into_bytes())?)
134 }
135 }
136
137 impl IntoCString for CString {
138 fn into_c_string(self) -> Result<CString, Error> {
139 Ok(self)
140 }
141 }
142
143 impl<'a> IntoCString for &'a Path {
144 fn into_c_string(self) -> Result<CString, Error> {
145 let s: &OsStr = self.as_ref();
146 s.into_c_string()
147 }
148 }
149
150 impl IntoCString for PathBuf {
151 fn into_c_string(self) -> Result<CString, Error> {
152 let s: OsString = self.into();
153 s.into_c_string()
154 }
155 }
156
157 impl<'a> IntoCString for &'a OsStr {
158 fn into_c_string(self) -> Result<CString, Error> {
159 self.to_os_string().into_c_string()
160 }
161 }
162
163 impl IntoCString for OsString {
164 #[cfg(unix)]
165 fn into_c_string(self) -> Result<CString, Error> {
166 use std::os::unix::prelude::*;
167 let s: &OsStr = self.as_ref();
168 Ok(CString::new(s.as_bytes())?)
169 }
170 #[cfg(windows)]
171 fn into_c_string(self) -> Result<CString, Error> {
172 match self.to_str() {
173 Some(s) => s.into_c_string(),
174 None => Err(Error::from_str(
175 "only valid unicode paths are accepted on windows",
176 )),
177 }
178 }
179 }
180
181 impl<'a> IntoCString for &'a [u8] {
182 fn into_c_string(self) -> Result<CString, Error> {
183 Ok(CString::new(self)?)
184 }
185 }
186
187 impl IntoCString for Vec<u8> {
188 fn into_c_string(self) -> Result<CString, Error> {
189 Ok(CString::new(self)?)
190 }
191 }
192
193 pub fn into_opt_c_string<S>(opt_s: Option<S>) -> Result<Option<CString>, Error>
194 where
195 S: IntoCString,
196 {
197 match opt_s {
198 None => Ok(None),
199 Some(s) => Ok(Some(s.into_c_string()?)),
200 }
201 }
202
203 pub fn c_cmp_to_ordering(cmp: c_int) -> Ordering {
204 match cmp {
205 0 => Ordering::Equal,
206 n if n < 0 => Ordering::Less,
207 _ => Ordering::Greater,
208 }
209 }
210
211 /// Converts a path to a CString that is usable by the libgit2 API.
212 ///
213 /// Checks if it is a relative path.
214 ///
215 /// On Windows, this also requires the path to be valid Unicode, and translates
216 /// back slashes to forward slashes.
217 pub fn path_to_repo_path(path: &Path) -> Result<CString, Error> {
218 macro_rules! err {
219 ($msg:literal, $path:expr) => {
220 return Err(Error::from_str(&format!($msg, $path.display())))
221 };
222 }
223 match path.components().next() {
224 None => return Err(Error::from_str("repo path should not be empty")),
225 Some(Component::Prefix(_)) => err!(
226 "repo path `{}` should be relative, not a windows prefix",
227 path
228 ),
229 Some(Component::RootDir) => err!("repo path `{}` should be relative", path),
230 Some(Component::CurDir) => err!("repo path `{}` should not start with `.`", path),
231 Some(Component::ParentDir) => err!("repo path `{}` should not start with `..`", path),
232 Some(Component::Normal(_)) => {}
233 }
234 #[cfg(windows)]
235 {
236 match path.to_str() {
237 None => {
238 return Err(Error::from_str(
239 "only valid unicode paths are accepted on windows",
240 ))
241 }
242 Some(s) => return fixup_windows_path(s),
243 }
244 }
245 #[cfg(not(windows))]
246 {
247 path.into_c_string()
248 }
249 }
250
251 pub fn cstring_to_repo_path<T: IntoCString>(path: T) -> Result<CString, Error> {
252 fixup_windows_path(path.into_c_string()?)
253 }
254
255 #[cfg(windows)]
256 fn fixup_windows_path<P: Into<Vec<u8>>>(path: P) -> Result<CString, Error> {
257 let mut bytes: Vec<u8> = path.into();
258 for i in 0..bytes.len() {
259 if bytes[i] == b'\\' {
260 bytes[i] = b'/';
261 }
262 }
263 Ok(CString::new(bytes)?)
264 }
265
266 #[cfg(not(windows))]
267 fn fixup_windows_path(path: CString) -> Result<CString, Error> {
268 Ok(path)
269 }
270
271 /// Creates a zeroed `git_oid` to be used as an output buffer
272 /// that libgit2 overwrites before any read.
273 ///
274 /// Defaults `kind` to `GIT_OID_SHA1` so the value is a valid
275 /// `git_oid_t` even transiently.
276 #[inline]
277 pub(crate) fn zeroed_raw_oid() -> raw::git_oid {
278 raw::git_oid {
279 #[cfg(feature = "unstable-sha256")]
280 kind: raw::GIT_OID_SHA1 as libc::c_uchar,
281 id: [0; raw::GIT_OID_MAX_SIZE],
282 }
283 }
284
285 #[cfg(test)]
286 mod tests {
287 use super::*;
288
289 macro_rules! assert_err {
290 ($path:expr, $msg:expr) => {
291 match path_to_repo_path(Path::new($path)) {
292 Ok(_) => panic!("expected `{}` to err", $path),
293 Err(e) => assert_eq!(e.message(), $msg),
294 }
295 };
296 }
297
298 macro_rules! assert_repo_path_ok {
299 ($path:expr) => {
300 assert_repo_path_ok!($path, $path)
301 };
302 ($path:expr, $expect:expr) => {
303 assert_eq!(
304 path_to_repo_path(Path::new($path)),
305 Ok(CString::new($expect).unwrap())
306 );
307 };
308 }
309
310 #[test]
311 #[cfg(windows)]
312 fn path_to_repo_path_translate() {
313 assert_repo_path_ok!("foo");
314 assert_repo_path_ok!("foo/bar");
315 assert_repo_path_ok!(r"foo\bar", "foo/bar");
316 assert_repo_path_ok!(r"foo\bar\", "foo/bar/");
317 }
318
319 #[test]
320 fn path_to_repo_path_no_weird() {
321 assert_err!("", "repo path should not be empty");
322 assert_err!("./foo", "repo path `./foo` should not start with `.`");
323 assert_err!("../foo", "repo path `../foo` should not start with `..`");
324 }
325
326 #[test]
327 #[cfg(not(windows))]
328 fn path_to_repo_path_no_absolute() {
329 assert_err!("/", "repo path `/` should be relative");
330 assert_repo_path_ok!("foo/bar");
331 }
332
333 #[test]
334 #[cfg(windows)]
335 fn path_to_repo_path_no_absolute() {
336 assert_err!(
337 r"c:",
338 r"repo path `c:` should be relative, not a windows prefix"
339 );
340 assert_err!(
341 r"c:\",
342 r"repo path `c:\` should be relative, not a windows prefix"
343 );
344 assert_err!(
345 r"c:temp",
346 r"repo path `c:temp` should be relative, not a windows prefix"
347 );
348 assert_err!(
349 r"\\?\UNC\a\b\c",
350 r"repo path `\\?\UNC\a\b\c` should be relative, not a windows prefix"
351 );
352 assert_err!(
353 r"\\?\c:\foo",
354 r"repo path `\\?\c:\foo` should be relative, not a windows prefix"
355 );
356 assert_err!(
357 r"\\.\COM42",
358 r"repo path `\\.\COM42` should be relative, not a windows prefix"
359 );
360 assert_err!(
361 r"\\a\b",
362 r"repo path `\\a\b` should be relative, not a windows prefix"
363 );
364 assert_err!(r"\", r"repo path `\` should be relative");
365 assert_err!(r"/", r"repo path `/` should be relative");
366 assert_err!(r"\foo", r"repo path `\foo` should be relative");
367 assert_err!(r"/foo", r"repo path `/foo` should be relative");
368 }
369 }