Merge commit 'refs/top-bases/t/email/obfuscate' into t/email/obfuscate
[git/repo.git] / merge-file.c
blob2a939c9dd835a7e7946eb1548e4cf637ae3ca329
1 #include "cache.h"
2 #include "run-command.h"
3 #include "xdiff-interface.h"
4 #include "blob.h"
6 static int fill_mmfile_blob(mmfile_t *f, struct blob *obj)
8 void *buf;
9 unsigned long size;
10 enum object_type type;
12 buf = read_sha1_file(obj->object.sha1, &type, &size);
13 if (!buf)
14 return -1;
15 if (type != OBJ_BLOB)
16 return -1;
17 f->ptr = buf;
18 f->size = size;
19 return 0;
22 static void free_mmfile(mmfile_t *f)
24 free(f->ptr);
27 static void *three_way_filemerge(mmfile_t *base, mmfile_t *our, mmfile_t *their, unsigned long *size)
29 mmbuffer_t res;
30 xpparam_t xpp;
31 int merge_status;
33 memset(&xpp, 0, sizeof(xpp));
34 merge_status = xdl_merge(base, our, ".our", their, ".their",
35 &xpp, XDL_MERGE_ZEALOUS, &res);
37 if (merge_status < 0)
38 return NULL;
40 *size = res.size;
41 return res.ptr;
44 static int common_outf(void *priv_, mmbuffer_t *mb, int nbuf)
46 int i;
47 mmfile_t *dst = priv_;
49 for (i = 0; i < nbuf; i++) {
50 memcpy(dst->ptr + dst->size, mb[i].ptr, mb[i].size);
51 dst->size += mb[i].size;
53 return 0;
56 static int generate_common_file(mmfile_t *res, mmfile_t *f1, mmfile_t *f2)
58 unsigned long size = f1->size < f2->size ? f1->size : f2->size;
59 void *ptr = xmalloc(size);
60 xpparam_t xpp;
61 xdemitconf_t xecfg;
62 xdemitcb_t ecb;
64 xpp.flags = XDF_NEED_MINIMAL;
65 memset(&xecfg, 0, sizeof(xecfg));
66 xecfg.ctxlen = 3;
67 xecfg.flags = XDL_EMIT_COMMON;
68 ecb.outf = common_outf;
70 res->ptr = ptr;
71 res->size = 0;
73 ecb.priv = res;
74 return xdi_diff(f1, f2, &xpp, &xecfg, &ecb);
77 void *merge_file(struct blob *base, struct blob *our, struct blob *their, unsigned long *size)
79 void *res = NULL;
80 mmfile_t f1, f2, common;
83 * Removed in either branch?
85 * NOTE! This depends on the caller having done the
86 * proper warning about removing a file that got
87 * modified in the other branch!
89 if (!our || !their) {
90 enum object_type type;
91 if (base)
92 return NULL;
93 if (!our)
94 our = their;
95 return read_sha1_file(our->object.sha1, &type, size);
98 if (fill_mmfile_blob(&f1, our) < 0)
99 goto out_no_mmfile;
100 if (fill_mmfile_blob(&f2, their) < 0)
101 goto out_free_f1;
103 if (base) {
104 if (fill_mmfile_blob(&common, base) < 0)
105 goto out_free_f2_f1;
106 } else {
107 if (generate_common_file(&common, &f1, &f2) < 0)
108 goto out_free_f2_f1;
110 res = three_way_filemerge(&common, &f1, &f2, size);
111 free_mmfile(&common);
112 out_free_f2_f1:
113 free_mmfile(&f2);
114 out_free_f1:
115 free_mmfile(&f1);
116 out_no_mmfile:
117 return res;