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
275
276
use crate::hash;
use crate::repo;
use git2::{self, Repository, TreeEntry};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Deserialize, Serialize, Clone, Default)]
pub enum ObjectKind {
    Blob,
    Tree,
    Commit,
    #[default]
    Unknown,
}

//Metrics contains data extracted from `git-sizer`
//we can run `git-sizer --json` on the repository`
//and use the output to populate the metrics
//it is a little bit more involved and can be done
//a later on
#[derive(Deserialize, Serialize, Clone, Default)]
pub struct Metrics {}

#[derive(Deserialize, Serialize, Clone, Default)]
pub struct Blob {
    pub filemode: i32,
    pub name: String,
    //path is the path to the file/directory relative
    //to the root tree
    //this is used to map git data to code data.
    //that hashed path is used as a key to a code entry
    pub path: String,
    //path_sha is the sha 256 of the path.
    //this is used to optimize code data lookup
    pub path_sha: String,
    pub sha: String,
}

#[derive(Deserialize, Serialize, Clone, Default)]
pub struct Tree {
    pub name: String,
    //path is the path to the file/directory relative
    //to the root tree.
    //this is used to map git data to code data.
    //that hashed path is used as a key to a code entry
    pub path: String,
    //path_sha is the sha 256 of the path.
    //this is used to optimize code data lookup
    pub path_sha: String,
    //sha the git object hash
    pub sha: String,
    pub filemode: i32,
    //objects contain a list of git objects hash
    pub objects: Vec<String>,
}

#[derive(Deserialize, Serialize, Clone, Default)]
pub struct Tag {
    pub name: String,
    pub message: String,
    //kind is equivalent to the `type`
    pub kind: ObjectKind,
    pub tagger: String,
    pub sha: String,
    //commit_sha is the sha of the commit object the tagged is applied to
    pub commit_sha: String,
}

#[derive(Deserialize, Serialize, Clone, Default)]
pub struct Commit {
    //sha the git object hash
    pub sha: String,
    pub author: String,
    pub committer: String,
    pub message: String,
    pub tree: String,
    //parents is a list of parent commits
    //only merge commits may have more than one parent
    pub parents: Vec<String>,
}

#[derive(Deserialize, Serialize, Clone, Default)]
pub struct Object {
    pub kind: ObjectKind,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub blob: Option<Blob>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub tree: Option<Tree>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub commit: Option<Commit>,
}

#[derive(Deserialize, Serialize, Clone, Default)]
pub struct Git {
    pub metrics: Metrics,
    pub objects: HashMap<String, Object>,
    //the ref_target is the ref used to traverse the git
    //repository tree.
    // (String, String) <=> (ref, oid)
    pub ref_target: (String, String),
    pub refs: HashMap<String, String>,
}

impl Object {
    fn new() -> Object {
        Object {
            ..Default::default()
        }
    }
}

pub fn new(repo: &repo::Repo) -> Result<Git, String> {
    let git_data = match extract_git_objects(repo) {
        Ok(d) => d,
        Err(err) => return Err(format!("failed to extract git objects: {err}")),
    };

    Ok(git_data)
}

pub fn extract_git_objects(repo: &repo::Repo) -> Result<Git, git2::Error> {
    let r = &repo.repo;

    let mut ref_name = "refs/heads/master";
    //Get default reference oid
    //First we check for `master` and if `master` does not exist we fallback to `main`
    let oid = match repo.repo.refname_to_id(ref_name) {
        Ok(oid) => oid,
        Err(_) => {
            ref_name = "refs/heads/main";
            repo.repo.refname_to_id(ref_name)?
        }
    };

    let mut objects: HashMap<String, Object> = HashMap::new();
    let mut obj = Object::new();
    let commit = r.find_commit(oid)?;
    obj.kind = ObjectKind::Commit;
    obj.commit = Some(Commit {
        author: commit.author().to_string(),
        sha: commit.id().to_string(),
        message: commit.message().unwrap_or("").to_string(),
        tree: commit.tree()?.id().to_string(),
        committer: commit.committer().to_string(),
        parents: {
            let mut ids = vec![];
            for id in commit.parent_ids() {
                ids.push(id.to_string());
            }
            ids
        },
    });
    //Add the commit object in the objects HashMap
    objects.insert(oid.to_string(), obj);

    //Add every git objects found during the tree object traversal
    add_tree_objects(&commit.tree()?, &mut objects, r)?;

    Ok(Git {
        objects,
        ref_target: (ref_name.to_string(), format!("{oid}")),
        ..Default::default()
    })
}

fn add_tree_objects(
    tree: &git2::Tree,
    objects: &mut HashMap<String, Object>,
    repo: &git2::Repository,
) -> Result<(), git2::Error> {
    //Create the root tree object
    {
        let mut obj = Object::new();
        obj.kind = ObjectKind::Tree;
        obj.tree = Some(Tree {
            name: "".to_string(),
            path: "".to_string(),
            path_sha: hash::new("".to_string()),
            sha: tree.id().to_string(),
            filemode: 0,
            objects: tree.iter().map(|t| t.id().to_string()).collect(),
        });

        objects.insert(tree.id().to_string(), obj);
    }

    tree.walk(git2::TreeWalkMode::PreOrder, |path, entry| {
        let mut obj = Object::new();
        if let Some(kind) = entry.kind() {
            match kind {
                //Create and add Tree objects
                git2::ObjectType::Tree => {
                    obj.kind = ObjectKind::Tree;
                    obj.tree = Some(build_tree_object(path.to_string(), entry, repo));
                }

                //Create and add Blob objects
                git2::ObjectType::Blob => {
                    let name = entry.name().unwrap_or("").to_string();
                    let path = get_relative_path(path.to_string(), name.clone());
                    obj.kind = ObjectKind::Blob;
                    obj.blob = Some(Blob {
                        name,
                        path: path.clone(),
                        path_sha: hash::new(path),
                        sha: entry.id().to_string(),
                        filemode: entry.filemode(),
                    });
                }
                _ => (),
            }
        };

        objects.insert(entry.id().to_string(), obj);
        git2::TreeWalkResult::Ok
    })?;

    Ok(())
}

fn build_tree_object(path: String, entry: &TreeEntry, repo: &Repository) -> Tree {
    let name = entry.name().unwrap_or("").to_string();
    let path = get_relative_path(path, name.clone());
    Tree {
        name,
        sha: entry.id().to_string(),
        path: path.clone(),
        path_sha: hash::new(path),
        filemode: entry.filemode(),
        objects: {
            let mut objs = vec![];
            let t = repo.find_tree(entry.id()).unwrap();

            //We walk down the tree to find every blob or tree objects and add them
            //to our list of objects
            t.walk(git2::TreeWalkMode::PreOrder, |_, entry| {
                objs.push(entry.id().to_string());
                if Some(git2::ObjectType::Tree) == entry.kind() {
                    return git2::TreeWalkResult::Skip;
                }
                git2::TreeWalkResult::Ok
            })
            .unwrap();
            objs
        },
    }
}

pub fn get_relative_path(path: String, file_name: String) -> String {
    format!("{path}{file_name}")
}

#[cfg(test)]
mod tests {
    use crate::extractor::git;

    #[test]
    fn test_get_relative_path() {
        assert_eq!(
            git::get_relative_path("src/".to_string(), "test.rs".to_string()),
            "src/test.rs"
        );
        assert_eq!(
            git::get_relative_path("src/".to_string(), "".to_string()),
            "src/"
        );

        assert_eq!(
            git::get_relative_path("".to_string(), "test".to_string()),
            "test"
        );
    }
}