gitg-ref-action-merge.vala 11.2 KB
Newer Older
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
/*
 * This file is part of gitg
 *
 * Copyright (C) 2015 - Jesse van den Kieboom
 *
 * gitg is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * gitg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gitg. If not, see <http://www.gnu.org/licenses/>.
 */

namespace Gitg
{

class RefActionMerge : GitgExt.UIElement, GitgExt.Action, GitgExt.RefAction, Object
{
	// Do this to pull in config.h before glib.h (for gettext...)
	private const string version = Gitg.Config.VERSION;

	public GitgExt.Application? application { owned get; construct set; }
	public GitgExt.RefActionInterface action_interface { get; construct set; }
	public Gitg.Ref reference { get; construct set; }

	private struct RemoteSource
	{
		public string name;
		public Gitg.Ref[] sources;
	}

	private bool d_has_sourced;
	private Gitg.Ref? d_upstream;
	private Gitg.Ref[]? d_local_sources;
	private RemoteSource[]? d_remote_sources;
	private Gitg.Ref[]? d_tag_sources;
43
	private ActionSupport d_support;
44 45 46 47 48 49 50 51

	public RefActionMerge(GitgExt.Application        application,
	                      GitgExt.RefActionInterface action_interface,
	                      Gitg.Ref                   reference)
	{
		Object(application:      application,
		       action_interface: action_interface,
		       reference:        reference);
52 53

		d_support = new ActionSupport(application, action_interface);
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
	}

	public string id
	{
		owned get { return "/org/gnome/gitg/ref-actions/merge"; }
	}

	public string display_name
	{
		owned get { return _("Merge into %s").printf(reference.parsed_name.shortname); }
	}

	public string description
	{
		// TODO
		owned get { return _("Merge another branch into branch %s").printf(reference.parsed_name.shortname); }
	}

	public bool available
	{
		get
		{
			return reference.is_branch();
		}
	}

	public bool enabled
	{
		get
		{
			ensure_sources();

			return d_upstream != null ||
			       d_local_sources.length != 0 ||
			       d_remote_sources.length != 0 ||
			       d_tag_sources.length != 0;
		}
	}

	private async Ggit.Index create_merge_index(SimpleNotification notification, Ggit.Commit ours, Ggit.Commit theirs)
	{
		Ggit.Index? index = null;

		yield Async.thread_try(() => {
			var options = new Ggit.MergeOptions();

			try
			{
				index = application.repository.merge_commits(ours, theirs, options);
			}
			catch (Error e)
			{
				notification.error(_("Failed to merge commits: %s").printf(e.message));
				return;
			}
		});

		return index;
	}

114
	private void write_merge_state_files(Ggit.Index index, Gitg.Ref source)
115
	{
116 117
		var wd = application.repository.get_location().get_path();
		var theirs_name = source.parsed_name.shortname;
118 119 120

		try
		{
121 122 123
			var dest_oid = reference.resolve().get_target();
			FileUtils.set_contents(Path.build_filename(wd, "ORIG_HEAD"), "%s\n".printf(dest_oid.to_string()));
		} catch {}
124

125
		try
126
		{
127 128 129
			var source_oid = source.resolve().get_target();
			FileUtils.set_contents(Path.build_filename(wd, "MERGE_HEAD"), "%s\n".printf(source_oid.to_string()));
		} catch {}
130

131
		try
132
		{
133 134
			FileUtils.set_contents(Path.build_filename(wd, "MERGE_MODE"), "no-ff\n");
		} catch {}
135 136 137

		try
		{
138 139 140
			string msg;

			if (source.parsed_name.rtype == RefType.REMOTE)
141
			{
142 143 144 145 146
				msg = @"Merge remote branch '$theirs_name'";
			}
			else
			{
				msg = @"Merge branch '$theirs_name'";
147 148
			}

149
			msg += "\n\nConflicts:\n";
150

151 152
			var entries = index.get_entries();
			var seen = new Gee.HashSet<string>();
153

154
			for (var i = 0; i < entries.size(); i++)
155
			{
156 157
				var entry = entries.get_by_index(i);
				var p = entry.get_path();
158

159 160 161 162 163
				if (entry.is_conflict() && !seen.contains(p))
				{
					msg += "\t%s\n".printf(p);
					seen.add(p);
				}
164 165
			}

166 167
			FileUtils.set_contents(Path.build_filename(wd, "MERGE_MSG"), msg);
		} catch {}
168 169 170 171 172 173 174 175 176 177
	}

	private async bool checkout_conflicts(SimpleNotification notification, Ggit.Index index, Gitg.Ref source)
	{
		var ours_name = reference.parsed_name.shortname;
		var theirs_name = source.parsed_name.shortname;

		notification.message = _("Merge has conflicts");

		Gitg.Ref? head = null;
178
		var ishead = d_support.reference_is_head(reference, ref head);
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202

		string message;

		if (ishead)
		{
			message = _("The merge of %s into %s has caused conflicts, would you like to checkout branch %s with the merge to your working directory to resolve the conflicts?").printf(@"'$theirs_name'", @"'$ours_name'", @"'$ours_name'");
		}
		else
		{
			message = _("The merge of %s into %s has caused conflicts, would you like to checkout the merge to your working directory to resolve the conflicts?").printf(@"'$theirs_name'", @"'$ours_name'");
		}

		var q = new GitgExt.UserQuery.full(_("Merge has conflicts"),
		                                   message,
		                                   Gtk.MessageType.QUESTION,
		                                   _("Cancel"), Gtk.ResponseType.CANCEL,
		                                   _("Checkout"), Gtk.ResponseType.OK);

		if ((yield application.user_query_async(q)) != Gtk.ResponseType.OK)
		{
			notification.error(_("Merge failed with conflicts"));
			return false;
		}

203
		if (!(yield d_support.checkout_conflicts(notification, reference, index, head)))
204 205 206 207
		{
			return false;
		}

208
		write_merge_state_files(index, source);
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

		notification.success(_("Finished merge with conflicts in working directory"));
		return true;
	}

	public async Ggit.OId? merge(Gitg.Ref source)
	{
		Ggit.Commit ours;
		Ggit.Commit theirs;

		var ours_name = reference.parsed_name.shortname;
		var theirs_name = source.parsed_name.shortname;

		var notification = new SimpleNotification(_("Merge %s into %s").printf(@"'$theirs_name'", @"'$ours_name'"));
		application.notifications.add(notification);

		try
		{
			ours = reference.resolve().lookup() as Ggit.Commit;
		}
		catch (Error e)
		{
			notification.error(_("Failed to lookup our commit: %s").printf(e.message));
			return null;
		}

		try
		{
			theirs = source.resolve().lookup() as Ggit.Commit;
		}
		catch (Error e)
		{
			notification.error(_("Failed to lookup their commit: %s").printf(e.message));
			return null;
		}

		var index = yield create_merge_index(notification, ours, theirs);

		if (index == null)
		{
			return null;
		}

		if (index.has_conflicts())
		{
			yield checkout_conflicts(notification, index, source);
			return null;
		}

		string msg;

		if (source.parsed_name.rtype == RefType.REMOTE)
		{
			msg = @"Merge remote branch '$theirs_name'";
		}
		else
		{
			msg = @"Merge branch '$theirs_name'";
		}

269 270 271 272 273 274
		var oid = yield d_support.commit_index(notification,
		                                       reference,
		                                       index,
		                                       new Ggit.OId[] { ours.get_id(), theirs.get_id() },
		                                       null,
		                                       msg);
275

276
		if (oid != null)
277
		{
278
			notification.success(_("Successfully merged %s into %s").printf(@"'$theirs_name'", @"'$ours_name'"));
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 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
		}

		return oid;
	}

	public void activate_source(Gitg.Ref source)
	{
		merge.begin(source, (obj, res) => {
			merge.end(res);
		});
	}

	private Gitg.Ref? upstream_reference()
	{
		var branch = reference as Ggit.Branch;

		if (branch != null)
		{
			try
			{
				return branch.get_upstream() as Gitg.Ref;
			} catch {}
		}

		return null;
	}

	private void add_merge_source(Gtk.Menu submenu, Gitg.Ref? source)
	{
		if (source == null)
		{
			var sep = new Gtk.SeparatorMenuItem();
			sep.show();
			submenu.append(sep);
			return;
		}

		var name = source.parsed_name.shortname;
		var item = new Gtk.MenuItem.with_label(name);

		item.show();
		item.tooltip_text = _("Merge %s into branch %s").printf(@"'$name'", @"'$(reference.parsed_name.shortname)'");

		item.activate.connect(() => {
			activate_source(source);
		});

		submenu.append(item);
	}

	private void ensure_sources()
	{
		if (d_has_sourced)
		{
			return;
		}

		d_has_sourced = true;

		if (!available)
		{
			return;
		}

		// Allow merging from remotes and other local branches, offer
		// to merge upstream first.
		d_upstream = upstream_reference();

		d_local_sources = new Gitg.Ref[0];
		d_remote_sources = new RemoteSource[0];
		d_tag_sources = new Gitg.Ref[0];

		Ggit.OId? target_oid = null;

		try
		{
			target_oid = reference.resolve().get_target();
		} catch {}

		string? last_remote = null;

		foreach (var r in action_interface.references)
		{
			if (d_upstream != null && r.get_name() == d_upstream.get_name())
			{
				continue;
			}

			// Filter out things where merging is a noop
			if (target_oid != null)
			{
				Ggit.OId? oid = null;

				try
				{
					oid = r.resolve().get_target();
				} catch {}

				if (oid != null && oid.equal(target_oid))
				{
					continue;
				}
			}

			if (r.is_branch())
			{
				d_local_sources += r;
			}
			else if (r.is_tag())
			{
				d_tag_sources += r;
			}
			else if (r.parsed_name.rtype == RefType.REMOTE)
			{
				var remote_name = r.parsed_name.remote_name;

				if (remote_name != last_remote)
				{
					var source = RemoteSource() {
						name = remote_name,
						sources = new Gitg.Ref[] { r }
					};

					d_remote_sources += source;
				}
				else
				{
					d_remote_sources[d_remote_sources.length - 1].sources += r;
				}

				last_remote = remote_name;
			}
		}
	}

	public void populate_menu(Gtk.Menu menu)
	{
		if (!available)
		{
			return;
		}

		var item = new Gtk.MenuItem.with_label(display_name);
		item.tooltip_text = description;

		if (enabled)
		{
			var submenu = new Gtk.Menu();
			submenu.show();

			if (d_upstream != null)
			{
				add_merge_source(submenu, d_upstream);
			}

			if (d_local_sources.length != 0)
			{
				if (d_upstream != null)
				{
					// Add a separator
					add_merge_source(submenu, null);
				}

				foreach (var source in d_local_sources)
				{
					add_merge_source(submenu, source);
				}
			}

			if (d_remote_sources.length != 0)
			{
				if (d_local_sources.length != 0 || d_upstream != null)
				{
					// Add a separator
					add_merge_source(submenu, null);
				}

				foreach (var remote in d_remote_sources)
				{
					var subitem = new Gtk.MenuItem.with_label(remote.name);
					subitem.show();

					var subsubmenu = new Gtk.Menu();
					subsubmenu.show();

					foreach (var source in remote.sources)
					{
						add_merge_source(subsubmenu, source);
					}

					subitem.submenu = subsubmenu;
					submenu.append(subitem);
				}
			}

			if (d_tag_sources.length != 0)
			{
				if (d_remote_sources.length != 0 || d_local_sources.length != 0 || d_upstream != null)
				{
					// Add a separator
					add_merge_source(submenu, null);
				}

				var subitem = new Gtk.MenuItem.with_label(_("Tags"));
				subitem.show();

				var subsubmenu = new Gtk.Menu();
				subsubmenu.show();

				foreach (var source in d_tag_sources)
				{
					add_merge_source(subsubmenu, source);
				}

				subitem.submenu = subsubmenu;
				submenu.append(subitem);
			}

			item.submenu = submenu;
		}
		else
		{
			item.sensitive = false;
		}

		item.show();
		menu.append(item);
	}
}

}

// ex:set ts=4 noet