summaryrefslogtreecommitdiffstats
path: root/asyncgit/src/sync/branch/merge_commit.rs
blob: fcabf915cd25a5beb1f5a44ed234d706ab178172 (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
//! merging from upstream

use super::BranchType;
use crate::{
	error::{Error, Result},
	sync::{merge_msg, utils, CommitId},
};
use git2::Commit;
use scopetime::scope_time;

/// merge upstream using a merge commit if we did not create conflicts.
/// if we did not create conflicts we create a merge commit and return the commit id.
/// Otherwise we return `None`
pub fn merge_upstream_commit(
	repo_path: &str,
	branch_name: &str,
) -> Result<Option<CommitId>> {
	scope_time!("merge_upstream_commit");

	let repo = utils::repo(repo_path)?;

	let branch = repo.find_branch(branch_name, BranchType::Local)?;
	let upstream = branch.upstream()?;

	let upstream_commit = upstream.get().peel_to_commit()?;

	let annotated_upstream = repo
		.reference_to_annotated_commit(&upstream.into_reference())?;

	let (analysis, pref) =
		repo.merge_analysis(&[&annotated_upstream])?;

	if !analysis.is_normal() {
		return Err(Error::Generic(
			"normal merge not possible".into(),
		));
	}

	if analysis.is_fast_forward() && pref.is_fastforward_only() {
		return Err(Error::Generic(
			"ff merge would be possible".into(),
		));
	}

	//TODO: support merge on unborn?
	if analysis.is_unborn() {
		return Err(Error::Generic("head is unborn".into()));
	}

	repo.merge(&[&annotated_upstream], None, None)?;

	if !repo.index()?.has_conflicts() {
		let msg = merge_msg(repo_path)?;

		let commit_id =
			commit_merge_with_head(&repo, &[upstream_commit], &msg)?;

		return Ok(Some(commit_id));
	}

	Ok(None)
}

pub(crate) fn commit_merge_with_head(
	repo: &git2::Repository,
	commits: &[Commit],
	msg: &str,
) -> Result<CommitId> {
	let signature =
		crate::sync::commit::signature_allow_undefined_name(repo)?;
	let mut index = repo.index()?;
	let tree_id = index.write_tree()?;
	let tree = repo.find_tree(tree_id)?;
	let head_commit = repo.find_commit(
		crate::sync::utils::get_head_repo(repo)?.into(),
	)?;

	let mut parents = vec![&head_commit];
	parents.extend(commits);

	let commit_id = repo
		.commit(
			Some("HEAD"),
			&signature,
			&signature,
			msg,
			&tree,
			parents.as_slice(),
		)?
		.into();
	repo.cleanup_state()?;
	Ok(commit_id)
}

#[cfg(test)]
mod test {
	use git2::Time;

	use super::*;
	use crate::sync::{
		branch_compare_upstream,
		remotes::{fetch, push::push},
		tests::{
			debug_cmd_print, get_commit_ids, repo_clone,
			repo_init_bare, write_commit_file, write_commit_file_at,
		},
		RepoState,
	};

	#[test]
	fn test_merge_normal() {
		let (r1_dir, _repo) = repo_init_bare().unwrap();

		let (clone1_dir, clone1) =
			repo_clone(r1_dir.path().to_str().unwrap()).unwrap();

		let (clone2_dir, clone2) =
			repo_clone(r1_dir.path().to_str().unwrap()).unwrap();

		let clone2_dir = clone2_dir.path().to_str().unwrap();

		// clone1

		let commit1 = write_commit_file_at(
			&clone1,
			"test.txt",
			"test",
			"commit1",
			Time::new(1, 0),
		);

		push(
			clone1_dir.path().to_str().unwrap(),
			"origin",
			"master",
			false,
			false,
			None,
			None,
		)
		.unwrap();

		// clone2

		let commit2 = write_commit_file_at(
			&clone2,
			"test2.txt",
			"test",
			"commit2",
			Time::new(2, 0),
		);

		//push should fail since origin diverged
		assert!(push(
			clone2_dir, "origin", "master", false, false, None, None,
		)
		.is_err());

		//lets fetch from origin
		let bytes = fetch(clone2_dir, "master", None, None).unwrap();
		assert!(bytes > 0);

		//we should be one commit behind
		assert_eq!(
			branch_compare_upstream(clone2_dir, "master")
				.unwrap()
				.behind,
			1
		);

		let merge_commit =
			merge_upstream_commit(clone2_dir, "master")
				.unwrap()
				.unwrap();

		let state = crate::sync::repo_state(clone2_dir).unwrap();
		assert_eq!(state, RepoState::Clean);

		assert!(!clone2.head_detached().unwrap());

		let commits = get_commit_ids(&clone2, 10);
		assert_eq!(commits.len(), 3);
		assert_eq!(commits[0], merge_commit);
		assert_eq!(commits[1], commit2);
		assert_eq!(commits[2], commit1);

		//verify commit msg
		let details =
			crate::sync::get_commit_details(clone2_dir, merge_commit)
				.unwrap();
		assert_eq!(
            details.message.unwrap().combine(),
            String::from("Merge remote-tracking branch 'refs/remotes/origin/master'")
        );
	}

	#[test]
	fn test_merge_normal_non_ff() {
		let (r1_dir, _repo) = repo_init_bare().unwrap();

		let (clone1_dir, clone1) =
			repo_clone(r1_dir.path().to_str().unwrap()).unwrap();

		let (clone2_dir, clone2) =
			repo_clone(r1_dir.path().to_str().unwrap()).unwrap();

		// clone1

		write_commit_file(
			&clone1,
			"test.bin",
			"test\nfooo",
			"commit1",
		);

		debug_cmd_print(
			clone2_dir.path().to_str().unwrap(),
			"git status",
		);

		push(
			clone1_dir.path().to_str().unwrap(),
			"origin",
			"master",
			false,
			false,
			None,
			None,
		)
		.unwrap();

		// clone2

		write_commit_file(
			&clone2,
			"test.bin",
			"foobar\ntest",
			"commit2",
		);

		let bytes = fetch(
			clone2_dir.path().to_str().unwrap(),
			"master",
			None,
			None,
		)
		.unwrap();
		assert!(bytes > 0);

		let res = merge_upstream_commit(
			clone2_dir.path().to_str().unwrap(),
			"master",
		)
		.unwrap();

		//this should not have commited cause we left conflicts behind
		assert_eq!(res, None);

		let state = crate::sync::repo_state(
			clone2_dir.path().to_str().unwrap(),
		)
		.unwrap();

		//validate the repo is in a merge state now
		assert_eq!(state, RepoState::Merge);

		//check that we still only have the first commit
		let commits = get_commit_ids(&clone1, 10);
		assert_eq!(commits.len(), 1);
	}
}