File: tagforeach.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 (69 lines) | stat: -rw-r--r-- 1,857 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
//! git_tag_foreach support
//! see original: https://libgit2.org/libgit2/#HEAD/group/tag/git_tag_foreach

use crate::{panic, raw, util::Binding, Oid};
use libc::{c_char, c_int};
use raw::git_oid;
use std::ffi::{c_void, CStr};

/// boxed callback type
pub(crate) type TagForeachCB<'a> = Box<dyn FnMut(Oid, &[u8]) -> bool + 'a>;

/// helper type to be able to pass callback to payload
pub(crate) struct TagForeachData<'a> {
    /// callback
    pub(crate) cb: TagForeachCB<'a>,
}

/// c callback forwarding to rust callback inside `TagForeachData`
/// see original: https://libgit2.org/libgit2/#HEAD/group/callback/git_tag_foreach_cb
pub(crate) extern "C" fn tag_foreach_cb(
    name: *const c_char,
    oid: *mut git_oid,
    payload: *mut c_void,
) -> c_int {
    panic::wrap(|| unsafe {
        let id: Oid = Binding::from_raw(oid as *const _);

        let name = CStr::from_ptr(name);
        let name = name.to_bytes();

        let payload = &mut *(payload as *mut TagForeachData<'_>);
        let cb = &mut payload.cb;

        let res = cb(id, name);

        if res {
            0
        } else {
            -1
        }
    })
    .unwrap_or(-1)
}

#[cfg(test)]
mod tests {

    #[test]
    fn smoke() {
        let (_td, repo) = crate::test::repo_init();
        let head = repo.head().unwrap();
        let id = head.target().unwrap();
        assert!(repo.find_tag(id).is_err());

        let obj = repo.find_object(id, None).unwrap();
        let sig = repo.signature().unwrap();
        let tag_id = repo.tag("foo", &obj, &sig, "msg", false).unwrap();

        let mut tags = Vec::new();
        repo.tag_foreach(|id, name| {
            tags.push((id, String::from_utf8(name.into()).unwrap()));
            true
        })
        .unwrap();

        assert_eq!(tags[0].0, tag_id);
        assert_eq!(tags[0].1, "refs/tags/foo");
    }
}