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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// This file is part of radicle-surf
// <https://github.com/radicle-dev/radicle-surf>
//
// Copyright (C) 2019-2020 The Radicle Team <dev@radicle.xyz>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 or
// later as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! Represents git object type 'tree', i.e. like directory entries in Unix.
//! See git [doc](https://git-scm.com/book/en/v2/Git-Internals-Git-Objects) for more details.

use std::cmp::Ordering;

use radicle_git_ext::Oid;
#[cfg(feature = "serde")]
use serde::{
    ser::{SerializeStruct as _, Serializer},
    Serialize,
};
use url::Url;

use crate::{fs, Commit};

/// Represents a tree object as in git. It is essentially the content of
/// one directory. Note that multiple directories can have the same content,
/// i.e. have the same tree object. Hence this struct does not embed its path.
#[derive(Clone, Debug)]
pub struct Tree {
    /// The object id of this tree.
    id: Oid,
    /// The first descendant entries for this tree.
    entries: Vec<Entry>,
    /// The commit object that created this tree object.
    commit: Commit,
}

impl Tree {
    /// Creates a new tree, ensuring the `entries` are sorted.
    pub(crate) fn new(id: Oid, mut entries: Vec<Entry>, commit: Commit) -> Self {
        entries.sort();
        Self {
            id,
            entries,
            commit,
        }
    }

    pub fn object_id(&self) -> Oid {
        self.id
    }

    /// Returns the commit that created this tree.
    pub fn commit(&self) -> &Commit {
        &self.commit
    }

    /// Returns the entries of the tree.
    pub fn entries(&self) -> &Vec<Entry> {
        &self.entries
    }
}

#[cfg(feature = "serde")]
impl Serialize for Tree {
    /// Sample output:
    /// (for `<entry_1>` and `<entry_2>` sample output, see [`Entry`])
    /// ```
    /// {
    ///   "entries": [
    ///     { <entry_1> },
    ///     { <entry_2> },
    ///   ],
    ///   "lastCommit": {
    ///     "author": {
    ///       "email": "foobar@gmail.com",
    ///       "name": "Foo Bar"
    ///     },
    ///     "committer": {
    ///       "email": "noreply@github.com",
    ///       "name": "GitHub"
    ///     },
    ///     "committerTime": 1582198877,
    ///     "description": "A sample commit.",
    ///     "sha1": "b57846bbc8ced6587bf8329fc4bce970eb7b757e",
    ///     "summary": "Add a new sample"
    ///   },
    ///   "oid": "dd52e9f8dfe1d8b374b2a118c25235349a743dd2"
    /// }
    /// ```
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        const FIELDS: usize = 4;
        let mut state = serializer.serialize_struct("Tree", FIELDS)?;
        state.serialize_field("oid", &self.id)?;
        state.serialize_field("entries", &self.entries)?;
        state.serialize_field("lastCommit", &self.commit)?;
        state.end()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EntryKind {
    Tree(Oid),
    Blob(Oid),
    Submodule { id: Oid, url: Option<Url> },
}

impl PartialOrd for EntryKind {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for EntryKind {
    fn cmp(&self, other: &Self) -> Ordering {
        match (self, other) {
            (EntryKind::Submodule { .. }, EntryKind::Submodule { .. }) => Ordering::Equal,
            (EntryKind::Submodule { .. }, EntryKind::Tree(_)) => Ordering::Equal,
            (EntryKind::Tree(_), EntryKind::Submodule { .. }) => Ordering::Equal,
            (EntryKind::Tree(_), EntryKind::Tree(_)) => Ordering::Equal,
            (EntryKind::Tree(_), EntryKind::Blob(_)) => Ordering::Less,
            (EntryKind::Blob(_), EntryKind::Tree(_)) => Ordering::Greater,
            (EntryKind::Submodule { .. }, EntryKind::Blob(_)) => Ordering::Less,
            (EntryKind::Blob(_), EntryKind::Submodule { .. }) => Ordering::Greater,
            (EntryKind::Blob(_), EntryKind::Blob(_)) => Ordering::Equal,
        }
    }
}

/// An entry that can be found in a tree.
///
/// # Ordering
///
/// The ordering of a [`Entry`] is first by its `entry` where
/// [`EntryKind::Tree`]s come before [`EntryKind::Blob`]. If both kinds
/// are equal then they are next compared by the lexicographical ordering
/// of their `name`s.
#[derive(Clone, Debug)]
pub struct Entry {
    name: String,
    entry: EntryKind,

    /// The commit object that created this entry object.
    commit: Commit,
}

impl Entry {
    pub(crate) fn new(name: String, entry: EntryKind, commit: Commit) -> Self {
        Self {
            name,
            entry,
            commit,
        }
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn entry(&self) -> &EntryKind {
        &self.entry
    }

    pub fn is_tree(&self) -> bool {
        matches!(self.entry, EntryKind::Tree(_))
    }

    pub fn commit(&self) -> &Commit {
        &self.commit
    }

    pub fn object_id(&self) -> Oid {
        match self.entry {
            EntryKind::Blob(id) => id,
            EntryKind::Tree(id) => id,
            EntryKind::Submodule { id, .. } => id,
        }
    }
}

// To support `sort`.
impl Ord for Entry {
    fn cmp(&self, other: &Self) -> Ordering {
        self.entry
            .cmp(&other.entry)
            .then(self.name.cmp(&other.name))
    }
}

impl PartialOrd for Entry {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for Entry {
    fn eq(&self, other: &Self) -> bool {
        self.entry == other.entry && self.name == other.name
    }
}

impl Eq for Entry {}

impl From<fs::Entry> for EntryKind {
    fn from(entry: fs::Entry) -> Self {
        match entry {
            fs::Entry::File(f) => EntryKind::Blob(f.id()),
            fs::Entry::Directory(d) => EntryKind::Tree(d.id()),
            fs::Entry::Submodule(u) => EntryKind::Submodule {
                id: u.id(),
                url: u.url().clone(),
            },
        }
    }
}

#[cfg(feature = "serde")]
impl Serialize for Entry {
    /// Sample output:
    /// ```json
    ///  {
    ///     "kind": "blob",
    ///     "lastCommit": {
    ///       "author": {
    ///         "email": "foobar@gmail.com",
    ///         "name": "Foo Bar"
    ///       },
    ///       "committer": {
    ///         "email": "noreply@github.com",
    ///         "name": "GitHub"
    ///       },
    ///       "committerTime": 1578309972,
    ///       "description": "This is a sample file",
    ///       "sha1": "2873745c8f6ffb45c990eb23b491d4b4b6182f95",
    ///       "summary": "Add a new sample"
    ///     },
    ///     "name": "Sample.rs",
    ///     "oid": "6d6240123a8d8ea8a8376610168a0a4bcb96afd0"
    ///   },
    /// ```
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        const FIELDS: usize = 5;
        let mut state = serializer.serialize_struct("TreeEntry", FIELDS)?;
        state.serialize_field("name", &self.name)?;
        state.serialize_field(
            "kind",
            match self.entry {
                EntryKind::Blob(_) => "blob",
                EntryKind::Tree(_) => "tree",
                EntryKind::Submodule { .. } => "submodule",
            },
        )?;
        if let EntryKind::Submodule { url: Some(url), .. } = &self.entry {
            state.serialize_field("url", url)?;
        };
        state.serialize_field("oid", &self.object_id())?;
        state.serialize_field("lastCommit", &self.commit)?;
        state.end()
    }
}