aboutsummaryrefslogtreecommitdiff
path: root/src/git/tree.rs
blob: 5343a57c2463ff79ce0f9d9aa0964f3f5ab0583f (plain)
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
//! Tree handling utilities
//!
//! The way that libgit2 handles trees is super low-level and overkill
//! for what we need.  In this module we knock it down a notch or two.
//!
//! This code takes a tree returned by
//! `crate::git::repo::Repo::get_tree()`, and transforms it into a
//! `TreeData` type that the template engine can render.

use crate::templ_data::repo::{CommitData, FileData, TreeData};
use git2::{self, ObjectType, TreeWalkMode};
use std::collections::BTreeMap;

/// A cache of a repository tree
#[derive(Default, Debug, Clone)]
pub(crate) struct Tree {
    inner: BTreeMap<String, TreeNode>,
}

impl Tree {
    /// Insert a node into a subtree with it's full path
    fn insert_to_subtree(&mut self, mut path: Vec<String>, name: String, node: TreeNode) {
        // If we are given a path, resolve it first
        let curr = if path.len() > 0 {
            let rest = path.split_off(1);
            let mut curr = self.inner.get_mut(&path[0]).unwrap();

            for dir in rest {
                match curr {
                    TreeNode::Dir(ref mut d) => {
                        curr = d.children.inner.get_mut(&dir).unwrap();
                    }
                    _ => panic!("Not a tree!"),
                }
            }

            match curr {
                TreeNode::Dir(ref mut d) => &mut d.children,
                TreeNode::File(_) => panic!("Not a tree!"),
            }
        } else {
            // If no path was given, we assume the root is meant
            self
        };

        curr.inner.insert(name, node);
    }

    /// Walk through the tree and only return filenode objects
    pub(crate) fn flatten(&self) -> Vec<FileNode> {
        self.inner.values().fold(vec![], |mut vec, node| {
            match node {
                TreeNode::File(f) => vec.push(f.clone()),
                TreeNode::Dir(d) => vec.append(&mut d.children.flatten()),
            }

            vec
        })
    }

    /// Get all the commits that touch a file
    pub(crate) fn grab_path_history(&self, mut path: String) -> String {
        let mut path: Vec<String> = path
            .split("/")
            .filter_map(|seg| match seg {
                "" => None,
                val => Some(val.into()),
            })
            .collect();

        let leaf = if path.len() > 0 {
            let rest = path.split_off(1);
            let mut curr = self.inner.get(&path[0]).unwrap();

            for dir in rest {
                match curr {
                    TreeNode::Dir(d) => curr = d.children.inner.get(&dir).unwrap(),
                    TreeNode::File(_) => break, // we reached the leaf
                }
            }

            curr
        } else {
            panic!("No valid path!");
        };

        match leaf {
            TreeNode::File(f) => f.id.clone(),
            _ => panic!("Not a leaf!"),
        }
    }
}

#[derive(Clone, Debug)]
pub(crate) enum TreeNode {
    File(FileNode),
    Dir(DirNode),
}

impl TreeNode {
    fn name(&self) -> String {
        match self {
            Self::File(f) => f.name.clone(),
            Self::Dir(d) => d.name.clone(),
        }
    }
}

#[derive(Clone, Debug)]
pub(crate) struct FileNode {
    pub id: String,
    pub path: Vec<String>,
    pub name: String,
}

#[derive(Clone, Debug)]
pub(crate) struct DirNode {
    pub path: Vec<String>,
    pub name: String,
    pub children: Tree,
}

impl DirNode {
    fn append(&mut self, node: TreeNode) {
        self.children.inner.insert(node.name(), node);
    }
}

/// Take a series of path-segments and render a tree at that location
pub(crate) fn parse_tree(tree: git2::Tree, repo: &git2::Repository) -> Tree {
    let mut root = Tree::default();

    tree.walk(TreeWalkMode::PreOrder, |path, entry| {
        let path: Vec<String> = path
            .split("/")
            .filter_map(|seg| match seg {
                "" => None,
                val => Some(val.into()),
            })
            .collect();
        let name = entry.name().unwrap().to_string();

        match entry.kind() {
            // For every tree in the tree we create a new TreeNode with the path we know about
            Some(ObjectType::Tree) => {
                root.insert_to_subtree(
                    path.clone(),
                    name.clone(),
                    TreeNode::Dir(DirNode {
                        path,
                        name,
                        children: Tree::default(),
                    }),
                );
            }
            // If we encounter a blob, this is a file that we can simply insert into the tree
            Some(ObjectType::Blob) => {
                root.insert_to_subtree(
                    path.clone(),
                    name.clone(),
                    TreeNode::File(FileNode {
                        id: format!("{}", entry.id()),
                        path,
                        name,
                    }),
                );
            }
            _ => {}
        }

        0
    })
    .unwrap();

    root
}