Echo Writes Code

git.rs

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
use crate::errors::{ Result, Error };

use serde::{ Serialize };

use std::ffi::{ OsStr };
use std::fs;
use std::path::{ PathBuf };

pub use git2::{ Repository, Oid, Tree };

pub struct Git {
	path: PathBuf,
}

impl Git {
	pub fn open(path: &std::path::Path) -> Result<Git> {
		match fs::read_dir(path) {
			Ok(_) => Ok(Git { path: path.to_path_buf() }),
			Err(e) => Err(Error::InvalidGitRoot(e)),
		}
	}

	pub fn find_repository_by_name(&self, name: &str) -> Result<Repository> {
		for repo in self.repositories()? {
			let repo = repo?;

			if repo.name()? == name {
				return Ok(repo);
			}
		}

		Err(Error::RepositoryNotFound(name.to_string()))
	}

	pub fn repositories(&self) -> Result<RepositoryIterator> {
		Ok(RepositoryIterator {
			directory_iterator: fs::read_dir(&self.path)?,
		})
	}
}

pub struct RepositoryIterator {
	directory_iterator: fs::ReadDir,
}

impl Iterator for RepositoryIterator {
	type Item = Result<Repository>;

	fn next(&mut self) -> Option<Result<Repository>> {
		let repository = loop {
			let path = 
				match self.directory_iterator.next()? {
					Ok(directory_entry) => directory_entry.path(),
					Err(e) => return Some(Err(e.into())),
				};

			// Repositories have to be directories
			if !path.is_dir() {
				continue;
			}

			// We only consider bare repositories, i.e. `foo.git`, not `foo/.git`
			if path.extension() != Some(OsStr::new("git")) {
				continue;
			}

			break Repository::open(path);
		};

		match repository {
			Ok(repository) => Some(Ok(repository)),
			Err(e) => Some(Err(e.into())),
		}
	}
}

pub trait RepositoryExtensions {
	fn name(&self) -> Result<String>;

	fn list_tree_by_commit_name(&self, commit_name: &str) -> Result<Vec<GitObjectMetadata>>;

	fn list_tree_by_id(&self, tree_id: Oid) -> Result<Vec<GitObjectMetadata>>;

	fn list_tree(&self, tree: &Tree) -> Result<Vec<GitObjectMetadata>>;

	fn get_blob_text_by_id(&self, blob_id: Oid) -> Result<String>;
}

impl RepositoryExtensions for Repository {
	fn name(&self) -> Result<String> {
		let raw_name =
			if self.is_bare() {
				let Some(file_stem) = self.path().file_stem() else {
					return Err(Error::CannotDetermineRepositoryName(self.path().to_path_buf()));
				};

				file_stem
			} else {
				let Some(parent) = self.path().parent() else {
					return Err(Error::CannotDetermineRepositoryName(self.path().to_path_buf()));
				};

				let Some(file_name) = parent.file_name() else {
					return Err(Error::CannotDetermineRepositoryName(self.path().to_path_buf()));
				};

				file_name
			};

		let Some(name) = raw_name.to_str() else {
			return Err(Error::CannotDetermineRepositoryName(self.path().to_path_buf()));
		};

		Ok(name.to_string())
	}

	fn list_tree_by_commit_name(&self, commit_name: &str) -> Result<Vec<GitObjectMetadata>> {
		let commit_oid = self.refname_to_id(commit_name)?;
		let commit = self.find_commit(commit_oid)?;
		let tree = commit.tree()?;
		self.list_tree(&tree)
	}

	fn list_tree_by_id(&self, id: Oid) -> Result<Vec<GitObjectMetadata>> {
		let tree = self.find_tree(id)?;
		self.list_tree(&tree)
	}

	fn list_tree(&self, tree: &Tree) -> Result<Vec<GitObjectMetadata>> {
		let repository_name = self.name()?;

		let list = tree.iter().map(|entry| {
			let name = entry
				.name()
				.ok_or(Error::UnnamedTreeEntry(entry.id()))?
				.to_string();

			let kind = entry
				.kind()
				.ok_or(Error::UntypedTreeEntry(entry.id()))?
				.try_into()?;

			// It would be easy to do this with a fmt::Display impl, but it's really important that these
			// URLs don't change, so we do it explicitly to avoid surprises
			let link = match kind {
				GitObjectKind::Blob => format!("/repository/{}/blob/{}", repository_name, entry.id()),
				GitObjectKind::Commit => format!("/repository/{}/commit/{}", repository_name, entry.id()),
				GitObjectKind::Tag => format!("/repository/{}/tag/{}", repository_name, entry.id()),
				GitObjectKind::Tree => format!("/repository/{}/tree/{}", repository_name, entry.id()),
			};

			Ok(GitObjectMetadata {
				link,
				name,
				kind,
			})
		}).collect::<Result<_>>()?;

		Ok(list)
	}

	fn get_blob_text_by_id(&self, blob_id: Oid) -> Result<String> {
		let blob = self.find_blob(blob_id)?;
		let content = blob.content();
		let text = String::from_utf8(content.to_vec())?;
		Ok(text)
	}
}

#[derive(Clone, Serialize)]
pub struct GitObjectMetadata {
	pub link: String,
	pub name: String,
	pub kind: GitObjectKind,
}

#[derive(Clone, Eq, PartialEq, Serialize)]
pub enum GitObjectKind {
	Blob,
	Commit,
	Tag,
	Tree,
}

impl TryFrom<git2::ObjectType> for GitObjectKind {
	type Error = crate::errors::Error;

	fn try_from(t: git2::ObjectType) -> Result<GitObjectKind> {
		match t {
			git2::ObjectType::Blob => Ok(GitObjectKind::Blob),
			git2::ObjectType::Commit => Ok(GitObjectKind::Commit),
			git2::ObjectType::Tag => Ok(GitObjectKind::Tag),
			git2::ObjectType::Tree => Ok(GitObjectKind::Tree),
			_ => Err(Error::UnexpectedObjectType(t)),
		}
	}
}