Commit e18df18bea14e17f648209b733359564a5836d8a

Carlos Martín Nieto 2016-03-17T18:01:37

Merge pull request #3564 from ethomson/merge_drivers Custom merge drivers and proper gitattributes `merge` handling

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
43
44
45
46
47
48
49
50
51
52
53
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
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
269
270
271
272
273
274
275
276
277
278
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 21f972d..0e9ca15 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,10 @@ v0.24
 
 ### Changes or improvements
 
+* Custom merge drivers can now be registered, which allows callers to
+  configure callbacks to honor `merge=driver` configuration in
+  `.gitattributes`.
+
 * Custom filters can now be registered with wildcard attributes, for
   example `filter=*`.  Consumers should examine the attributes parameter
   of the `check` function for details.
@@ -83,6 +87,10 @@ v0.24
 
 ### Breaking API changes
 
+* `git_merge_options` now provides a `default_driver` that can be used
+  to provide the name of a merge driver to be used to handle files changed
+  during a merge.
+
 * The `git_merge_tree_flag_t` is now `git_merge_flag_t`.  Subsequently,
   its members are no longer prefixed with `GIT_MERGE_TREE_FLAG` but are
   now prefixed with `GIT_MERGE_FLAG`, and the `tree_flags` field of the
diff --git a/include/git2/merge.h b/include/git2/merge.h
index 560797a..c6f6cba 100644
--- a/include/git2/merge.h
+++ b/include/git2/merge.h
@@ -273,7 +273,16 @@ typedef struct {
 	 */
 	unsigned int recursion_limit;
 
-	/** Flags for handling conflicting content. */
+	/**
+	 * Default merge driver to be used when both sides of a merge have
+	 * changed.  The default is the `text` driver.
+	 */
+	const char *default_driver;
+
+	/**
+	 * Flags for handling conflicting content, to be used with the standard
+	 * (`text`) merge driver.
+	 */
 	git_merge_file_favor_t file_favor;
 
 	/** see `git_merge_file_flag_t` above */
diff --git a/include/git2/sys/merge.h b/include/git2/sys/merge.h
new file mode 100644
index 0000000..0319410
--- /dev/null
+++ b/include/git2/sys/merge.h
@@ -0,0 +1,177 @@
+/*
+ * Copyright (C) the libgit2 contributors. All rights reserved.
+ *
+ * This file is part of libgit2, distributed under the GNU GPL v2 with
+ * a Linking Exception. For full terms see the included COPYING file.
+ */
+#ifndef INCLUDE_sys_git_merge_h__
+#define INCLUDE_sys_git_merge_h__
+
+/**
+ * @file git2/sys/merge.h
+ * @brief Git merge driver backend and plugin routines
+ * @defgroup git_backend Git custom backend APIs
+ * @ingroup Git
+ * @{
+ */
+GIT_BEGIN_DECL
+
+typedef struct git_merge_driver git_merge_driver;
+
+/**
+ * Look up a merge driver by name
+ *
+ * @param name The name of the merge driver
+ * @return Pointer to the merge driver object or NULL if not found
+ */
+GIT_EXTERN(git_merge_driver *) git_merge_driver_lookup(const char *name);
+
+#define GIT_MERGE_DRIVER_TEXT   "text"
+#define GIT_MERGE_DRIVER_BINARY "binary"
+#define GIT_MERGE_DRIVER_UNION  "union"
+
+/**
+ * A merge driver source represents the file to be merged
+ */
+typedef struct git_merge_driver_source git_merge_driver_source;
+
+/** Get the repository that the source data is coming from. */
+GIT_EXTERN(git_repository *) git_merge_driver_source_repo(
+	const git_merge_driver_source *src);
+
+/** Gets the ancestor of the file to merge. */
+GIT_EXTERN(git_index_entry *) git_merge_driver_source_ancestor(
+	const git_merge_driver_source *src);
+
+/** Gets the ours side of the file to merge. */
+GIT_EXTERN(git_index_entry *) git_merge_driver_source_ours(
+	const git_merge_driver_source *src);
+
+/** Gets the theirs side of the file to merge. */
+GIT_EXTERN(git_index_entry *) git_merge_driver_source_theirs(
+	const git_merge_driver_source *src);
+
+/** Gets the merge file options that the merge was invoked with */
+GIT_EXTERN(git_merge_file_options *) git_merge_driver_source_file_options(
+	const git_merge_driver_source *src);
+
+
+/**
+ * Initialize callback on merge driver
+ *
+ * Specified as `driver.initialize`, this is an optional callback invoked
+ * before a merge driver is first used.  It will be called once at most
+ * per library lifetime.
+ *
+ * If non-NULL, the merge driver's `initialize` callback will be invoked
+ * right before the first use of the driver, so you can defer expensive
+ * initialization operations (in case libgit2 is being used in a way that
+ * doesn't need the merge driver).
+ */
+typedef int (*git_merge_driver_init_fn)(git_merge_driver *self);
+
+/**
+ * Shutdown callback on merge driver
+ *
+ * Specified as `driver.shutdown`, this is an optional callback invoked
+ * when the merge driver is unregistered or when libgit2 is shutting down.
+ * It will be called once at most and should release resources as needed.
+ * This may be called even if the `initialize` callback was not made.
+ *
+ * Typically this function will free the `git_merge_driver` object itself.
+ */
+typedef void (*git_merge_driver_shutdown_fn)(git_merge_driver *self);
+
+/**
+ * Callback to perform the merge.
+ *
+ * Specified as `driver.apply`, this is the callback that actually does the
+ * merge.  If it can successfully perform a merge, it should populate
+ * `path_out` with a pointer to the filename to accept, `mode_out` with
+ * the resultant mode, and `merged_out` with the buffer of the merged file
+ * and then return 0.  If the driver returns `GIT_PASSTHROUGH`, then the
+ * default merge driver should instead be run.  It can also return
+ * `GIT_EMERGECONFLICT` if the driver is not able to produce a merge result,
+ * and the file will remain conflicted.  Any other errors will fail and
+ * return to the caller.
+ *
+ * The `filter_name` contains the name of the filter that was invoked, as
+ * specified by the file's attributes.
+ *
+ * The `src` contains the data about the file to be merged.
+ */
+typedef int (*git_merge_driver_apply_fn)(
+	git_merge_driver *self,
+	const char **path_out,
+	uint32_t *mode_out,
+	git_buf *merged_out,
+	const char *filter_name,
+	const git_merge_driver_source *src);
+
+/**
+ * Merge driver structure used to register custom merge drivers.
+ *
+ * To associate extra data with a driver, allocate extra data and put the
+ * `git_merge_driver` struct at the start of your data buffer, then cast
+ * the `self` pointer to your larger structure when your callback is invoked.
+ */
+struct git_merge_driver {
+	/** The `version` should be set to `GIT_MERGE_DRIVER_VERSION`. */
+	unsigned int                 version;
+
+	/** Called when the merge driver is first used for any file. */
+	git_merge_driver_init_fn     initialize;
+
+	/** Called when the merge driver is unregistered from the system. */
+	git_merge_driver_shutdown_fn shutdown;
+
+	/**
+	 * Called to merge the contents of a conflict.  If this function
+	 * returns `GIT_PASSTHROUGH` then the default (`text`) merge driver
+	 * will instead be invoked.  If this function returns
+	 * `GIT_EMERGECONFLICT` then the file will remain conflicted.
+	 */
+	git_merge_driver_apply_fn    apply;
+};
+
+#define GIT_MERGE_DRIVER_VERSION 1
+
+/**
+ * Register a merge driver under a given name.
+ *
+ * As mentioned elsewhere, the initialize callback will not be invoked
+ * immediately.  It is deferred until the driver is used in some way.
+ *
+ * Currently the merge driver registry is not thread safe, so any
+ * registering or deregistering of merge drivers must be done outside of
+ * any possible usage of the drivers (i.e. during application setup or
+ * shutdown).
+ *
+ * @param name The name of this driver to match an attribute.  Attempting
+ * 			to register with an in-use name will return GIT_EEXISTS.
+ * @param driver The merge driver definition.  This pointer will be stored
+ *			as is by libgit2 so it must be a durable allocation (either
+ *			static or on the heap).
+ * @return 0 on successful registry, error code <0 on failure
+ */
+GIT_EXTERN(int) git_merge_driver_register(
+	const char *name, git_merge_driver *driver);
+
+/**
+ * Remove the merge driver with the given name.
+ *
+ * Attempting to remove the builtin libgit2 merge drivers is not permitted
+ * and will return an error.
+ *
+ * Currently the merge driver registry is not thread safe, so any
+ * registering or deregistering of drivers must be done outside of any
+ * possible usage of the drivers (i.e. during application setup or shutdown).
+ *
+ * @param name The name under which the merge driver was registered
+ * @return 0 on success, error code <0 on failure
+ */
+GIT_EXTERN(int) git_merge_driver_unregister(const char *name);
+
+/** @} */
+GIT_END_DECL
+#endif
diff --git a/src/global.c b/src/global.c
index c725b51..cbd12dd 100644
--- a/src/global.c
+++ b/src/global.c
@@ -9,6 +9,7 @@
 #include "hash.h"
 #include "sysdir.h"
 #include "filter.h"
+#include "merge_driver.h"
 #include "openssl_stream.h"
 #include "thread-utils.h"
 #include "git2/global.h"
@@ -59,6 +60,7 @@ static int init_common(void)
 	if ((ret = git_hash_global_init()) == 0 &&
 		(ret = git_sysdir_global_init()) == 0 &&
 		(ret = git_filter_global_init()) == 0 &&
+		(ret = git_merge_driver_global_init()) == 0 &&
 		(ret = git_transport_ssh_global_init()) == 0)
 		ret = git_openssl_stream_global_init();
 
diff --git a/src/merge.c b/src/merge.c
index d2f92cc..a0f2405 100644
--- a/src/merge.c
+++ b/src/merge.c
@@ -29,6 +29,7 @@
 #include "annotated_commit.h"
 #include "commit.h"
 #include "oidarray.h"
+#include "merge_driver.h"
 
 #include "git2/types.h"
 #include "git2/repository.h"
@@ -50,18 +51,6 @@
 #define GIT_MERGE_INDEX_ENTRY_ISFILE(X) S_ISREG((X).mode)
 
 
-/** Internal merge flags. */
-enum {
-	/** The merge is for a virtual base in a recursive merge. */
-	GIT_MERGE__VIRTUAL_BASE = (1 << 31),
-};
-
-enum {
-	/** Accept the conflict file, staging it as the merge result. */
-	GIT_MERGE_FILE_FAVOR__CONFLICTED = 4,
-};
-
-
 typedef enum {
 	TREE_IDX_ANCESTOR = 0,
 	TREE_IDX_OURS = 1,
@@ -273,7 +262,7 @@ int git_merge_base(git_oid *out, git_repository *repo, const git_oid *one, const
 int git_merge_bases(git_oidarray *out, git_repository *repo, const git_oid *one, const git_oid *two)
 {
 	int error;
-        git_revwalk *walk;
+	git_revwalk *walk;
 	git_commit_list *result, *list;
 	git_array_oid_t array;
 
@@ -810,76 +799,158 @@ static int merge_conflict_resolve_one_renamed(
 	return error;
 }
 
-static int merge_conflict_resolve_automerge(
-	int *resolved,
-	git_merge_diff_list *diff_list,
-	const git_merge_diff *conflict,
-	const git_merge_file_options *file_opts)
+static bool merge_conflict_can_resolve_contents(
+	const git_merge_diff *conflict)
 {
-	const git_index_entry *ancestor = NULL, *ours = NULL, *theirs = NULL;
-	git_merge_file_result result = {0};
-	git_index_entry *index_entry;
-	git_odb *odb = NULL;
-	git_oid automerge_oid;
-	int error = 0;
-
-	assert(resolved && diff_list && conflict);
-
-	*resolved = 0;
-
 	if (!GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->our_entry) ||
 		!GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->their_entry))
-		return 0;
+		return false;
 
 	/* Reject D/F conflicts */
 	if (conflict->type == GIT_MERGE_DIFF_DIRECTORY_FILE)
-		return 0;
+		return false;
 
 	/* Reject submodules. */
 	if (S_ISGITLINK(conflict->ancestor_entry.mode) ||
 		S_ISGITLINK(conflict->our_entry.mode) ||
 		S_ISGITLINK(conflict->their_entry.mode))
-		return 0;
+		return false;
 
 	/* Reject link/file conflicts. */
-	if ((S_ISLNK(conflict->ancestor_entry.mode) ^ S_ISLNK(conflict->our_entry.mode)) ||
-		(S_ISLNK(conflict->ancestor_entry.mode) ^ S_ISLNK(conflict->their_entry.mode)))
-		return 0;
+	if ((S_ISLNK(conflict->ancestor_entry.mode) ^
+			S_ISLNK(conflict->our_entry.mode)) ||
+		(S_ISLNK(conflict->ancestor_entry.mode) ^
+			S_ISLNK(conflict->their_entry.mode)))
+		return false;
 
 	/* Reject name conflicts */
 	if (conflict->type == GIT_MERGE_DIFF_BOTH_RENAMED_2_TO_1 ||
 		conflict->type == GIT_MERGE_DIFF_RENAMED_ADDED)
-		return 0;
+		return false;
 
 	if ((conflict->our_status & GIT_DELTA_RENAMED) == GIT_DELTA_RENAMED &&
 		(conflict->their_status & GIT_DELTA_RENAMED) == GIT_DELTA_RENAMED &&
 		strcmp(conflict->ancestor_entry.path, conflict->their_entry.path) != 0)
+		return false;
+
+	return true;
+}
+
+static int merge_conflict_invoke_driver(
+	git_index_entry **out,
+	const char *name,
+	git_merge_driver *driver,
+	git_merge_diff_list *diff_list,
+	git_merge_driver_source *src)
+{
+	git_index_entry *result;
+	git_buf buf = GIT_BUF_INIT;
+	const char *path;
+	uint32_t mode;
+	git_odb *odb = NULL;
+	git_oid oid;
+	int error;
+
+	*out = NULL;
+
+	if ((error = driver->apply(driver, &path, &mode, &buf, name, src)) < 0 ||
+		(error = git_repository_odb(&odb, src->repo)) < 0 ||
+		(error = git_odb_write(&oid, odb, buf.ptr, buf.size, GIT_OBJ_BLOB)) < 0)
+		goto done;
+
+	result = git_pool_mallocz(&diff_list->pool, sizeof(git_index_entry));
+	GITERR_CHECK_ALLOC(result);
+
+	git_oid_cpy(&result->id, &oid);
+	result->mode = mode;
+	result->file_size = buf.size;
+
+	result->path = git_pool_strdup(&diff_list->pool, path);
+	GITERR_CHECK_ALLOC(result->path);
+
+	*out = result;
+
+done:
+	git_buf_free(&buf);
+	git_odb_free(odb);
+
+	return error;
+}
+
+static int merge_conflict_resolve_contents(
+	int *resolved,
+	git_merge_diff_list *diff_list,
+	const git_merge_diff *conflict,
+	const git_merge_options *merge_opts,
+	const git_merge_file_options *file_opts)
+{
+	git_merge_driver_source source = {0};
+	git_merge_file_result result = {0};
+	git_merge_driver *driver;
+	git_merge_driver__builtin builtin = {{0}};
+	git_index_entry *merge_result;
+	git_odb *odb = NULL;
+	const char *name;
+	bool fallback = false;
+	int error;
+
+	assert(resolved && diff_list && conflict);
+
+	*resolved = 0;
+
+	if (!merge_conflict_can_resolve_contents(conflict))
 		return 0;
 
-	ancestor = GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->ancestor_entry) ?
+	source.repo = diff_list->repo;
+	source.default_driver = merge_opts->default_driver;
+	source.file_opts = file_opts;
+	source.ancestor = GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->ancestor_entry) ?
 		&conflict->ancestor_entry : NULL;
-	ours = GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->our_entry) ?
+	source.ours = GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->our_entry) ?
 		&conflict->our_entry : NULL;
-	theirs = GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->their_entry) ?
+	source.theirs = GIT_MERGE_INDEX_ENTRY_EXISTS(conflict->their_entry) ?
 		&conflict->their_entry : NULL;
 
-	if ((error = git_repository_odb(&odb, diff_list->repo)) < 0 ||
-		(error = git_merge_file_from_index(&result, diff_list->repo, ancestor, ours, theirs, file_opts)) < 0 ||
-		(!result.automergeable && !(file_opts->flags & GIT_MERGE_FILE_FAVOR__CONFLICTED)) ||
-		(error = git_odb_write(&automerge_oid, odb, result.ptr, result.len, GIT_OBJ_BLOB)) < 0)
-		goto done;
+	if (file_opts->favor != GIT_MERGE_FILE_FAVOR_NORMAL) {
+		/* if the user requested a particular type of resolution (via the
+		 * favor flag) then let that override the gitattributes and use
+		 * the builtin driver.
+		 */
+		name = "text";
+		builtin.base.apply = git_merge_driver__builtin_apply;
+		builtin.favor = file_opts->favor;
+
+		driver = &builtin.base;
+	} else {
+		/* find the merge driver for this file */
+		if ((error = git_merge_driver_for_source(&name, &driver, &source)) < 0)
+			goto done;
+
+		if (driver == NULL)
+			fallback = true;
+	}
 
-	if ((index_entry = git_pool_mallocz(&diff_list->pool, sizeof(git_index_entry))) == NULL)
-	GITERR_CHECK_ALLOC(index_entry);
+	if (driver) {
+		error = merge_conflict_invoke_driver(&merge_result, name, driver,
+			diff_list, &source);
 
-	index_entry->path = git_pool_strdup(&diff_list->pool, result.path);
-	GITERR_CHECK_ALLOC(index_entry->path);
+		if (error == GIT_PASSTHROUGH)
+			fallback = true;
+	}
 
-	index_entry->file_size = result.len;
-	index_entry->mode = result.mode;
-	git_oid_cpy(&index_entry->id, &automerge_oid);
+	if (fallback) {
+		error = merge_conflict_invoke_driver(&merge_result, "text",
+			&git_merge_driver__text.base, diff_list, &source);
+	}
 
-	git_vector_insert(&diff_list->staged, index_entry);
+	if (error < 0) {
+		if (error == GIT_EMERGECONFLICT)
+			error = 0;
+
+		goto done;
+	}
+
+	git_vector_insert(&diff_list->staged, merge_result);
 	git_vector_insert(&diff_list->resolved, (git_merge_diff *)conflict);
 
 	*resolved = 1;
@@ -895,6 +966,7 @@ static int merge_conflict_resolve(
 	int *out,
 	git_merge_diff_list *diff_list,
 	const git_merge_diff *conflict,
+	const git_merge_options *merge_opts,
 	const git_merge_file_options *file_opts)
 {
 	int resolved = 0;
@@ -902,16 +974,20 @@ static int merge_conflict_resolve(
 
 	*out = 0;
 
-	if ((error = merge_conflict_resolve_trivial(&resolved, diff_list, conflict)) < 0)
+	if ((error = merge_conflict_resolve_trivial(
+			&resolved, diff_list, conflict)) < 0)
 		goto done;
 
-	if (!resolved && (error = merge_conflict_resolve_one_removed(&resolved, diff_list, conflict)) < 0)
+	if (!resolved && (error = merge_conflict_resolve_one_removed(
+			&resolved, diff_list, conflict)) < 0)
 		goto done;
 
-	if (!resolved && (error = merge_conflict_resolve_one_renamed(&resolved, diff_list, conflict)) < 0)
+	if (!resolved && (error = merge_conflict_resolve_one_renamed(
+			&resolved, diff_list, conflict)) < 0)
 		goto done;
 
-	if (!resolved && (error = merge_conflict_resolve_automerge(&resolved, diff_list, conflict, file_opts)) < 0)
+	if (!resolved && (error = merge_conflict_resolve_contents(
+			&resolved, diff_list, conflict, merge_opts, file_opts)) < 0)
 		goto done;
 
 	*out = resolved;
@@ -1627,6 +1703,7 @@ static int merge_normalize_opts(
 	const git_merge_options *given)
 {
 	git_config *cfg = NULL;
+	git_config_entry *entry = NULL;
 	int error = 0;
 
 	assert(repo && opts);
@@ -1644,6 +1721,22 @@ static int merge_normalize_opts(
 		opts->rename_threshold = GIT_MERGE_DEFAULT_RENAME_THRESHOLD;
 	}
 
+	if (given && given->default_driver) {
+		opts->default_driver = git__strdup(given->default_driver);
+		GITERR_CHECK_ALLOC(opts->default_driver);
+	} else {
+		error = git_config_get_entry(&entry, cfg, "merge.default");
+
+		if (error == 0) {
+			opts->default_driver = git__strdup(entry->value);
+			GITERR_CHECK_ALLOC(opts->default_driver);
+		} else if (error == GIT_ENOTFOUND) {
+			error = 0;
+		} else {
+			goto done;
+		}
+	}
+
 	if (!opts->target_limit) {
 		int limit = git_config__get_int_force(cfg, "merge.renamelimit", 0);
 
@@ -1666,7 +1759,9 @@ static int merge_normalize_opts(
 		opts->metric->payload = (void *)GIT_HASHSIG_SMART_WHITESPACE;
 	}
 
-	return 0;
+done:
+	git_config_entry_free(entry);
+	return error;
 }
 
 
@@ -1878,7 +1973,7 @@ int git_merge__iterators(
 		int resolved = 0;
 
 		if ((error = merge_conflict_resolve(
-			&resolved, diff_list, conflict, &file_opts)) < 0)
+			&resolved, diff_list, conflict, &opts, &file_opts)) < 0)
 			goto done;
 
 		if (!resolved) {
@@ -1899,6 +1994,8 @@ done:
 	if (!given_opts || !given_opts->metric)
 		git__free(opts.metric);
 
+	git__free((char *)opts.default_driver);
+
 	git_merge_diff_list__free(diff_list);
 	git_iterator_free(empty_ancestor);
 	git_iterator_free(empty_ours);
@@ -2111,14 +2208,14 @@ static int merge_annotated_commits(
 	git_iterator *base_iter = NULL, *our_iter = NULL, *their_iter = NULL;
 	int error;
 
-    if ((error = compute_base(&base, repo, ours, theirs, opts,
+	if ((error = compute_base(&base, repo, ours, theirs, opts,
 		recursion_level)) < 0) {
 
-        if (error != GIT_ENOTFOUND)
-            goto done;
+		if (error != GIT_ENOTFOUND)
+			goto done;
 
-        giterr_clear();
-    }
+		giterr_clear();
+	}
 
 	if ((error = iterator_for_annotated_commit(&base_iter, base)) < 0 ||
 		(error = iterator_for_annotated_commit(&our_iter, ours)) < 0 ||
diff --git a/src/merge.h b/src/merge.h
index bd839be..f8cac16 100644
--- a/src/merge.h
+++ b/src/merge.h
@@ -12,8 +12,9 @@
 #include "pool.h"
 #include "iterator.h"
 
-#include "git2/merge.h"
 #include "git2/types.h"
+#include "git2/merge.h"
+#include "git2/sys/merge.h"
 
 #define GIT_MERGE_MSG_FILE		"MERGE_MSG"
 #define GIT_MERGE_MODE_FILE		"MERGE_MODE"
@@ -22,6 +23,19 @@
 #define GIT_MERGE_DEFAULT_RENAME_THRESHOLD	50
 #define GIT_MERGE_DEFAULT_TARGET_LIMIT		1000
 
+
+/** Internal merge flags. */
+enum {
+	/** The merge is for a virtual base in a recursive merge. */
+	GIT_MERGE__VIRTUAL_BASE = (1 << 31),
+};
+
+enum {
+	/** Accept the conflict file, staging it as the merge result. */
+	GIT_MERGE_FILE_FAVOR__CONFLICTED = 4,
+};
+
+
 /** Types of changes when files are merged from branch to branch. */
 typedef enum {
 	/* No conflict - a change only occurs in one branch. */
@@ -70,7 +84,6 @@ typedef enum {
 	GIT_MERGE_DIFF_DF_CHILD = (1 << 11),
 } git_merge_diff_type_t;
 
-
 typedef struct {
 	git_repository *repo;
 	git_pool pool;
@@ -152,4 +165,50 @@ int git_merge__check_result(git_repository *repo, git_index *index_new);
 
 int git_merge__append_conflicts_to_merge_msg(git_repository *repo, git_index *index);
 
+/* Merge files */
+
+GIT_INLINE(const char *) git_merge_file__best_path(
+	const char *ancestor,
+	const char *ours,
+	const char *theirs)
+{
+	if (!ancestor) {
+		if (ours && theirs && strcmp(ours, theirs) == 0)
+			return ours;
+
+		return NULL;
+	}
+
+	if (ours && strcmp(ancestor, ours) == 0)
+		return theirs;
+	else if(theirs && strcmp(ancestor, theirs) == 0)
+		return ours;
+
+	return NULL;
+}
+
+GIT_INLINE(uint32_t) git_merge_file__best_mode(
+	uint32_t ancestor, uint32_t ours, uint32_t theirs)
+{
+	/*
+	 * If ancestor didn't exist and either ours or theirs is executable,
+	 * assume executable.  Otherwise, if any mode changed from the ancestor,
+	 * use that one.
+	 */
+	if (!ancestor) {
+		if (ours == GIT_FILEMODE_BLOB_EXECUTABLE ||
+			theirs == GIT_FILEMODE_BLOB_EXECUTABLE)
+			return GIT_FILEMODE_BLOB_EXECUTABLE;
+
+		return GIT_FILEMODE_BLOB;
+	} else if (ours && theirs) {
+		if (ancestor == ours)
+			return theirs;
+
+		return ours;
+	}
+
+	return 0;
+}
+
 #endif
diff --git a/src/merge_driver.c b/src/merge_driver.c
new file mode 100644
index 0000000..cc039db
--- /dev/null
+++ b/src/merge_driver.c
@@ -0,0 +1,396 @@
+/*
+ * Copyright (C) the libgit2 contributors. All rights reserved.
+ *
+ * This file is part of libgit2, distributed under the GNU GPL v2 with
+ * a Linking Exception. For full terms see the included COPYING file.
+ */
+
+#include "common.h"
+#include "vector.h"
+#include "global.h"
+#include "merge.h"
+#include "merge_driver.h"
+#include "git2/merge.h"
+#include "git2/sys/merge.h"
+
+static const char *merge_driver_name__text = "text";
+static const char *merge_driver_name__union = "union";
+static const char *merge_driver_name__binary = "binary";
+
+struct merge_driver_registry {
+	git_rwlock lock;
+	git_vector drivers;
+};
+
+typedef struct {
+	git_merge_driver *driver;
+	int initialized;
+	char name[GIT_FLEX_ARRAY];
+} git_merge_driver_entry;
+
+static struct merge_driver_registry merge_driver_registry;
+
+static void git_merge_driver_global_shutdown(void);
+
+
+int git_merge_driver__builtin_apply(
+	git_merge_driver *self,
+	const char **path_out,
+	uint32_t *mode_out,
+	git_buf *merged_out,
+	const char *filter_name,
+	const git_merge_driver_source *src)
+{
+	git_merge_driver__builtin *driver = (git_merge_driver__builtin *)self;
+	git_merge_file_options file_opts = GIT_MERGE_FILE_OPTIONS_INIT;
+	git_merge_file_result result = {0};
+	int error;
+
+	GIT_UNUSED(filter_name);
+
+	if (src->file_opts)
+		memcpy(&file_opts, src->file_opts, sizeof(git_merge_file_options));
+
+	if (driver->favor)
+		file_opts.favor = driver->favor;
+
+	if ((error = git_merge_file_from_index(&result, src->repo,
+		src->ancestor, src->ours, src->theirs, &file_opts)) < 0)
+		goto done;
+
+	if (!result.automergeable &&
+		!(file_opts.flags & GIT_MERGE_FILE_FAVOR__CONFLICTED)) {
+		error = GIT_EMERGECONFLICT;
+		goto done;
+	}
+
+	*path_out = git_merge_file__best_path(
+		src->ancestor ? src->ancestor->path : NULL,
+		src->ours ? src->ours->path : NULL,
+		src->theirs ? src->theirs->path : NULL);
+
+	*mode_out = git_merge_file__best_mode(
+		src->ancestor ? src->ancestor->mode : 0,
+		src->ours ? src->ours->mode : 0,
+		src->theirs ? src->theirs->mode : 0);
+
+	merged_out->ptr = (char *)result.ptr;
+	merged_out->size = result.len;
+	merged_out->asize = result.len;
+	result.ptr = NULL;
+
+done:
+	git_merge_file_result_free(&result);
+	return error;
+}
+
+static int merge_driver_binary_apply(
+	git_merge_driver *self,
+	const char **path_out,
+	uint32_t *mode_out,
+	git_buf *merged_out,
+	const char *filter_name,
+	const git_merge_driver_source *src)
+{
+	GIT_UNUSED(self);
+	GIT_UNUSED(path_out);
+	GIT_UNUSED(mode_out);
+	GIT_UNUSED(merged_out);
+	GIT_UNUSED(filter_name);
+	GIT_UNUSED(src);
+
+	return GIT_EMERGECONFLICT;
+}
+
+static int merge_driver_entry_cmp(const void *a, const void *b)
+{
+	const git_merge_driver_entry *entry_a = a;
+	const git_merge_driver_entry *entry_b = b;
+
+	return strcmp(entry_a->name, entry_b->name);
+}
+
+static int merge_driver_entry_search(const void *a, const void *b)
+{
+	const char *name_a = a;
+	const git_merge_driver_entry *entry_b = b;
+
+	return strcmp(name_a, entry_b->name);
+}
+
+git_merge_driver__builtin git_merge_driver__text = {
+	{
+		GIT_MERGE_DRIVER_VERSION,
+		NULL,
+		NULL,
+		git_merge_driver__builtin_apply,
+	},
+	GIT_MERGE_FILE_FAVOR_NORMAL
+};
+
+git_merge_driver__builtin git_merge_driver__union = {
+	{
+		GIT_MERGE_DRIVER_VERSION,
+		NULL,
+		NULL,
+		git_merge_driver__builtin_apply,
+	},
+	GIT_MERGE_FILE_FAVOR_UNION
+};
+
+git_merge_driver git_merge_driver__binary = {
+	GIT_MERGE_DRIVER_VERSION,
+	NULL,
+	NULL,
+	merge_driver_binary_apply
+};
+
+/* Note: callers must lock the registry before calling this function */
+static int merge_driver_registry_insert(
+	const char *name, git_merge_driver *driver)
+{
+	git_merge_driver_entry *entry;
+
+	entry = git__calloc(1, sizeof(git_merge_driver_entry) + strlen(name) + 1);
+	GITERR_CHECK_ALLOC(entry);
+
+	strcpy(entry->name, name);
+	entry->driver = driver;
+
+	return git_vector_insert_sorted(
+		&merge_driver_registry.drivers, entry, NULL);
+}
+
+int git_merge_driver_global_init(void)
+{
+	int error;
+
+	if (git_rwlock_init(&merge_driver_registry.lock) < 0)
+		return -1;
+
+	if ((error = git_vector_init(&merge_driver_registry.drivers, 3,
+		merge_driver_entry_cmp)) < 0)
+		goto done;
+
+	if ((error = merge_driver_registry_insert(
+			merge_driver_name__text, &git_merge_driver__text.base)) < 0 ||
+		(error = merge_driver_registry_insert(
+			merge_driver_name__union, &git_merge_driver__union.base)) < 0 ||
+		(error = merge_driver_registry_insert(
+			merge_driver_name__binary, &git_merge_driver__binary)) < 0)
+
+	git__on_shutdown(git_merge_driver_global_shutdown);
+
+done:
+	if (error < 0)
+		git_vector_free_deep(&merge_driver_registry.drivers);
+
+	return error;
+}
+
+static void git_merge_driver_global_shutdown(void)
+{
+	git_merge_driver_entry *entry;
+	size_t i;
+
+	if (git_rwlock_wrlock(&merge_driver_registry.lock) < 0)
+		return;
+
+	git_vector_foreach(&merge_driver_registry.drivers, i, entry) {
+		if (entry->driver->shutdown)
+			entry->driver->shutdown(entry->driver);
+
+		git__free(entry);
+	}
+
+	git_vector_free(&merge_driver_registry.drivers);
+
+	git_rwlock_wrunlock(&merge_driver_registry.lock);
+	git_rwlock_free(&merge_driver_registry.lock);
+}
+
+/* Note: callers must lock the registry before calling this function */
+static int merge_driver_registry_find(size_t *pos, const char *name)
+{
+	return git_vector_search2(pos, &merge_driver_registry.drivers,
+		merge_driver_entry_search, name);
+}
+
+/* Note: callers must lock the registry before calling this function */
+static git_merge_driver_entry *merge_driver_registry_lookup(
+	size_t *pos, const char *name)
+{
+	git_merge_driver_entry *entry = NULL;
+
+	if (!merge_driver_registry_find(pos, name))
+		entry = git_vector_get(&merge_driver_registry.drivers, *pos);
+
+	return entry;
+}
+
+int git_merge_driver_register(const char *name, git_merge_driver *driver)
+{
+	int error;
+
+	assert(name && driver);
+
+	if (git_rwlock_wrlock(&merge_driver_registry.lock) < 0) {
+		giterr_set(GITERR_OS, "failed to lock merge driver registry");
+		return -1;
+	}
+
+	if (!merge_driver_registry_find(NULL, name)) {
+		giterr_set(GITERR_MERGE, "attempt to reregister existing driver '%s'",
+			name);
+		error = GIT_EEXISTS;
+		goto done;
+	}
+
+	error = merge_driver_registry_insert(name, driver);
+
+done:
+	git_rwlock_wrunlock(&merge_driver_registry.lock);
+	return error;
+}
+
+int git_merge_driver_unregister(const char *name)
+{
+	git_merge_driver_entry *entry;
+	size_t pos;
+	int error = 0;
+
+	if (git_rwlock_wrlock(&merge_driver_registry.lock) < 0) {
+		giterr_set(GITERR_OS, "failed to lock merge driver registry");
+		return -1;
+	}
+
+	if ((entry = merge_driver_registry_lookup(&pos, name)) == NULL) {
+		giterr_set(GITERR_MERGE, "cannot find merge driver '%s' to unregister",
+			name);
+		error = GIT_ENOTFOUND;
+		goto done;
+	}
+
+	git_vector_remove(&merge_driver_registry.drivers, pos);
+
+	if (entry->initialized && entry->driver->shutdown) {
+		entry->driver->shutdown(entry->driver);
+		entry->initialized = false;
+	}
+
+	git__free(entry);
+
+done:
+	git_rwlock_wrunlock(&merge_driver_registry.lock);
+	return error;
+}
+
+git_merge_driver *git_merge_driver_lookup(const char *name)
+{
+	git_merge_driver_entry *entry;
+	size_t pos;
+	int error;
+
+	/* If we've decided the merge driver to use internally - and not
+	 * based on user configuration (in merge_driver_name_for_path)
+	 * then we can use a hardcoded name to compare instead of bothering
+	 * to take a lock and look it up in the vector.
+	 */
+	if (name == merge_driver_name__text)
+		return &git_merge_driver__text.base;
+	else if (name == merge_driver_name__binary)
+		return &git_merge_driver__binary;
+
+	if (git_rwlock_rdlock(&merge_driver_registry.lock) < 0) {
+		giterr_set(GITERR_OS, "failed to lock merge driver registry");
+		return NULL;
+	}
+
+	entry = merge_driver_registry_lookup(&pos, name);
+
+	git_rwlock_rdunlock(&merge_driver_registry.lock);
+
+	if (entry == NULL) {
+		giterr_set(GITERR_MERGE, "cannot use an unregistered filter");
+		return NULL;
+	}
+
+	if (!entry->initialized) {
+		if (entry->driver->initialize &&
+			(error = entry->driver->initialize(entry->driver)) < 0)
+			return NULL;
+
+		entry->initialized = 1;
+	}
+
+	return entry->driver;
+}
+
+static int merge_driver_name_for_path(
+	const char **out,
+	git_repository *repo,
+	const char *path,
+	const char *default_driver)
+{
+	const char *value;
+	int error;
+
+	*out = NULL;
+
+	if ((error = git_attr_get(&value, repo, 0, path, "merge")) < 0)
+		return error;
+
+	/* set: use the built-in 3-way merge driver ("text") */
+	if (GIT_ATTR_TRUE(value))
+		*out = merge_driver_name__text;
+
+	/* unset: do not merge ("binary") */
+	else if (GIT_ATTR_FALSE(value))
+		*out = merge_driver_name__binary;
+
+	else if (GIT_ATTR_UNSPECIFIED(value) && default_driver)
+		*out = default_driver;
+
+	else if (GIT_ATTR_UNSPECIFIED(value))
+		*out = merge_driver_name__text;
+
+	else
+		*out = value;
+
+	return 0;
+}
+
+
+GIT_INLINE(git_merge_driver *) merge_driver_lookup_with_wildcard(
+	const char *name)
+{
+	git_merge_driver *driver = git_merge_driver_lookup(name);
+
+	if (driver == NULL)
+		driver = git_merge_driver_lookup("*");
+
+	return driver;
+}
+
+int git_merge_driver_for_source(
+	const char **name_out,
+	git_merge_driver **driver_out,
+	const git_merge_driver_source *src)
+{
+	const char *path, *driver_name;
+	int error = 0;
+
+	path = git_merge_file__best_path(
+		src->ancestor ? src->ancestor->path : NULL,
+		src->ours ? src->ours->path : NULL,
+		src->theirs ? src->theirs->path : NULL);
+
+	if ((error = merge_driver_name_for_path(
+			&driver_name, src->repo, path, src->default_driver)) < 0)
+		return error;
+
+	*name_out = driver_name;
+	*driver_out = merge_driver_lookup_with_wildcard(driver_name);
+	return error;
+}
+
diff --git a/src/merge_driver.h b/src/merge_driver.h
new file mode 100644
index 0000000..bde2750
--- /dev/null
+++ b/src/merge_driver.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) the libgit2 contributors. All rights reserved.
+ *
+ * This file is part of libgit2, distributed under the GNU GPL v2 with
+ * a Linking Exception. For full terms see the included COPYING file.
+ */
+#ifndef INCLUDE_merge_driver_h__
+#define INCLUDE_merge_driver_h__
+
+#include "git2/merge.h"
+#include "git2/index.h"
+#include "git2/sys/merge.h"
+
+struct git_merge_driver_source {
+	git_repository *repo;
+	const char *default_driver;
+	const git_merge_file_options *file_opts;
+
+	const git_index_entry *ancestor;
+	const git_index_entry *ours;
+	const git_index_entry *theirs;
+};
+
+typedef struct git_merge_driver__builtin {
+	git_merge_driver base;
+	git_merge_file_favor_t favor;
+} git_merge_driver__builtin;
+
+extern int git_merge_driver_global_init(void);
+
+extern int git_merge_driver_for_path(
+	char **name_out,
+	git_merge_driver **driver_out,
+	git_repository *repo,
+	const char *path);
+
+/* Merge driver configuration */
+extern int git_merge_driver_for_source(
+	const char **name_out,
+	git_merge_driver **driver_out,
+	const git_merge_driver_source *src);
+
+extern int git_merge_driver__builtin_apply(
+	git_merge_driver *self,
+	const char **path_out,
+	uint32_t *mode_out,
+	git_buf *merged_out,
+	const char *filter_name,
+	const git_merge_driver_source *src);
+
+/* Merge driver for text files, performs a standard three-way merge */
+extern git_merge_driver__builtin git_merge_driver__text;
+
+/* Merge driver for union-style merging */
+extern git_merge_driver__builtin git_merge_driver__union;
+
+/* Merge driver for unmergeable (binary) files: always produces conflicts */
+extern git_merge_driver git_merge_driver__binary;
+
+#endif
diff --git a/src/merge_file.c b/src/merge_file.c
index 6d47380..731f4b7 100644
--- a/src/merge_file.c
+++ b/src/merge_file.c
@@ -11,6 +11,7 @@
 #include "fileops.h"
 #include "index.h"
 #include "diff_xdiff.h"
+#include "merge.h"
 
 #include "git2/repository.h"
 #include "git2/object.h"
@@ -26,52 +27,6 @@
 
 #define GIT_MERGE_FILE_SIDE_EXISTS(X)	((X)->mode != 0)
 
-GIT_INLINE(const char *) merge_file_best_path(
-	const git_merge_file_input *ancestor,
-	const git_merge_file_input *ours,
-	const git_merge_file_input *theirs)
-{
-	if (!ancestor) {
-		if (ours && theirs && strcmp(ours->path, theirs->path) == 0)
-			return ours->path;
-
-		return NULL;
-	}
-
-	if (ours && strcmp(ancestor->path, ours->path) == 0)
-		return theirs ? theirs->path : NULL;
-	else if(theirs && strcmp(ancestor->path, theirs->path) == 0)
-		return ours ? ours->path : NULL;
-
-	return NULL;
-}
-
-GIT_INLINE(int) merge_file_best_mode(
-	const git_merge_file_input *ancestor,
-	const git_merge_file_input *ours,
-	const git_merge_file_input *theirs)
-{
-	/*
-	 * If ancestor didn't exist and either ours or theirs is executable,
-	 * assume executable.  Otherwise, if any mode changed from the ancestor,
-	 * use that one.
-	 */
-	if (!ancestor) {
-		if ((ours && ours->mode == GIT_FILEMODE_BLOB_EXECUTABLE) ||
-			(theirs && theirs->mode == GIT_FILEMODE_BLOB_EXECUTABLE))
-			return GIT_FILEMODE_BLOB_EXECUTABLE;
-
-		return GIT_FILEMODE_BLOB;
-	} else if (ours && theirs) {
-		if (ancestor->mode == ours->mode)
-			return theirs->mode;
-
-		return ours->mode;
-	}
-
-	return 0;
-}
-
 int git_merge_file__input_from_index(
 	git_merge_file_input *input_out,
 	git_odb_object **odb_object_out,
@@ -177,8 +132,12 @@ static int merge_file__xdiff(
 		goto done;
 	}
 
-	if ((path = merge_file_best_path(ancestor, ours, theirs)) != NULL &&
-		(out->path = strdup(path)) == NULL) {
+	path = git_merge_file__best_path(
+		ancestor ? ancestor->path : NULL,
+		ours ? ours->path : NULL,
+		theirs ? theirs->path : NULL);
+
+	if (path != NULL && (out->path = git__strdup(path)) == NULL) {
 		error = -1;
 		goto done;
 	}
@@ -186,7 +145,10 @@ static int merge_file__xdiff(
 	out->automergeable = (xdl_result == 0);
 	out->ptr = (const char *)mmbuffer.ptr;
 	out->len = mmbuffer.size;
-	out->mode = merge_file_best_mode(ancestor, ours, theirs);
+	out->mode = git_merge_file__best_mode(
+		ancestor ? ancestor->mode : 0,
+		ours ? ours->mode : 0,
+		theirs ? theirs->mode : 0);
 
 done:
 	if (error < 0)
diff --git a/tests/merge/driver.c b/tests/merge/driver.c
new file mode 100644
index 0000000..c75a007
--- /dev/null
+++ b/tests/merge/driver.c
@@ -0,0 +1,388 @@
+#include "clar_libgit2.h"
+#include "git2/repository.h"
+#include "git2/merge.h"
+#include "buffer.h"
+#include "merge.h"
+
+#define TEST_REPO_PATH "merge-resolve"
+#define BRANCH_ID "7cb63eed597130ba4abb87b3e544b85021905520"
+
+#define AUTOMERGEABLE_IDSTR "f2e1550a0c9e53d5811175864a29536642ae3821"
+
+static git_repository *repo;
+static git_index *repo_index;
+static git_oid automergeable_id;
+
+static void test_drivers_register(void);
+static void test_drivers_unregister(void);
+
+void test_merge_driver__initialize(void)
+{
+    git_config *cfg;
+
+    repo = cl_git_sandbox_init(TEST_REPO_PATH);
+    git_repository_index(&repo_index, repo);
+
+	git_oid_fromstr(&automergeable_id, AUTOMERGEABLE_IDSTR);
+
+    /* Ensure that the user's merge.conflictstyle doesn't interfere */
+    cl_git_pass(git_repository_config(&cfg, repo));
+
+    cl_git_pass(git_config_set_string(cfg, "merge.conflictstyle", "merge"));
+    cl_git_pass(git_config_set_bool(cfg, "core.autocrlf", false));
+
+	test_drivers_register();
+
+    git_config_free(cfg);
+}
+
+void test_merge_driver__cleanup(void)
+{
+	test_drivers_unregister();
+
+    git_index_free(repo_index);
+	cl_git_sandbox_cleanup();
+}
+
+struct test_merge_driver {
+	git_merge_driver base;
+	int initialized;
+	int shutdown;
+};
+
+static int test_driver_init(git_merge_driver *s)
+{
+	struct test_merge_driver *self = (struct test_merge_driver *)s;
+	self->initialized = 1;
+	return 0;
+}
+
+static void test_driver_shutdown(git_merge_driver *s)
+{
+	struct test_merge_driver *self = (struct test_merge_driver *)s;
+	self->shutdown = 1;
+}
+
+static int test_driver_apply(
+	git_merge_driver *s,
+	const char **path_out,
+	uint32_t *mode_out,
+	git_buf *merged_out,
+	const char *filter_name,
+	const git_merge_driver_source *src)
+{
+	GIT_UNUSED(s);
+	GIT_UNUSED(src);
+
+	*path_out = "applied.txt";
+	*mode_out = GIT_FILEMODE_BLOB;
+
+	return git_buf_printf(merged_out, "This is the `%s` driver.\n",
+		filter_name);
+}
+
+static struct test_merge_driver test_driver_custom = {
+	{
+		GIT_MERGE_DRIVER_VERSION,
+		test_driver_init,
+		test_driver_shutdown,
+		test_driver_apply,
+	},
+	0,
+	0,
+};
+
+static struct test_merge_driver test_driver_wildcard = {
+	{
+		GIT_MERGE_DRIVER_VERSION,
+		test_driver_init,
+		test_driver_shutdown,
+		test_driver_apply,
+	},
+	0,
+	0,
+};
+
+static void test_drivers_register(void)
+{
+	cl_git_pass(git_merge_driver_register("custom", &test_driver_custom.base));
+	cl_git_pass(git_merge_driver_register("*", &test_driver_wildcard.base));
+}
+
+static void test_drivers_unregister(void)
+{
+	cl_git_pass(git_merge_driver_unregister("custom"));
+	cl_git_pass(git_merge_driver_unregister("*"));
+}
+
+static void set_gitattributes_to(const char *driver)
+{
+	git_buf line = GIT_BUF_INIT;
+
+	if (driver && strcmp(driver, ""))
+		git_buf_printf(&line, "automergeable.txt merge=%s\n", driver);
+	else if (driver)
+		git_buf_printf(&line, "automergeable.txt merge\n");
+	else
+		git_buf_printf(&line, "automergeable.txt -merge\n");
+
+	cl_assert(!git_buf_oom(&line));
+
+	cl_git_mkfile(TEST_REPO_PATH "/.gitattributes", line.ptr);
+	git_buf_free(&line);
+}
+
+static void merge_branch(void)
+{
+	git_oid their_id;
+	git_annotated_commit *their_head;
+
+	cl_git_pass(git_oid_fromstr(&their_id, BRANCH_ID));
+	cl_git_pass(git_annotated_commit_lookup(&their_head, repo, &their_id));
+
+	cl_git_pass(git_merge(repo, (const git_annotated_commit **)&their_head,
+		1, NULL, NULL));
+
+	git_annotated_commit_free(their_head);
+}
+
+void test_merge_driver__custom(void)
+{
+	const char *expected = "This is the `custom` driver.\n";
+	set_gitattributes_to("custom");
+	merge_branch();
+
+	cl_assert_equal_file(expected, strlen(expected),
+		TEST_REPO_PATH "/applied.txt");
+}
+
+void test_merge_driver__wildcard(void)
+{
+	const char *expected = "This is the `foobar` driver.\n";
+	set_gitattributes_to("foobar");
+	merge_branch();
+
+	cl_assert_equal_file(expected, strlen(expected),
+		TEST_REPO_PATH "/applied.txt");
+}
+
+void test_merge_driver__shutdown_is_called(void)
+{
+    test_driver_custom.initialized = 0;
+    test_driver_custom.shutdown = 0;
+    test_driver_wildcard.initialized = 0;
+    test_driver_wildcard.shutdown = 0;
+    
+    /* run the merge with the custom driver */
+    set_gitattributes_to("custom");
+    merge_branch();
+    
+	/* unregister the drivers, ensure their shutdown function is called */
+	test_drivers_unregister();
+
+    /* since the `custom` driver was used, it should have been initialized and
+     * shutdown, but the wildcard driver was not used at all and should not
+     * have been initialized or shutdown.
+     */
+	cl_assert(test_driver_custom.initialized);
+	cl_assert(test_driver_custom.shutdown);
+	cl_assert(!test_driver_wildcard.initialized);
+	cl_assert(!test_driver_wildcard.shutdown);
+
+	test_drivers_register();
+}
+
+static int defer_driver_apply(
+	git_merge_driver *s,
+	const char **path_out,
+	uint32_t *mode_out,
+	git_buf *merged_out,
+	const char *filter_name,
+	const git_merge_driver_source *src)
+{
+	GIT_UNUSED(s);
+	GIT_UNUSED(path_out);
+	GIT_UNUSED(mode_out);
+	GIT_UNUSED(merged_out);
+	GIT_UNUSED(filter_name);
+	GIT_UNUSED(src);
+
+	return GIT_PASSTHROUGH;
+}
+
+static struct test_merge_driver test_driver_defer_apply = {
+	{
+		GIT_MERGE_DRIVER_VERSION,
+		test_driver_init,
+		test_driver_shutdown,
+		defer_driver_apply,
+	},
+	0,
+	0,
+};
+
+void test_merge_driver__apply_can_defer(void)
+{
+	const git_index_entry *idx;
+
+	cl_git_pass(git_merge_driver_register("defer",
+		&test_driver_defer_apply.base));
+
+    set_gitattributes_to("defer");
+    merge_branch();
+
+	cl_assert((idx = git_index_get_bypath(repo_index, "automergeable.txt", 0)));
+	cl_assert_equal_oid(&automergeable_id, &idx->id);
+
+	git_merge_driver_unregister("defer");
+}
+
+static int conflict_driver_apply(
+	git_merge_driver *s,
+	const char **path_out,
+	uint32_t *mode_out,
+	git_buf *merged_out,
+	const char *filter_name,
+	const git_merge_driver_source *src)
+{
+	GIT_UNUSED(s);
+	GIT_UNUSED(path_out);
+	GIT_UNUSED(mode_out);
+	GIT_UNUSED(merged_out);
+	GIT_UNUSED(filter_name);
+	GIT_UNUSED(src);
+
+	return GIT_EMERGECONFLICT;
+}
+
+static struct test_merge_driver test_driver_conflict_apply = {
+	{
+		GIT_MERGE_DRIVER_VERSION,
+		test_driver_init,
+		test_driver_shutdown,
+		conflict_driver_apply,
+	},
+	0,
+	0,
+};
+
+void test_merge_driver__apply_can_conflict(void)
+{
+	const git_index_entry *ancestor, *ours, *theirs;
+
+	cl_git_pass(git_merge_driver_register("conflict",
+		&test_driver_conflict_apply.base));
+
+    set_gitattributes_to("conflict");
+    merge_branch();
+
+	cl_git_pass(git_index_conflict_get(&ancestor, &ours, &theirs,
+		repo_index, "automergeable.txt"));
+
+	git_merge_driver_unregister("conflict");
+}
+
+void test_merge_driver__default_can_be_specified(void)
+{
+	git_oid their_id;
+	git_annotated_commit *their_head;
+	git_merge_options merge_opts = GIT_MERGE_OPTIONS_INIT;
+	const char *expected = "This is the `custom` driver.\n";
+
+	merge_opts.default_driver = "custom";
+
+	cl_git_pass(git_oid_fromstr(&their_id, BRANCH_ID));
+	cl_git_pass(git_annotated_commit_lookup(&their_head, repo, &their_id));
+
+	cl_git_pass(git_merge(repo, (const git_annotated_commit **)&their_head,
+		1, &merge_opts, NULL));
+
+	git_annotated_commit_free(their_head);
+
+	cl_assert_equal_file(expected, strlen(expected),
+		TEST_REPO_PATH "/applied.txt");
+}
+
+void test_merge_driver__honors_builtin_mergedefault(void)
+{
+	const git_index_entry *ancestor, *ours, *theirs;
+
+	cl_repo_set_string(repo, "merge.default", "binary");
+	merge_branch();
+
+	cl_git_pass(git_index_conflict_get(&ancestor, &ours, &theirs,
+		repo_index, "automergeable.txt"));
+}
+
+void test_merge_driver__honors_custom_mergedefault(void)
+{
+	const char *expected = "This is the `custom` driver.\n";
+
+	cl_repo_set_string(repo, "merge.default", "custom");
+	merge_branch();
+
+	cl_assert_equal_file(expected, strlen(expected),
+		TEST_REPO_PATH "/applied.txt");
+}
+
+void test_merge_driver__mergedefault_deferring_falls_back_to_text(void)
+{
+	const git_index_entry *idx;
+
+	cl_git_pass(git_merge_driver_register("defer",
+		&test_driver_defer_apply.base));
+
+	cl_repo_set_string(repo, "merge.default", "defer");
+	merge_branch();
+
+	cl_assert((idx = git_index_get_bypath(repo_index, "automergeable.txt", 0)));
+	cl_assert_equal_oid(&automergeable_id, &idx->id);
+
+	git_merge_driver_unregister("defer");
+}
+
+void test_merge_driver__set_forces_text(void)
+{
+	const git_index_entry *idx;
+
+	/* `merge` without specifying a driver indicates `text` */
+	set_gitattributes_to("");
+	cl_repo_set_string(repo, "merge.default", "custom");
+
+	merge_branch();
+
+	cl_assert((idx = git_index_get_bypath(repo_index, "automergeable.txt", 0)));
+	cl_assert_equal_oid(&automergeable_id, &idx->id);
+}
+
+void test_merge_driver__unset_forces_binary(void)
+{
+	const git_index_entry *ancestor, *ours, *theirs;
+
+	/* `-merge` without specifying a driver indicates `binary` */
+	set_gitattributes_to(NULL);
+	cl_repo_set_string(repo, "merge.default", "custom");
+
+	merge_branch();
+
+	cl_git_pass(git_index_conflict_get(&ancestor, &ours, &theirs,
+		repo_index, "automergeable.txt"));
+}
+
+void test_merge_driver__not_configured_driver_falls_back(void)
+{
+	const git_index_entry *idx;
+
+	test_drivers_unregister();
+
+	/* `merge` without specifying a driver indicates `text` */
+	set_gitattributes_to("notfound");
+
+	merge_branch();
+
+	cl_assert((idx = git_index_get_bypath(repo_index, "automergeable.txt", 0)));
+	cl_assert_equal_oid(&automergeable_id, &idx->id);
+
+	test_drivers_register();
+}
+
diff --git a/tests/merge/workdir/simple.c b/tests/merge/workdir/simple.c
index 3cdd15b..964532e 100644
--- a/tests/merge/workdir/simple.c
+++ b/tests/merge/workdir/simple.c
@@ -330,6 +330,42 @@ void test_merge_workdir_simple__union(void)
 	cl_assert(merge_test_reuc(repo_index, merge_reuc_entries, 4));
 }
 
+void test_merge_workdir_simple__gitattributes_union(void)
+{
+	git_buf conflicting_buf = GIT_BUF_INIT;
+
+	struct merge_index_entry merge_index_entries[] = {
+		ADDED_IN_MASTER_INDEX_ENTRY,
+		AUTOMERGEABLE_INDEX_ENTRY,
+		CHANGED_IN_BRANCH_INDEX_ENTRY,
+		CHANGED_IN_MASTER_INDEX_ENTRY,
+
+		{ 0100644, "72cdb057b340205164478565e91eb71647e66891", 0, "conflicting.txt" },
+
+		UNCHANGED_INDEX_ENTRY,
+	};
+
+	struct merge_reuc_entry merge_reuc_entries[] = {
+		AUTOMERGEABLE_REUC_ENTRY,
+		CONFLICTING_REUC_ENTRY,
+		REMOVED_IN_BRANCH_REUC_ENTRY,
+		REMOVED_IN_MASTER_REUC_ENTRY
+	};
+
+	set_core_autocrlf_to(repo, false);
+	cl_git_mkfile(TEST_REPO_PATH "/.gitattributes", "conflicting.txt merge=union\n");
+
+	merge_simple_branch(GIT_MERGE_FILE_FAVOR_NORMAL, 0);
+
+	cl_git_pass(git_futils_readbuffer(&conflicting_buf,
+		TEST_REPO_PATH "/conflicting.txt"));
+	cl_assert(strcmp(conflicting_buf.ptr, CONFLICTING_UNION_FILE) == 0);
+	git_buf_free(&conflicting_buf);
+
+	cl_assert(merge_test_index(repo_index, merge_index_entries, 6));
+	cl_assert(merge_test_reuc(repo_index, merge_reuc_entries, 4));
+}
+
 void test_merge_workdir_simple__diff3_from_config(void)
 {
 	git_config *config;