summaryrefslogtreecommitdiffstats
path: root/src/git/repository.rs
blob: 0ed9ddcedd44776488e38a0ea67bee37a0046be5 (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
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
use std::{
	fmt::{Debug, Formatter},
	sync::Arc,
};

use parking_lot::Mutex;

use crate::git::{CommitDiff, CommitDiffLoader, CommitDiffLoaderOptions, Config, GitError, RepositoryLoadKind};

/// A light cloneable, simple wrapper around the `git2::Repository` struct
#[derive(Clone)]
pub(crate) struct Repository {
	repository: Arc<Mutex<git2::Repository>>,
}

impl Repository {
	/// Find and open an existing repository, respecting git environment variables. This will check
	/// for and use `$GIT_DIR`, and if unset will search for a repository starting in the current
	/// directory, walking to the root.
	///
	/// # Errors
	/// Will result in an error if the repository cannot be opened.
	pub(crate) fn open_from_env() -> Result<Self, GitError> {
		let repository = git2::Repository::open_from_env().map_err(|e| {
			GitError::RepositoryLoad {
				kind: RepositoryLoadKind::Environment,
				cause: e,
			}
		})?;
		Ok(Self {
			repository: Arc::new(Mutex::new(repository)),
		})
	}

	/// Load the git configuration for the repository.
	///
	/// # Errors
	/// Will result in an error if the configuration is invalid.
	pub(crate) fn load_config(&self) -> Result<Config, GitError> {
		self.repository
			.lock()
			.config()
			.map_err(|e| GitError::ConfigLoad { cause: e })
	}

	/// Load a diff for a commit hash
	///
	/// # Errors
	/// Will result in an error if the commit cannot be loaded.
	pub(crate) fn load_commit_diff(
		&self,
		hash: &str,
		config: &CommitDiffLoaderOptions,
	) -> Result<CommitDiff, GitError> {
		let oid = self
			.repository
			.lock()
			.revparse_single(hash)
			.map_err(|e| GitError::CommitLoad { cause: e })?
			.id();
		let diff_loader_repository = Arc::clone(&self.repository);
		let loader = CommitDiffLoader::new(diff_loader_repository, config);
		// TODO this is ugly because it assumes one parent
		Ok(loader
			.load_from_hash(oid)
			.map_err(|e| GitError::CommitLoad { cause: e })?
			.remove(0))
	}
}

impl From<git2::Repository> for Repository {
	fn from(repository: git2::Repository) -> Self {
		Self {
			repository: Arc::new(Mutex::new(repository)),
		}
	}
}

impl Debug for Repository {
	fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
		f.debug_struct("Repository")
			.field("[path]", &self.repository.lock().path())
			.finish()
	}
}

#[cfg(test)]
mod tests {
	use std::{
		path::{Path, PathBuf},
		sync::Arc,
	};

	use git2::{Oid, Signature};
	use parking_lot::Mutex;

	use crate::git::{Commit, GitError, Reference, Repository, RepositoryLoadKind};

	impl Repository {
		/// Attempt to open an already-existing repository at `path`.
		///
		/// # Errors
		/// Will result in an error if the repository cannot be opened.
		pub(crate) fn open_from_path(path: &Path) -> Result<Self, GitError> {
			let repository = git2::Repository::open(path).map_err(|e| {
				GitError::RepositoryLoad {
					kind: RepositoryLoadKind::Path,
					cause: e,
				}
			})?;
			Ok(Self {
				repository: Arc::new(Mutex::new(repository)),
			})
		}

		/// Find a reference by the reference name.
		///
		/// # Errors
		/// Will result in an error if the reference cannot be found.
		pub(crate) fn find_reference(&self, reference: &str) -> Result<Reference, GitError> {
			let repo = self.repository.lock();
			let git2_reference = repo
				.find_reference(reference)
				.map_err(|e| GitError::ReferenceNotFound { cause: e })?;
			Ok(Reference::from(&git2_reference))
		}

		/// Find a commit by a reference name.
		///
		/// # Errors
		/// Will result in an error if the reference cannot be found or is not a commit.
		pub(crate) fn find_commit(&self, reference: &str) -> Result<Commit, GitError> {
			let repo = self.repository.lock();
			let git2_reference = repo
				.find_reference(reference)
				.map_err(|e| GitError::ReferenceNotFound { cause: e })?;
			Commit::try_from(&git2_reference)
		}

		pub(crate) fn repo_path(&self) -> PathBuf {
			self.repository.lock().path().to_path_buf()
		}

		pub(crate) fn head_id(&self, head_name: &str) -> Result<Oid, git2::Error> {
			let repo = self.repository.lock();
			let ref_name = format!("refs/heads/{head_name}");
			let revision = repo.revparse_single(ref_name.as_str())?;
			Ok(revision.id())
		}

		pub(crate) fn commit_id_from_ref(&self, reference: &str) -> Result<Oid, git2::Error> {
			let repo = self.repository.lock();
			let commit = repo.find_reference(reference)?.peel_to_commit()?;
			Ok(commit.id())
		}

		pub(crate) fn add_path_to_index(&self, path: &Path) -> Result<(), git2::Error> {
			let repo = self.repository.lock();
			let mut index = repo.index()?;
			index.add_path(path)
		}

		pub(crate) fn remove_path_from_index(&self, path: &Path) -> Result<(), git2::Error> {
			let repo = self.repository.lock();
			let mut index = repo.index()?;
			index.remove_path(path)
		}

		pub(crate) fn create_commit_on_index(
			&self,
			reference: &str,
			author: &Signature<'_>,
			committer: &Signature<'_>,
			message: &str,
		) -> Result<(), git2::Error> {
			let repo = self.repository.lock();
			let tree = repo.find_tree(repo.index()?.write_tree()?)?;
			let head = repo.find_reference(reference)?.peel_to_commit()?;
			_ = repo.commit(Some("HEAD"), author, committer, message, &tree, &[&head])?;
			Ok(())
		}

		pub(crate) fn repository(&self) -> Arc<Mutex<git2::Repository>> {
			Arc::clone(&self.repository)
		}
	}
}

// Paths in Windows makes these tests difficult, so disable
#[cfg(all(unix, test))]
mod unix_tests {
	use std::path::Path;

	use claims::{assert_err_eq, assert_ok};
	use git2::{ErrorClass, ErrorCode};

	use super::*;
	use crate::test_helpers::{create_commit, set_git_directory, with_temp_bare_repository, with_temp_repository};

	#[test]
	#[serial_test::serial]
	fn open_from_env() {
		_ = set_git_directory("fixtures/simple");
		assert_ok!(Repository::open_from_env());
	}

	#[test]
	#[serial_test::serial]
	fn open_from_env_error() {
		let path = set_git_directory("fixtures/does-not-exist");
		assert_err_eq!(Repository::open_from_env(), GitError::RepositoryLoad {
			kind: RepositoryLoadKind::Environment,
			cause: git2::Error::new(
				ErrorCode::NotFound,
				ErrorClass::Os,
				format!("failed to resolve path '{path}': No such file or directory")
			),
		});
	}

	#[test]
	fn open_from_path() {
		let path = Path::new(env!("CARGO_MANIFEST_DIR"))
			.join("test")
			.join("fixtures")
			.join("simple");
		assert_ok!(Repository::open_from_path(&path));
	}

	#[test]
	fn open_from_path_error() {
		let path = Path::new(env!("CARGO_MANIFEST_DIR"))
			.join("..")
			.join("..")
			.join("test")
			.join("fixtures")
			.join("does-not-exist");
		assert_err_eq!(Repository::open_from_path(&path), GitError::RepositoryLoad {
			kind: RepositoryLoadKind::Path,
			cause: git2::Error::new(
				ErrorCode::NotFound,
				ErrorClass::Os,
				format!(
					"failed to resolve path '{}': No such file or directory",