Merge branch 'sp/maint-bash-completion-optim'
[git/git-p4.git] / builtin-merge-file.c
blob3605960c2d9692514a6df0f344f3c3269cf1de3c
1 #include "builtin.h"
2 #include "cache.h"
3 #include "xdiff/xdiff.h"
4 #include "xdiff-interface.h"
6 static const char merge_file_usage[] =
7 "git merge-file [-p | --stdout] [-q | --quiet] [-L name1 [-L orig [-L name2]]] file1 orig_file file2";
9 int cmd_merge_file(int argc, const char **argv, const char *prefix)
11 const char *names[3];
12 mmfile_t mmfs[3];
13 mmbuffer_t result = {NULL, 0};
14 xpparam_t xpp = {XDF_NEED_MINIMAL};
15 int ret = 0, i = 0, to_stdout = 0;
17 while (argc > 4) {
18 if (!strcmp(argv[1], "-L") && i < 3) {
19 names[i++] = argv[2];
20 argc--;
21 argv++;
22 } else if (!strcmp(argv[1], "-p") ||
23 !strcmp(argv[1], "--stdout"))
24 to_stdout = 1;
25 else if (!strcmp(argv[1], "-q") ||
26 !strcmp(argv[1], "--quiet"))
27 freopen("/dev/null", "w", stderr);
28 else
29 usage(merge_file_usage);
30 argc--;
31 argv++;
34 if (argc != 4)
35 usage(merge_file_usage);
37 for (; i < 3; i++)
38 names[i] = argv[i + 1];
40 for (i = 0; i < 3; i++) {
41 if (read_mmfile(mmfs + i, argv[i + 1]))
42 return -1;
43 if (buffer_is_binary(mmfs[i].ptr, mmfs[i].size))
44 return error("Cannot merge binary files: %s\n",
45 argv[i + 1]);
48 ret = xdl_merge(mmfs + 1, mmfs + 0, names[0], mmfs + 2, names[2],
49 &xpp, XDL_MERGE_ZEALOUS_ALNUM, &result);
51 for (i = 0; i < 3; i++)
52 free(mmfs[i].ptr);
54 if (ret >= 0) {
55 const char *filename = argv[1];
56 FILE *f = to_stdout ? stdout : fopen(filename, "wb");
58 if (!f)
59 ret = error("Could not open %s for writing", filename);
60 else if (result.size &&
61 fwrite(result.ptr, result.size, 1, f) != 1)
62 ret = error("Could not write to %s", filename);
63 else if (fclose(f))
64 ret = error("Could not close %s", filename);
65 free(result.ptr);
68 return ret;