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
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use crate::errors::{ Result, Error };

use serde::{ Serialize };

use std::ffi::{ OsStr };
use std::fmt;
use std::fs;
use std::path::{ Path, PathBuf };

pub(crate) use git2::{ Commit, Repository, ObjectType, Oid, Sort, Tree };

#[derive(Eq, PartialEq)]
pub(crate) enum CommitReference {
	Branch(String),
	Direct(Oid),
	Head,
	Tag(String),
}

impl CommitReference {
	pub(crate) fn slug(&self) -> String {
		use CommitReference::*;

		match *self {
			Branch(ref branch_name) => format!("branch/{}", branch_name),
			Direct(commit_id) => format!("commit/{}", commit_id),
			Head => "head".to_string(),
			Tag(ref tag_name) => format!("tag/{}", tag_name),
		}
	}
}

impl fmt::Display for CommitReference {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		use CommitReference::*;

		match *self {
			Branch(ref branch_name) => write!(f, "{}", branch_name),
			Direct(id) => write!(f, "{}", id),
			Head => write!(f, "HEAD"),
			Tag(ref tag_name) => write!(f, "{}", tag_name),
		}
	}
}

pub(crate) struct Git {
	path: PathBuf,
}

impl Git {
	pub(crate) 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(crate) fn find_repository_by_name(&self, name: &str) -> Result<Repository> {
		// Scanning the repository iterator, rather than just concatenating the name onto the git.root,
		// is important because the iterator implements filtering and hiding.
		for repo in self.repositories()? {
			let repo = repo?;

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

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

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

pub(crate) 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;
			}

			// We can hide a repository if it has a file called `gitten-hide-this-repository` at the root.
			//
			// THIS IS NOT A SECURITY FEATURE. DO NOT RELY ON THIS TO HIDE ENCRYPTION KEYS, TRADE SECRETS,
			// PII, OR OTHER SENSITIVE INFORMATION.
			let hide_path = path.join("gitten-hide-this-repository");
			if hide_path.is_file() {
				tracing::debug!("Hiding repository {}", path.display());
				continue;
			}

			break Repository::open(path);
		};

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

pub(crate) trait RepositoryExtensions {
	fn find_blob_name_by_path(&self, commit_reference: &CommitReference, blob_path: &str) -> Result<String>;

	fn find_blob_text_by_path(&self, commit_reference: &CommitReference, path: &str) -> Result<String>;

	fn find_tree_name_by_path(&self, commit_reference: &CommitReference, tree_path: &str) -> Result<String>;

	fn list_branches(&self) -> Result<Vec<String>>;

	fn list_commit_history(&self, from_head: &CommitReference, page_size: usize, page: usize) -> Result<Vec<Commit>>;

	fn list_tags(&self) -> Result<Vec<String>>;

	fn list_tree_by_commit(&self, commit_reference: &CommitReference) -> Result<Vec<GitObjectMetadata>>;

	fn list_tree_by_path(&self, commit_reference: &CommitReference, tree_path: &str) -> Result<Vec<GitObjectMetadata>>;

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

	fn name(&self) -> Result<String>;

	fn resolve_commit_reference(&self, commit: &CommitReference) -> Result<Oid>;
}

impl RepositoryExtensions for Repository {
	fn find_blob_name_by_path(&self, commit_reference: &CommitReference, blob_path: &str) -> Result<String> {
		let commit_oid = self.resolve_commit_reference(commit_reference)?;
		let commit = self.find_commit(commit_oid)?;
		let commit_tree = commit.tree()?;
		let entry = commit_tree.get_path(Path::new(blob_path))?;

		match entry.kind() {
			Some(ObjectType::Blob) => entry.name().map(|s| s.to_string()).ok_or(Error::UnnamedTreeEntry(entry.id())),
			Some(k) => Err(Error::UnexpectedObjectType(k)),
			None => Err(Error::ObjectNotFoundByPath(blob_path.to_string())),
		}
	}

	fn find_blob_text_by_path(&self, commit_reference: &CommitReference, blob_path: &str) -> Result<String> {
		let commit_oid = self.resolve_commit_reference(commit_reference)?;
		let commit = self.find_commit(commit_oid)?;
		let commit_tree = commit.tree()?;
		let entry = commit_tree.get_path(Path::new(blob_path))?;
		let object = entry.to_object(self)?;

		if let Some(blob) = object.as_blob() {
			let content = blob.content();
			let text = String::from_utf8(content.to_vec())
				.map_err(Error::NonUtf8Blob)?;
			Ok(text)
		} else if let Some(kind) = object.kind() {
			Err(Error::UnexpectedObjectType(kind))
		} else {
			Err(Error::UntypedTreeEntry(entry.id()))
		}
	}

	fn find_tree_name_by_path(&self, commit_reference: &CommitReference, tree_path: &str) -> Result<String> {
		let commit_oid = self.resolve_commit_reference(commit_reference)?;
		let commit = self.find_commit(commit_oid)?;
		let commit_tree = commit.tree()?;
		let entry = commit_tree.get_path(Path::new(tree_path))?;

		match entry.kind() {
			Some(ObjectType::Tree) => entry.name().map(|s| s.to_string()).ok_or(Error::UnnamedTreeEntry(entry.id())),
			Some(k) => Err(Error::UnexpectedObjectType(k)),
			None => Err(Error::ObjectNotFoundByPath(tree_path.to_string())),
		}
	}

	fn list_branches(&self) -> Result<Vec<String>> {
		let branches = self.references()?
			.map(|reference| {
				let reference = reference?;
				Ok(reference)
			})
			.collect::<Result<Vec<_>>>()?
			.into_iter()
			.filter(|reference| reference.is_branch())
			.map(|branch| {
				// shorthand because we don't want the `refs/heads/` part of the name
				let branch_name = branch.shorthand_bytes();
				let branch_name = String::from_utf8(branch_name.to_vec())
					.map_err(Error::NonUtf8BranchName)?;

				Ok(branch_name)
			})
			.collect::<Result<_>>()?;

		Ok(branches)
	}

	fn list_commit_history(&self, from_head: &CommitReference, page_size: usize, page: usize) -> Result<Vec<Commit>> {
		let commit_id = self.resolve_commit_reference(from_head)?;
		let mut revwalk = self.revwalk()?;

		revwalk.set_sorting(Sort::TOPOLOGICAL | Sort::TIME)?;
		revwalk.push(commit_id)?;

		let history = revwalk
			.skip(page_size * page)
			.take(page_size)
			.map(|commit_id| {
				let commit_id = commit_id?;
				let commit = self.find_commit(commit_id)?;
				Ok(commit)
			})
			.collect::<Result<_>>()?;

		Ok(history)
	}

	fn list_tags(&self) -> Result<Vec<String>> {
		let tags = self.references()?
			.map(|reference| {
				let reference = reference?;
				Ok(reference)
			})
			.collect::<Result<Vec<_>>>()?
			.into_iter()
			.filter(|reference| reference.is_tag())
			.map(|tag| {
				let tag_name = tag.shorthand_bytes();
				let tag_name = String::from_utf8(tag_name.to_vec())
					.map_err(Error::NonUtf8TagName)?;

				Ok(tag_name)
			})
			.collect::<Result<_>>()?;

		Ok(tags)
	}

	fn list_tree_by_commit(&self, commit_reference: &CommitReference) -> Result<Vec<GitObjectMetadata>> {
		let commit_oid = self.resolve_commit_reference(commit_reference)?;
		let commit = self.find_commit(commit_oid)?;
		let commit_tree = commit.tree()?;
		self.list_tree(commit_reference, &commit_tree, "")
	}

	fn list_tree_by_path(&self, commit_reference: &CommitReference, tree_path: &str) -> Result<Vec<GitObjectMetadata>> {
		let commit_oid = self.resolve_commit_reference(commit_reference)?;
		let commit = self.find_commit(commit_oid)?;
		let commit_tree = commit.tree()?;
		let entry = commit_tree.get_path(Path::new(tree_path))?;
		let object = entry.to_object(self)?;

		if let Some(tree) = object.as_tree() {
			self.list_tree(commit_reference, tree, tree_path)
		} else if let Some(kind) = object.kind() {
			Err(Error::UnexpectedObjectType(kind))
		} else {
			Err(Error::UntypedTreeEntry(entry.id()))
		}
	}

	fn list_tree(&self, commit: &CommitReference, tree: &Tree, root: &str) -> 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()?;

			let object_path = if root.is_empty() {
				name.clone()
			} else {
				format!("{}/{}", root, name)
			};

			let commit_path = format!("/repository/{}/{}", repository_name, commit.slug());

			let link = match kind {
				GitObjectKind::Blob => format!("{}/blob/{}", commit_path, object_path),
				GitObjectKind::Tree => format!("{}/tree/{}", commit_path, object_path),
				_ => return Err(Error::UnexpectedObjectType(kind.into())),
			};

			Ok(GitObjectMetadata {
				repository_name: repository_name.clone(),
				id: entry.id().to_string(),
				link,
				path: object_path,
				name,
				kind,
			})
		}).collect::<Result<_>>()?;

		Ok(list)
	}

	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 resolve_commit_reference(&self, commit_reference: &CommitReference) -> Result<Oid> {
		let id = match commit_reference {
			CommitReference::Branch(branch_name) => self.refname_to_id(&format!("refs/heads/{}", branch_name))?,
			CommitReference::Direct(id) => *id,
			CommitReference::Head => self.refname_to_id("HEAD")?,
			CommitReference::Tag(tag_name) => {
				let id = self.refname_to_id(&format!("refs/tags/{}", tag_name))?;

				// If the tag is a full tag object, we need to peel it to find whatever it's referring to
				// (hopefully a commit)
				if let Ok(full_tag) = self.find_tag(id) {
					full_tag.peel()?.id()
				} else {
					id
				}
			},
		};
		Ok(id)
	}
}

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

impl fmt::Display for GitObjectMetadata {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		write!(f, "{} {}", self.kind, self.name)
	}
}

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

impl TryFrom<ObjectType> for GitObjectKind {
	type Error = Error;

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

impl From<GitObjectKind> for ObjectType {
	fn from(k: GitObjectKind) -> ObjectType {
		match k {
			GitObjectKind::Blob => ObjectType::Blob,
			GitObjectKind::Commit => ObjectType::Commit,
			GitObjectKind::Tag => ObjectType::Tag,
			GitObjectKind::Tree => ObjectType::Tree,
		}
	}
}

impl fmt::Display for GitObjectKind {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		use GitObjectKind::*;

		match *self {
			Blob => write!(f, "blob"),
			Commit => write!(f, "commit"),
			Tag => write!(f, "tag"),
			Tree => write!(f, "tree"),
		}
	}
}