merge.c 10.4 KB
Newer Older
Etienne Samson committed
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
/*
 * libgit2 "merge" example - shows how to perform merges
 *
 * Written by the libgit2 contributors
 *
 * To the extent possible under law, the author(s) have dedicated all copyright
 * and related and neighboring rights to this software to the public domain
 * worldwide. This software is distributed without any warranty.
 *
 * You should have received a copy of the CC0 Public Domain Dedication along
 * with this software. If not, see
 * <http://creativecommons.org/publicdomain/zero/1.0/>.
 */

#include "common.h"

/** The following example demonstrates how to do merges with libgit2.
 *
 * It will merge whatever commit-ish you pass in into the current branch.
 *
 * Recognized options are :
 *  --no-commit: don't actually commit the merge.
 *
 */

26
struct merge_options {
Etienne Samson committed
27 28 29 30 31 32 33
	const char **heads;
	size_t heads_count;

	git_annotated_commit **annotated;
	size_t annotated_count;

	int no_commit : 1;
34
};
Etienne Samson committed
35 36 37 38 39 40 41

static void print_usage(void)
{
	fprintf(stderr, "usage: merge [--no-commit] <commit...>\n");
	exit(1);
}

42
static void merge_options_init(struct merge_options *opts)
Etienne Samson committed
43
{
44 45
	memset(opts, 0, sizeof(*opts));

Etienne Samson committed
46 47 48 49 50 51
	opts->heads = NULL;
	opts->heads_count = 0;
	opts->annotated = NULL;
	opts->annotated_count = 0;
}

52
static void opts_add_refish(struct merge_options *opts, const char *refish)
Etienne Samson committed
53 54 55 56 57 58
{
	size_t sz;

	assert(opts != NULL);

	sz = ++opts->heads_count * sizeof(opts->heads[0]);
59
	opts->heads = xrealloc((void *) opts->heads, sz);
Etienne Samson committed
60 61 62
	opts->heads[opts->heads_count - 1] = refish;
}

63
static void parse_options(const char **repo_path, struct merge_options *opts, int argc, char **argv)
Etienne Samson committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77
{
	struct args_info args = ARGS_INFO_INIT;

	if (argc <= 1)
		print_usage();

	for (args.pos = 1; args.pos < argc; ++args.pos) {
		const char *curr = argv[args.pos];

		if (curr[0] != '-') {
			opts_add_refish(opts, curr);
		} else if (!strcmp(curr, "--no-commit")) {
			opts->no_commit = 1;
		} else if (match_str_arg(repo_path, &args, "--git-dir")) {
78
			continue;
Etienne Samson committed
79 80 81 82 83 84
		} else {
			print_usage();
		}
	}
}

85
static int resolve_heads(git_repository *repo, struct merge_options *opts)
86
{
Etienne Samson committed
87 88 89 90 91
	git_annotated_commit **annotated = calloc(opts->heads_count, sizeof(git_annotated_commit *));
	size_t annotated_count = 0, i;
	int err = 0;

	for (i = 0; i < opts->heads_count; i++) {
92
		err = resolve_refish(&annotated[annotated_count++], repo, opts->heads[i]);
Etienne Samson committed
93
		if (err != 0) {
94
			fprintf(stderr, "failed to resolve refish %s: %s\n", opts->heads[i], git_error_last()->message);
Etienne Samson committed
95 96 97 98 99
			annotated_count--;
			continue;
		}
	}

100 101
	if (annotated_count != opts->heads_count) {
		fprintf(stderr, "unable to parse some refish\n");
Etienne Samson committed
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
		free(annotated);
		return -1;
	}

	opts->annotated = annotated;
	opts->annotated_count = annotated_count;
	return 0;
}

static int perform_fastforward(git_repository *repo, const git_oid *target_oid, int is_unborn)
{
	git_checkout_options ff_checkout_options = GIT_CHECKOUT_OPTIONS_INIT;
	git_reference *target_ref;
	git_reference *new_target_ref;
	git_object *target = NULL;
	int err = 0;

	if (is_unborn) {
		const char *symbolic_ref;
		git_reference *head_ref;

		/* HEAD reference is unborn, lookup manually so we don't try to resolve it */
		err = git_reference_lookup(&head_ref, repo, "HEAD");
		if (err != 0) {
			fprintf(stderr, "failed to lookup HEAD ref\n");
			return -1;
		}

		/* Grab the reference HEAD should be pointing to */
		symbolic_ref = git_reference_symbolic_target(head_ref);

133 134
		/* Create our master reference on the target OID */
		err = git_reference_create(&target_ref, repo, symbolic_ref, target_oid, 0, NULL);
Etienne Samson committed
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
		if (err != 0) {
			fprintf(stderr, "failed to create master reference\n");
			return -1;
		}

		git_reference_free(head_ref);
	} else {
		/* HEAD exists, just lookup and resolve */
		err = git_repository_head(&target_ref, repo);
		if (err != 0) {
			fprintf(stderr, "failed to get HEAD reference\n");
			return -1;
		}
	}

	/* Lookup the target object */
151
	err = git_object_lookup(&target, repo, target_oid, GIT_OBJECT_COMMIT);
Etienne Samson committed
152 153 154 155 156
	if (err != 0) {
		fprintf(stderr, "failed to lookup OID %s\n", git_oid_tostr_s(target_oid));
		return -1;
	}

157 158
	/* Checkout the result so the workdir is in the expected state */
	ff_checkout_options.checkout_strategy = GIT_CHECKOUT_SAFE;
Etienne Samson committed
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
	err = git_checkout_tree(repo, target, &ff_checkout_options);
	if (err != 0) {
		fprintf(stderr, "failed to checkout HEAD reference\n");
		return -1;
	}

	/* Move the target reference to the target OID */
	err = git_reference_set_target(&new_target_ref, target_ref, target_oid, NULL);
	if (err != 0) {
		fprintf(stderr, "failed to move HEAD reference\n");
		return -1;
	}

	git_reference_free(target_ref);
	git_reference_free(new_target_ref);
	git_object_free(target);

	return 0;
}

179 180 181 182 183 184 185 186 187 188 189 190
static void output_conflicts(git_index *index)
{
	git_index_conflict_iterator *conflicts;
	const git_index_entry *ancestor;
	const git_index_entry *our;
	const git_index_entry *their;
	int err = 0;

	check_lg2(git_index_conflict_iterator_new(&conflicts, index), "failed to create conflict iterator", NULL);

	while ((err = git_index_conflict_next(&ancestor, &our, &their, conflicts)) == 0) {
		fprintf(stderr, "conflict: a:%s o:%s t:%s\n",
191 192 193
		        ancestor ? ancestor->path : "NULL",
		        our->path ? our->path : "NULL",
		        their->path ? their->path : "NULL");
194 195 196 197 198 199 200 201 202
	}

	if (err != GIT_ITEROVER) {
		fprintf(stderr, "error iterating conflicts\n");
	}

	git_index_conflict_iterator_free(conflicts);
}

203
static int create_merge_commit(git_repository *repo, git_index *index, struct merge_options *opts)
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
{
	git_oid tree_oid, commit_oid;
	git_tree *tree;
	git_signature *sign;
	git_reference *merge_ref = NULL;
	git_annotated_commit *merge_commit;
	git_reference *head_ref;
	git_commit **parents = calloc(opts->annotated_count + 1, sizeof(git_commit *));
	const char *msg_target = NULL;
	size_t msglen = 0;
	char *msg;
	size_t i;
	int err;

	/* Grab our needed references */
	check_lg2(git_repository_head(&head_ref, repo), "failed to get repo HEAD", NULL);
	if (resolve_refish(&merge_commit, repo, opts->heads[0])) {
		fprintf(stderr, "failed to resolve refish %s", opts->heads[0]);
222
		free(parents);
223
		return -1;
224 225 226 227
	}

	/* Maybe that's a ref, so DWIM it */
	err = git_reference_dwim(&merge_ref, repo, opts->heads[0]);
228
	check_lg2(err, "failed to DWIM reference", git_error_last()->message);
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249

	/* Grab a signature */
	check_lg2(git_signature_now(&sign, "Me", "me@example.com"), "failed to create signature", NULL);

#define MERGE_COMMIT_MSG "Merge %s '%s'"
	/* Prepare a standard merge commit message */
	if (merge_ref != NULL) {
		check_lg2(git_branch_name(&msg_target, merge_ref), "failed to get branch name of merged ref", NULL);
	} else {
		msg_target = git_oid_tostr_s(git_annotated_commit_id(merge_commit));
	}

	msglen = snprintf(NULL, 0, MERGE_COMMIT_MSG, (merge_ref ? "branch" : "commit"), msg_target);
	if (msglen > 0) msglen++;
	msg = malloc(msglen);
	err = snprintf(msg, msglen, MERGE_COMMIT_MSG, (merge_ref ? "branch" : "commit"), msg_target);

	/* This is only to silence the compiler */
	if (err < 0) goto cleanup;

	/* Setup our parent commits */
250
	err = git_reference_peel((git_object **)&parents[0], head_ref, GIT_OBJECT_COMMIT);
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
	check_lg2(err, "failed to peel head reference", NULL);
	for (i = 0; i < opts->annotated_count; i++) {
		git_commit_lookup(&parents[i + 1], repo, git_annotated_commit_id(opts->annotated[i]));
	}

	/* Prepare our commit tree */
	check_lg2(git_index_write_tree(&tree_oid, index), "failed to write merged tree", NULL);
	check_lg2(git_tree_lookup(&tree, repo, &tree_oid), "failed to lookup tree", NULL);

	/* Commit time ! */
	err = git_commit_create(&commit_oid,
	                        repo, git_reference_name(head_ref),
	                        sign, sign,
	                        NULL, msg,
	                        tree,
	                        opts->annotated_count + 1, (const git_commit **)parents);
	check_lg2(err, "failed to create commit", NULL);

	/* We're done merging, cleanup the repository state */
	git_repository_state_cleanup(repo);

cleanup:
273
	free(parents);
274 275 276
	return err;
}

277
int lg2_merge(git_repository *repo, int argc, char **argv)
Etienne Samson committed
278
{
279
	struct merge_options opts;
280 281
	git_index *index;
	git_repository_state_t state;
Etienne Samson committed
282 283
	git_merge_analysis_t analysis;
	git_merge_preference_t preference;
284
	const char *path = ".";
Etienne Samson committed
285 286
	int err = 0;

287 288
	merge_options_init(&opts);
	parse_options(&path, &opts, argc, argv);
Etienne Samson committed
289

290 291 292 293 294 295 296 297 298
	state = git_repository_state(repo);
	if (state != GIT_REPOSITORY_STATE_NONE) {
		fprintf(stderr, "repository is in unexpected state %d\n", state);
		goto cleanup;
	}

	err = resolve_heads(repo, &opts);
	if (err != 0)
		goto cleanup;
Etienne Samson committed
299 300 301

	err = git_merge_analysis(&analysis, &preference,
	                         repo,
302 303
	                         (const git_annotated_commit **)opts.annotated,
	                         opts.annotated_count);
Etienne Samson committed
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
	check_lg2(err, "merge analysis failed", NULL);

	if (analysis & GIT_MERGE_ANALYSIS_UP_TO_DATE) {
		printf("Already up-to-date\n");
		return 0;
	} else if (analysis & GIT_MERGE_ANALYSIS_UNBORN ||
	          (analysis & GIT_MERGE_ANALYSIS_FASTFORWARD &&
	          !(preference & GIT_MERGE_PREFERENCE_NO_FASTFORWARD))) {
		const git_oid *target_oid;
		if (analysis & GIT_MERGE_ANALYSIS_UNBORN) {
			printf("Unborn\n");
		} else {
			printf("Fast-forward\n");
		}

		/* Since this is a fast-forward, there can be only one merge head */
320 321
		target_oid = git_annotated_commit_id(opts.annotated[0]);
		assert(opts.annotated_count == 1);
Etienne Samson committed
322 323 324

		return perform_fastforward(repo, target_oid, (analysis & GIT_MERGE_ANALYSIS_UNBORN));
	} else if (analysis & GIT_MERGE_ANALYSIS_NORMAL) {
325 326 327 328 329 330 331 332
		git_merge_options merge_opts = GIT_MERGE_OPTIONS_INIT;
		git_checkout_options checkout_opts = GIT_CHECKOUT_OPTIONS_INIT;

		merge_opts.flags = 0;
		merge_opts.file_flags = GIT_MERGE_FILE_STYLE_DIFF3;

		checkout_opts.checkout_strategy = GIT_CHECKOUT_FORCE|GIT_CHECKOUT_ALLOW_CONFLICTS;

Etienne Samson committed
333 334 335 336 337 338
		if (preference & GIT_MERGE_PREFERENCE_FASTFORWARD_ONLY) {
			printf("Fast-forward is preferred, but only a merge is possible\n");
			return -1;
		}

		err = git_merge(repo,
339
		                (const git_annotated_commit **)opts.annotated, opts.annotated_count,
Etienne Samson committed
340
		                &merge_opts, &checkout_opts);
341
		check_lg2(err, "merge failed", NULL);
Etienne Samson committed
342 343
	}

344
	/* If we get here, we actually performed the merge above */
Etienne Samson committed
345 346 347 348

	check_lg2(git_repository_index(&index, repo), "failed to get repository index", NULL);

	if (git_index_has_conflicts(index)) {
349
		/* Handle conflicts */
350
		output_conflicts(index);
Etienne Samson committed
351
	} else if (!opts.no_commit) {
352
		create_merge_commit(repo, index, &opts);
353
		printf("Merge made\n");
Etienne Samson committed
354
	}
355

Etienne Samson committed
356
cleanup:
357
	free((char **)opts.heads);
Etienne Samson committed
358 359 360 361
	free(opts.annotated);

	return 0;
}