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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
// Copyright © 2019-2020 The Radicle Foundation <hello@radicle.foundation>
//
// This file is part of radicle-link, distributed under the GPLv3 with Radicle
// Linking Exception. For full terms see the included LICENSE file.

use std::{borrow::Cow, collections::BTreeMap, iter::FromIterator};

/// A simplified representation of a git tree, intended mainly to be created
/// from literals.
///
/// # Example
///
/// ```
/// use radicle_git_ext::tree::{Tree, blob};
///
/// let my_tree = vec![
///     ("README", blob(b"awe")),
///     ("src", vec![("main.rs", blob(b"fn main() {}"))].into_iter().collect()),
/// ]
/// .into_iter()
/// .collect::<Tree>();
///
/// assert_eq!(
///     format!("{:?}", my_tree),
///     "Tree(\
///         {\
///             \"README\": Blob(\
///                 [\
///                     97, \
///                     119, \
///                     101\
///                 ]\
///             ), \
///             \"src\": Tree(\
///                 Tree(\
///                     {\
///                         \"main.rs\": Blob(\
///                             [\
///                                 102, \
///                                 110, \
///                                 32, \
///                                 109, \
///                                 97, \
///                                 105, \
///                                 110, \
///                                 40, \
///                                 41, \
///                                 32, \
///                                 123, \
///                                 125\
///                             ]\
///                         )\
///                     }\
///                 )\
///             )\
///         }\
///     )"
/// )
/// ```
#[derive(Clone, Debug)]
pub struct Tree<'a>(BTreeMap<Cow<'a, str>, Node<'a>>);

impl Tree<'_> {
    pub fn write(&self, repo: &git2::Repository) -> Result<git2::Oid, git2::Error> {
        use Node::*;

        let mut builder = repo.treebuilder(None)?;
        for (name, node) in &self.0 {
            match node {
                Blob(data) => {
                    let oid = repo.blob(data)?;
                    builder.insert(name.as_ref(), oid, git2::FileMode::Blob.into())?;
                }
                Tree(sub) => {
                    let oid = sub.write(repo)?;
                    builder.insert(name.as_ref(), oid, git2::FileMode::Tree.into())?;
                }
            }
        }

        builder.write()
    }
}

impl<'a> From<BTreeMap<Cow<'a, str>, Node<'a>>> for Tree<'a> {
    fn from(map: BTreeMap<Cow<'a, str>, Node<'a>>) -> Self {
        Self(map)
    }
}

impl<'a, K, N> FromIterator<(K, N)> for Tree<'a>
where
    K: Into<Cow<'a, str>>,
    N: Into<Node<'a>>,
{
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = (K, N)>,
    {
        Self(
            iter.into_iter()
                .map(|(k, v)| (k.into(), v.into()))
                .collect(),
        )
    }
}

#[derive(Clone, Debug)]
pub enum Node<'a> {
    Blob(Cow<'a, [u8]>),
    Tree(Tree<'a>),
}

pub fn blob(slice: &[u8]) -> Node {
    Node::from(slice)
}

impl<'a> From<&'a [u8]> for Node<'a> {
    fn from(slice: &'a [u8]) -> Self {
        Self::from(Cow::Borrowed(slice))
    }
}

impl<'a> From<Cow<'a, [u8]>> for Node<'a> {
    fn from(bytes: Cow<'a, [u8]>) -> Self {
        Self::Blob(bytes)
    }
}

impl<'a> From<Tree<'a>> for Node<'a> {
    fn from(tree: Tree<'a>) -> Self {
        Self::Tree(tree)
    }
}

impl<'a, K, N> FromIterator<(K, N)> for Node<'a>
where
    K: Into<Cow<'a, str>>,
    N: Into<Node<'a>>,
{
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = (K, N)>,
    {
        Self::Tree(iter.into_iter().collect())
    }
}