1#include "builtin.h"
2#include "cache.h"
3#include "xdiff/xdiff.h"
4#include "xdiff-interface.h"
5
6static const char merge_file_usage[] =
7"git merge-file [-p | --stdout] [--diff3] [-q | --quiet] [-L name1 [-L orig [-L name2]]] file1 orig_file file2";
8
9int cmd_merge_file(int argc, const char **argv, const char *prefix)
10{
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;
16 int merge_level = XDL_MERGE_ZEALOUS_ALNUM;
17 int merge_style = 0;
18 int nongit;
19
20 prefix = setup_git_directory_gently(&nongit);
21 if (!nongit) {
22 /* Read the configuration file */
23 git_config(git_xmerge_config, NULL);
24 if (0 <= git_xmerge_style)
25 merge_style = git_xmerge_style;
26 }
27
28 while (argc > 4) {
29 if (!strcmp(argv[1], "-L") && i < 3) {
30 names[i++] = argv[2];
31 argc--;
32 argv++;
33 } else if (!strcmp(argv[1], "-p") ||
34 !strcmp(argv[1], "--stdout"))
35 to_stdout = 1;
36 else if (!strcmp(argv[1], "-q") ||
37 !strcmp(argv[1], "--quiet"))
38 freopen("/dev/null", "w", stderr);
39 else if (!strcmp(argv[1], "--diff3"))
40 merge_style = XDL_MERGE_DIFF3;
41 else
42 usage(merge_file_usage);
43 argc--;
44 argv++;
45 }
46
47 if (argc != 4)
48 usage(merge_file_usage);
49
50 for (; i < 3; i++)
51 names[i] = argv[i + 1];
52
53 for (i = 0; i < 3; i++) {
54 if (read_mmfile(mmfs + i, argv[i + 1]))
55 return -1;
56 if (buffer_is_binary(mmfs[i].ptr, mmfs[i].size))
57 return error("Cannot merge binary files: %s\n",
58 argv[i + 1]);
59 }
60
61 ret = xdl_merge(mmfs + 1, mmfs + 0, names[0], mmfs + 2, names[2],
62 &xpp, merge_level | merge_style, &result);
63
64 for (i = 0; i < 3; i++)
65 free(mmfs[i].ptr);
66
67 if (ret >= 0) {
68 const char *filename = argv[1];
69 FILE *f = to_stdout ? stdout : fopen(filename, "wb");
70
71 if (!f)
72 ret = error("Could not open %s for writing", filename);
73 else if (result.size &&
74 fwrite(result.ptr, result.size, 1, f) != 1)
75 ret = error("Could not write to %s", filename);
76 else if (fclose(f))
77 ret = error("Could not close %s", filename);
78 free(result.ptr);
79 }
80
81 return ret;
82}