Commit 5b27bf7e5bfd5c2f92a15c0058c801d49faf8403

Vicent Martí 2013-03-18T16:17:14

Merge pull request #1417 from arrbee/opts-for-paths Implement opts interface for global/system file search paths

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
diff --git a/include/git2/common.h b/include/git2/common.h
index 7066d5e..b8c3e42 100644
--- a/include/git2/common.h
+++ b/include/git2/common.h
@@ -128,7 +128,9 @@ enum {
 	GIT_OPT_GET_MWINDOW_SIZE,
 	GIT_OPT_SET_MWINDOW_SIZE,
 	GIT_OPT_GET_MWINDOW_MAPPED_LIMIT,
-	GIT_OPT_SET_MWINDOW_MAPPED_LIMIT
+	GIT_OPT_SET_MWINDOW_MAPPED_LIMIT,
+	GIT_OPT_GET_SEARCH_PATH,
+	GIT_OPT_SET_SEARCH_PATH,
 };
 
 /**
@@ -136,17 +138,40 @@ enum {
  *
  * Available options:
  *
- *	opts(GIT_OPT_MWINDOW_SIZE, size_t):
- *		set the maximum mmap window size
+ *	opts(GIT_OPT_GET_MWINDOW_SIZE, size_t *):
+ *		Get the maximum mmap window size
  *
- *	opts(GIT_OPT_MWINDOW_MAPPED_LIMIT, size_t):
- *		set the maximum amount of memory that can be mapped at any time
+ *	opts(GIT_OPT_SET_MWINDOW_SIZE, size_t):
+ *		Set the maximum mmap window size
+ *
+ *	opts(GIT_OPT_GET_MWINDOW_MAPPED_LIMIT, size_t *):
+ *		Get the maximum memory that will be mapped in total by the library
+ *
+ *	opts(GIT_OPT_SET_MWINDOW_MAPPED_LIMIT, size_t):
+ *		Set the maximum amount of memory that can be mapped at any time
  *		by the library
  *
- *	@param option Option key
- *	@param ... value to set the option
+ *	opts(GIT_OPT_GET_SEARCH_PATH, int level, char *out, size_t len)
+ *		Get the search path for a given level of config data.  "level" must
+ *		be one of GIT_CONFIG_LEVEL_SYSTEM, GIT_CONFIG_LEVEL_GLOBAL, or
+ *		GIT_CONFIG_LEVEL_XDG.  The search path is written to the `out`
+ *		buffer up to size `len`.  Returns GIT_EBUFS if buffer is too small.
+ *
+ *	opts(GIT_OPT_SET_SEARCH_PATH, int level, const char *path)
+ *		Set the search path for a level of config data.  The search path
+ *		applied to shared attributes and ignore files, too.
+ *      - `path` lists directories delimited by GIT_PATH_LIST_SEPARATOR.
+ *		  Pass NULL to reset to the default (generally based on environment
+ *		  variables).  Use magic path `$PATH` to include the old value
+ *		  of the path (if you want to prepend or append, for instance).
+ *		- `level` must be GIT_CONFIG_LEVEL_SYSTEM, GIT_CONFIG_LEVEL_GLOBAL,
+ *		  or GIT_CONFIG_LEVEL_XDG.
+ *
+ * @param option Option key
+ * @param ... value to set the option
+ * @return 0 on success, <0 on failure
  */
-GIT_EXTERN(void) git_libgit2_opts(int option, ...);
+GIT_EXTERN(int) git_libgit2_opts(int option, ...);
 
 /** @} */
 GIT_END_DECL
diff --git a/include/git2/strarray.h b/include/git2/strarray.h
index 6ea570c..d338eb7 100644
--- a/include/git2/strarray.h
+++ b/include/git2/strarray.h
@@ -43,8 +43,8 @@ GIT_EXTERN(void) git_strarray_free(git_strarray *array);
 /**
  * Copy a string array object from source to target.
  *
- * Note: target is overwritten and hence should be empty,
- * otherwise its contents are leaked.
+ * Note: target is overwritten and hence should be empty, otherwise its
+ * contents are leaked.  Call git_strarray_free() if necessary.
  *
  * @param tgt target
  * @param src source
diff --git a/src/attr.c b/src/attr.c
index 9c88771..979fecc 100644
--- a/src/attr.c
+++ b/src/attr.c
@@ -1,6 +1,8 @@
 #include "repository.h"
 #include "fileops.h"
 #include "config.h"
+#include "attr.h"
+#include "ignore.h"
 #include "git2/oid.h"
 #include <ctype.h>
 
@@ -593,17 +595,28 @@ static int collect_attr_files(
 	return error;
 }
 
-static char *try_global_default(const char *relpath)
+static int attr_cache__lookup_path(
+	const char **out, git_config *cfg, const char *key, const char *fallback)
 {
-	git_buf dflt = GIT_BUF_INIT;
-	char *rval = NULL;
+	git_buf buf = GIT_BUF_INIT;
+	int error;
 
-	if (!git_futils_find_global_file(&dflt, relpath))
-		rval = git_buf_detach(&dflt);
+	if (!(error = git_config_get_string(out, cfg, key)))
+		return 0;
 
-	git_buf_free(&dflt);
+	if (error == GIT_ENOTFOUND) {
+		giterr_clear();
+		error = 0;
 
-	return rval;
+		if (!git_futils_find_xdg_file(&buf, fallback))
+			*out = git_buf_detach(&buf);
+		else
+			*out = NULL;
+
+		git_buf_free(&buf);
+	}
+
+	return error;
 }
 
 int git_attr_cache__init(git_repository *repo)
@@ -619,19 +632,15 @@ int git_attr_cache__init(git_repository *repo)
 	if (git_repository_config__weakptr(&cfg, repo) < 0)
 		return -1;
 
-	ret = git_config_get_string(&cache->cfg_attr_file, cfg, GIT_ATTR_CONFIG);
-	if (ret < 0 && ret != GIT_ENOTFOUND)
+	ret = attr_cache__lookup_path(
+		&cache->cfg_attr_file, cfg, GIT_ATTR_CONFIG, GIT_ATTR_FILE_XDG);
+	if (ret < 0)
 		return ret;
-	if (ret == GIT_ENOTFOUND)
-		cache->cfg_attr_file = try_global_default(GIT_ATTR_CONFIG_DEFAULT);
 
-	ret = git_config_get_string(&cache->cfg_excl_file, cfg, GIT_IGNORE_CONFIG);
-	if (ret < 0 && ret != GIT_ENOTFOUND)
+	ret = attr_cache__lookup_path(
+		&cache->cfg_excl_file, cfg, GIT_IGNORE_CONFIG, GIT_IGNORE_FILE_XDG);
+	if (ret < 0)
 		return ret;
-	if (ret == GIT_ENOTFOUND)
-		cache->cfg_excl_file = try_global_default(GIT_IGNORE_CONFIG_DEFAULT);
-
-	giterr_clear();
 
 	/* allocate hashtable for attribute and ignore file contents */
 	if (cache->files == NULL) {
diff --git a/src/attr.h b/src/attr.h
index 0fc3308..19c979b 100644
--- a/src/attr.h
+++ b/src/attr.h
@@ -8,27 +8,13 @@
 #define INCLUDE_attr_h__
 
 #include "attr_file.h"
-#include "strmap.h"
-
-#define GIT_ATTR_CONFIG   "core.attributesfile"
-#define GIT_ATTR_CONFIG_DEFAULT ".config/git/attributes"
-#define GIT_IGNORE_CONFIG "core.excludesfile"
-#define GIT_IGNORE_CONFIG_DEFAULT ".config/git/ignore"
-
-typedef struct {
-	int initialized;
-	git_pool pool;
-	git_strmap *files;	/* hash path to git_attr_file of rules */
-	git_strmap *macros;	/* hash name to vector<git_attr_assignment> */
-	const char *cfg_attr_file; /* cached value of core.attributesfile */
-	const char *cfg_excl_file; /* cached value of core.excludesfile */
-} git_attr_cache;
+
+#define GIT_ATTR_CONFIG       "core.attributesfile"
+#define GIT_IGNORE_CONFIG     "core.excludesfile"
 
 typedef int (*git_attr_file_parser)(
 	git_repository *, void *, const char *, git_attr_file *);
 
-extern int git_attr_cache__init(git_repository *repo);
-
 extern int git_attr_cache__insert_macro(
 	git_repository *repo, git_attr_rule *macro);
 
diff --git a/src/attr_file.c b/src/attr_file.c
index 628cb15..74bd213 100644
--- a/src/attr_file.c
+++ b/src/attr_file.c
@@ -1,6 +1,7 @@
 #include "common.h"
 #include "repository.h"
 #include "filebuf.h"
+#include "attr.h"
 #include "git2/blob.h"
 #include "git2/tree.h"
 #include <ctype.h>
diff --git a/src/attr_file.h b/src/attr_file.h
index 8dc8303..2cc8546 100644
--- a/src/attr_file.h
+++ b/src/attr_file.h
@@ -17,6 +17,7 @@
 #define GIT_ATTR_FILE			".gitattributes"
 #define GIT_ATTR_FILE_INREPO	"info/attributes"
 #define GIT_ATTR_FILE_SYSTEM	"gitattributes"
+#define GIT_ATTR_FILE_XDG		"attributes"
 
 #define GIT_ATTR_FNMATCH_NEGATIVE	(1U << 0)
 #define GIT_ATTR_FNMATCH_DIRECTORY	(1U << 1)
diff --git a/src/attrcache.h b/src/attrcache.h
new file mode 100644
index 0000000..12cec4b
--- /dev/null
+++ b/src/attrcache.h
@@ -0,0 +1,24 @@
+/*
+ * 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_attrcache_h__
+#define INCLUDE_attrcache_h__
+
+#include "pool.h"
+#include "strmap.h"
+
+typedef struct {
+	int initialized;
+	git_pool pool;
+	git_strmap *files;	/* hash path to git_attr_file of rules */
+	git_strmap *macros;	/* hash name to vector<git_attr_assignment> */
+	const char *cfg_attr_file; /* cached value of core.attributesfile */
+	const char *cfg_excl_file; /* cached value of core.excludesfile */
+} git_attr_cache;
+
+extern int git_attr_cache__init(git_repository *repo);
+
+#endif
diff --git a/src/common.h b/src/common.h
index e3a9e19..235da04 100644
--- a/src/common.h
+++ b/src/common.h
@@ -56,6 +56,12 @@
 #define GITERR_CHECK_ALLOC(ptr) if (ptr == NULL) { return -1; }
 
 /**
+ * Check a return value and propogate result if non-zero.
+ */
+#define GITERR_CHECK_ERROR(code) \
+	do { int _err = (code); if (_err < 0) return _err; } while (0)
+
+/**
  * Set the error message for this thread, formatting as needed.
  */
 void giterr_set(int error_class, const char *string, ...);
diff --git a/src/config.c b/src/config.c
index 4439a68..5379b0e 100644
--- a/src/config.c
+++ b/src/config.c
@@ -515,62 +515,48 @@ int git_config_set_multivar(git_config *cfg, const char *name, const char *regex
 	return file->set_multivar(file, name, regexp, value);
 }
 
-int git_config_find_global_r(git_buf *path)
+static int git_config__find_file_to_path(
+	char *out, size_t outlen, int (*find)(git_buf *buf))
 {
-	int error = git_futils_find_global_file(path, GIT_CONFIG_FILENAME);
+	int error = 0;
+	git_buf path = GIT_BUF_INIT;
+
+	if ((error = find(&path)) < 0)
+		goto done;
+
+	if (path.size >= outlen) {
+		giterr_set(GITERR_NOMEMORY, "Buffer is too short for the path");
+		error = GIT_EBUFS;
+		goto done;
+	}
 
+	git_buf_copy_cstr(out, outlen, &path);
+
+done:
+	git_buf_free(&path);
 	return error;
 }
 
-int git_config_find_xdg_r(git_buf *path)
+int git_config_find_global_r(git_buf *path)
 {
-	int error = git_futils_find_global_file(path, GIT_CONFIG_FILENAME_ALT);
-
-	return error;
+	return git_futils_find_global_file(path, GIT_CONFIG_FILENAME_GLOBAL);
 }
 
 int git_config_find_global(char *global_config_path, size_t length)
 {
-	git_buf path  = GIT_BUF_INIT;
-	int     ret = git_config_find_global_r(&path);
-
-	if (ret < 0) {
-		git_buf_free(&path);
-		return ret;
-	}
-
-	if (path.size >= length) {
-		git_buf_free(&path);
-		giterr_set(GITERR_NOMEMORY,
-			"Path is to long to fit on the given buffer");
-		return -1;
-	}
+	return git_config__find_file_to_path(
+		global_config_path, length, git_config_find_global_r);
+}
 
-	git_buf_copy_cstr(global_config_path, length, &path);
-	git_buf_free(&path);
-	return 0;
+int git_config_find_xdg_r(git_buf *path)
+{
+	return git_futils_find_xdg_file(path, GIT_CONFIG_FILENAME_XDG);
 }
 
 int git_config_find_xdg(char *xdg_config_path, size_t length)
 {
-	git_buf path  = GIT_BUF_INIT;
-	int ret = git_config_find_xdg_r(&path);
-
-	if (ret < 0) {
-		git_buf_free(&path);
-		return ret;
-	}
-
-	if (path.size >= length) {
-		git_buf_free(&path);
-		giterr_set(GITERR_NOMEMORY,
-			"Path is to long to fit on the given buffer");
-		return -1;
-	}
-
-	git_buf_copy_cstr(xdg_config_path, length, &path);
-	git_buf_free(&path);
-	return 0;
+	return git_config__find_file_to_path(
+		xdg_config_path, length, git_config_find_xdg_r);
 }
 
 int git_config_find_system_r(git_buf *path)
@@ -580,24 +566,8 @@ int git_config_find_system_r(git_buf *path)
 
 int git_config_find_system(char *system_config_path, size_t length)
 {
-	git_buf path  = GIT_BUF_INIT;
-	int     ret = git_config_find_system_r(&path);
-
-	if (ret < 0) {
-		git_buf_free(&path);
-		return ret;
-	}
-
-	if (path.size >= length) {
-		git_buf_free(&path);
-		giterr_set(GITERR_NOMEMORY,
-			"Path is to long to fit on the given buffer");
-		return -1;
-	}
-
-	git_buf_copy_cstr(system_config_path, length, &path);
-	git_buf_free(&path);
-	return 0;
+	return git_config__find_file_to_path(
+		system_config_path, length, git_config_find_system_r);
 }
 
 int git_config_open_default(git_config **out)
diff --git a/src/config.h b/src/config.h
index db5ebb3..c43e47e 100644
--- a/src/config.h
+++ b/src/config.h
@@ -12,10 +12,11 @@
 #include "vector.h"
 #include "repository.h"
 
-#define GIT_CONFIG_FILENAME ".gitconfig"
-#define GIT_CONFIG_FILENAME_ALT ".config/git/config"
-#define GIT_CONFIG_FILENAME_INREPO "config"
 #define GIT_CONFIG_FILENAME_SYSTEM "gitconfig"
+#define GIT_CONFIG_FILENAME_GLOBAL ".gitconfig"
+#define GIT_CONFIG_FILENAME_XDG    "config"
+
+#define GIT_CONFIG_FILENAME_INREPO "config"
 #define GIT_CONFIG_FILE_MODE 0666
 
 struct git_config {
diff --git a/src/fileops.c b/src/fileops.c
index e33377e..d624471 100644
--- a/src/fileops.c
+++ b/src/fileops.c
@@ -558,75 +558,186 @@ clean_up:
 	return error;
 }
 
-int git_futils_find_system_file(git_buf *path, const char *filename)
+
+static int git_futils_guess_system_dirs(git_buf *out)
 {
 #ifdef GIT_WIN32
-	// try to find git.exe/git.cmd on path
-	if (!win32_find_system_file_using_path(path, filename))
-		return 0;
+	return git_win32__find_system_dirs(out);
+#else
+	return git_buf_sets(out, "/etc");
+#endif
+}
 
-	// try to find msysgit installation path using registry
-	if (!win32_find_system_file_using_registry(path, filename))
-		return 0;
+static int git_futils_guess_global_dirs(git_buf *out)
+{
+#ifdef GIT_WIN32
+	return git_win32__find_global_dirs(out);
 #else
-	if (git_buf_joinpath(path, "/etc", filename) < 0)
-		return -1;
+	return git_buf_sets(out, getenv("HOME"));
+#endif
+}
 
-	if (git_path_exists(path->ptr) == true)
-		return 0;
+static int git_futils_guess_xdg_dirs(git_buf *out)
+{
+#ifdef GIT_WIN32
+	return git_win32__find_xdg_dirs(out);
+#else
+	const char *env = NULL;
+
+	if ((env = getenv("XDG_CONFIG_HOME")) != NULL)
+		return git_buf_joinpath(out, env, "git");
+	else if ((env = getenv("HOME")) != NULL)
+		return git_buf_joinpath(out, env, ".config/git");
+
+	git_buf_clear(out);
+	return 0;
 #endif
+}
 
-	git_buf_clear(path);
-	giterr_set(GITERR_OS, "The system file '%s' doesn't exist", filename);
-	return GIT_ENOTFOUND;
+typedef int (*git_futils_dirs_guess_cb)(git_buf *out);
+
+static git_buf git_futils__dirs[GIT_FUTILS_DIR__MAX] =
+	{ GIT_BUF_INIT, GIT_BUF_INIT, GIT_BUF_INIT };
+
+static git_futils_dirs_guess_cb git_futils__dir_guess[GIT_FUTILS_DIR__MAX] = {
+	git_futils_guess_system_dirs,
+	git_futils_guess_global_dirs,
+	git_futils_guess_xdg_dirs,
+};
+
+static int git_futils_check_selector(git_futils_dir_t which)
+{
+	if (which < GIT_FUTILS_DIR__MAX)
+		return 0;
+	giterr_set(GITERR_INVALID, "config directory selector out of range");
+	return -1;
 }
 
-int git_futils_find_global_file(git_buf *path, const char *filename)
+int git_futils_dirs_get(const git_buf **out, git_futils_dir_t which)
 {
-#ifdef GIT_WIN32
-	struct win32_path root;
-	static const wchar_t *tmpls[4] = {
-		L"%HOME%\\",
-		L"%HOMEDRIVE%%HOMEPATH%\\",
-		L"%USERPROFILE%\\",
-		NULL,
-	};
-	const wchar_t **tmpl;
-
-	for (tmpl = tmpls; *tmpl != NULL; tmpl++) {
-		/* try to expand environment variable, skipping if not set */
-		if (win32_expand_path(&root, *tmpl) != 0 || root.path[0] == L'%')
+	assert(out);
+
+	*out = NULL;
+
+	GITERR_CHECK_ERROR(git_futils_check_selector(which));
+
+	if (!git_buf_len(&git_futils__dirs[which]))
+		GITERR_CHECK_ERROR(
+			git_futils__dir_guess[which](&git_futils__dirs[which]));
+
+	*out = &git_futils__dirs[which];
+	return 0;
+}
+
+int git_futils_dirs_get_str(char *out, size_t outlen, git_futils_dir_t which)
+{
+	const git_buf *path = NULL;
+
+	GITERR_CHECK_ERROR(git_futils_check_selector(which));
+	GITERR_CHECK_ERROR(git_futils_dirs_get(&path, which));
+
+	if (!out || path->size >= outlen) {
+		giterr_set(GITERR_NOMEMORY, "Buffer is too short for the path");
+		return GIT_EBUFS;
+	}
+
+	git_buf_copy_cstr(out, outlen, path);
+	return 0;
+}
+
+#define PATH_MAGIC "$PATH"
+
+int git_futils_dirs_set(git_futils_dir_t which, const char *search_path)
+{
+	const char *expand_path = NULL;
+	git_buf merge = GIT_BUF_INIT;
+
+	GITERR_CHECK_ERROR(git_futils_check_selector(which));
+
+	if (search_path != NULL)
+		expand_path = strstr(search_path, PATH_MAGIC);
+
+	/* init with default if not yet done and needed (ignoring error) */
+	if ((!search_path || expand_path) &&
+		!git_buf_len(&git_futils__dirs[which]))
+		git_futils__dir_guess[which](&git_futils__dirs[which]);
+
+	/* if $PATH is not referenced, then just set the path */
+	if (!expand_path)
+		return git_buf_sets(&git_futils__dirs[which], search_path);
+
+	/* otherwise set to join(before $PATH, old value, after $PATH) */
+	if (expand_path > search_path)
+		git_buf_set(&merge, search_path, expand_path - search_path);
+
+	if (git_buf_len(&git_futils__dirs[which]))
+		git_buf_join(&merge, GIT_PATH_LIST_SEPARATOR,
+			merge.ptr, git_futils__dirs[which].ptr);
+
+	expand_path += strlen(PATH_MAGIC);
+	if (*expand_path)
+		git_buf_join(&merge, GIT_PATH_LIST_SEPARATOR, merge.ptr, expand_path);
+
+	git_buf_swap(&git_futils__dirs[which], &merge);
+	git_buf_free(&merge);
+
+	return git_buf_oom(&git_futils__dirs[which]) ? -1 : 0;
+}
+
+void git_futils_dirs_free(void)
+{
+	int i;
+	for (i = 0; i < GIT_FUTILS_DIR__MAX; ++i)
+		git_buf_free(&git_futils__dirs[i]);
+}
+
+static int git_futils_find_in_dirlist(
+	git_buf *path, const char *name, git_futils_dir_t which, const char *label)
+{
+	size_t len;
+	const char *scan, *next = NULL;
+	const git_buf *syspath;
+
+	GITERR_CHECK_ERROR(git_futils_dirs_get(&syspath, which));
+
+	for (scan = git_buf_cstr(syspath); scan; scan = next) {
+		for (next = strchr(scan, GIT_PATH_LIST_SEPARATOR);
+			 next && next > scan && next[-1] == '\\';
+			 next = strchr(next + 1, GIT_PATH_LIST_SEPARATOR))
+			/* find unescaped separator or end of string */;
+
+		len = next ? (size_t)(next++ - scan) : strlen(scan);
+		if (!len)
 			continue;
 
-		/* try to look up file under path */
-		if (!win32_find_file(path, &root, filename))
+		GITERR_CHECK_ERROR(git_buf_set(path, scan, len));
+		GITERR_CHECK_ERROR(git_buf_joinpath(path, path->ptr, name));
+
+		if (git_path_exists(path->ptr))
 			return 0;
 	}
 
-	giterr_set(GITERR_OS, "The global file '%s' doesn't exist", filename);
 	git_buf_clear(path);
-
+	giterr_set(GITERR_OS, "The %s file '%s' doesn't exist", label, name);
 	return GIT_ENOTFOUND;
-#else
-	const char *home = getenv("HOME");
-
-	if (home == NULL) {
-		giterr_set(GITERR_OS, "Global file lookup failed. "
-			"Cannot locate the user's home directory");
-		return GIT_ENOTFOUND;
-	}
+}
 
-	if (git_buf_joinpath(path, home, filename) < 0)
-		return -1;
+int git_futils_find_system_file(git_buf *path, const char *filename)
+{
+	return git_futils_find_in_dirlist(
+		path, filename, GIT_FUTILS_DIR_SYSTEM, "system");
+}
 
-	if (git_path_exists(path->ptr) == false) {
-		giterr_set(GITERR_OS, "The global file '%s' doesn't exist", filename);
-		git_buf_clear(path);
-		return GIT_ENOTFOUND;
-	}
+int git_futils_find_global_file(git_buf *path, const char *filename)
+{
+	return git_futils_find_in_dirlist(
+		path, filename, GIT_FUTILS_DIR_GLOBAL, "global");
+}
 
-	return 0;
-#endif
+int git_futils_find_xdg_file(git_buf *path, const char *filename)
+{
+	return git_futils_find_in_dirlist(
+		path, filename, GIT_FUTILS_DIR_XDG, "global/xdg");
 }
 
 int git_futils_fake_symlink(const char *old, const char *new)
diff --git a/src/fileops.h b/src/fileops.h
index 7ba99d3..627a692 100644
--- a/src/fileops.h
+++ b/src/fileops.h
@@ -276,25 +276,72 @@ extern void git_futils_mmap_free(git_map *map);
  *
  * @param pathbuf buffer to write the full path into
  * @param filename name of file to find in the home directory
- * @return
- * - 0 if found;
- * - GIT_ENOTFOUND if not found;
- * - -1 on an unspecified OS related error.
+ * @return 0 if found, GIT_ENOTFOUND if not found, or -1 on other OS error
  */
 extern int git_futils_find_global_file(git_buf *path, const char *filename);
 
 /**
+ * Find an "XDG" file (i.e. one in user's XDG config path).
+ *
+ * @param pathbuf buffer to write the full path into
+ * @param filename name of file to find in the home directory
+ * @return 0 if found, GIT_ENOTFOUND if not found, or -1 on other OS error
+ */
+extern int git_futils_find_xdg_file(git_buf *path, const char *filename);
+
+/**
  * Find a "system" file (i.e. one shared for all users of the system).
  *
  * @param pathbuf buffer to write the full path into
  * @param filename name of file to find in the home directory
- * @return
- * - 0 if found;
- * - GIT_ENOTFOUND if not found;
- * - -1 on an unspecified OS related error.
+ * @return 0 if found, GIT_ENOTFOUND if not found, or -1 on other OS error
  */
 extern int git_futils_find_system_file(git_buf *path, const char *filename);
 
+typedef enum {
+	GIT_FUTILS_DIR_SYSTEM = 0,
+	GIT_FUTILS_DIR_GLOBAL = 1,
+	GIT_FUTILS_DIR_XDG    = 2,
+	GIT_FUTILS_DIR__MAX   = 3,
+} git_futils_dir_t;
+
+/**
+ * Get the search path for global/system/xdg files
+ *
+ * @param out pointer to git_buf containing search path
+ * @param which which list of paths to return
+ * @return 0 on success, <0 on failure
+ */
+extern int git_futils_dirs_get(const git_buf **out, git_futils_dir_t which);
+
+/**
+ * Get search path into a preallocated buffer
+ *
+ * @param out String buffer to write into
+ * @param outlen Size of string buffer
+ * @param which Which search path to return
+ * @return 0 on success, GIT_EBUFS if out is too small, <0 on other failure
+ */
+
+extern int git_futils_dirs_get_str(
+	char *out, size_t outlen, git_futils_dir_t which);
+
+/**
+ * Set search paths for global/system/xdg files
+ *
+ * The first occurrence of the magic string "$PATH" in the new value will
+ * be replaced with the old value of the search path.
+ *
+ * @param which Which search path to modify
+ * @param paths New search path (separated by GIT_PATH_LIST_SEPARATOR)
+ * @return 0 on success, <0 on failure (allocation error)
+ */
+extern int git_futils_dirs_set(git_futils_dir_t which, const char *paths);
+
+/**
+ * Release / reset all search paths
+ */
+extern void git_futils_dirs_free(void);
 
 /**
  * Create a "fake" symlink (text file containing the target path).
diff --git a/src/global.c b/src/global.c
index 4d37fa1..b7fd8e2 100644
--- a/src/global.c
+++ b/src/global.c
@@ -7,7 +7,8 @@
 #include "common.h"
 #include "global.h"
 #include "hash.h"
-#include "git2/threads.h" 
+#include "fileops.h"
+#include "git2/threads.h"
 #include "thread-utils.h"
 
 
@@ -82,6 +83,7 @@ void git_threads_shutdown(void)
 
 	/* Shut down any subsystems that have global state */
 	git_hash_global_shutdown();
+	git_futils_dirs_free();
 }
 
 git_global_st *git__global_state(void)
@@ -139,6 +141,7 @@ void git_threads_shutdown(void)
 
 	/* Shut down any subsystems that have global state */
 	git_hash_global_shutdown();
+	git_futils_dirs_free();
 }
 
 git_global_st *git__global_state(void)
@@ -171,7 +174,9 @@ int git_threads_init(void)
 
 void git_threads_shutdown(void)
 {
-	/* noop */
+	/* Shut down any subsystems that have global state */
+	git_hash_global_shutdown();
+	git_futils_dirs_free();
 }
 
 git_global_st *git__global_state(void)
diff --git a/src/ignore.c b/src/ignore.c
index 5edc5b6..1777952 100644
--- a/src/ignore.c
+++ b/src/ignore.c
@@ -1,11 +1,10 @@
 #include "git2/ignore.h"
 #include "ignore.h"
+#include "attr.h"
 #include "path.h"
 #include "config.h"
 
 #define GIT_IGNORE_INTERNAL		"[internal]exclude"
-#define GIT_IGNORE_FILE_INREPO	"info/exclude"
-#define GIT_IGNORE_FILE			".gitignore"
 
 #define GIT_IGNORE_DEFAULT_RULES ".\n..\n.git\n"
 
diff --git a/src/ignore.h b/src/ignore.h
index 5a15afc..5af8e8e 100644
--- a/src/ignore.h
+++ b/src/ignore.h
@@ -9,6 +9,11 @@
 
 #include "repository.h"
 #include "vector.h"
+#include "attr_file.h"
+
+#define GIT_IGNORE_FILE			".gitignore"
+#define GIT_IGNORE_FILE_INREPO	"info/exclude"
+#define GIT_IGNORE_FILE_XDG		"ignore"
 
 /* The git_ignores structure maintains three sets of ignores:
  * - internal ignores
diff --git a/src/repository.h b/src/repository.h
index ebd797c..cc2f8c2 100644
--- a/src/repository.h
+++ b/src/repository.h
@@ -19,7 +19,7 @@
 #include "buffer.h"
 #include "odb.h"
 #include "object.h"
-#include "attr.h"
+#include "attrcache.h"
 #include "strmap.h"
 #include "refdb.h"
 
diff --git a/src/util.c b/src/util.c
index 8859780..f5b4a1d 100644
--- a/src/util.c
+++ b/src/util.c
@@ -10,6 +10,7 @@
 #include <stdio.h>
 #include <ctype.h>
 #include "posix.h"
+#include "fileops.h"
 
 #ifdef _MSC_VER
 # include <Shlwapi.h>
@@ -38,13 +39,30 @@ int git_libgit2_capabilities()
 extern size_t git_mwindow__window_size;
 extern size_t git_mwindow__mapped_limit;
 
-void git_libgit2_opts(int key, ...)
+static int config_level_to_futils_dir(int config_level)
 {
+	int val = -1;
+
+	switch (config_level) {
+	case GIT_CONFIG_LEVEL_SYSTEM: val = GIT_FUTILS_DIR_SYSTEM; break;
+	case GIT_CONFIG_LEVEL_XDG:    val = GIT_FUTILS_DIR_XDG; break;
+	case GIT_CONFIG_LEVEL_GLOBAL: val = GIT_FUTILS_DIR_GLOBAL; break;
+	default:
+		giterr_set(
+			GITERR_INVALID, "Invalid config path selector %d", config_level);
+	}
+
+	return val;
+}
+
+int git_libgit2_opts(int key, ...)
+{
+	int error = 0;
 	va_list ap;
 
 	va_start(ap, key);
 
-	switch(key) {
+	switch (key) {
 	case GIT_OPT_SET_MWINDOW_SIZE:
 		git_mwindow__window_size = va_arg(ap, size_t);
 		break;
@@ -60,9 +78,25 @@ void git_libgit2_opts(int key, ...)
 	case GIT_OPT_GET_MWINDOW_MAPPED_LIMIT:
 		*(va_arg(ap, size_t *)) = git_mwindow__mapped_limit;
 		break;
+
+	case GIT_OPT_GET_SEARCH_PATH:
+		if ((error = config_level_to_futils_dir(va_arg(ap, int))) >= 0) {
+			char *out = va_arg(ap, char *);
+			size_t outlen = va_arg(ap, size_t);
+
+			error = git_futils_dirs_get_str(out, outlen, error);
+		}
+		break;
+
+	case GIT_OPT_SET_SEARCH_PATH:
+		if ((error = config_level_to_futils_dir(va_arg(ap, int))) >= 0)
+			error = git_futils_dirs_set(error, va_arg(ap, const char *));
+		break;
 	}
 
 	va_end(ap);
+
+	return error;
 }
 
 void git_strarray_free(git_strarray *array)
@@ -72,6 +106,8 @@ void git_strarray_free(git_strarray *array)
 		git__free(array->strings[i]);
 
 	git__free(array->strings);
+
+	memset(array, 0, sizeof(*array));
 }
 
 int git_strarray_copy(git_strarray *tgt, const git_strarray *src)
@@ -89,8 +125,10 @@ int git_strarray_copy(git_strarray *tgt, const git_strarray *src)
 	GITERR_CHECK_ALLOC(tgt->strings);
 
 	for (i = 0; i < src->count; ++i) {
-		tgt->strings[tgt->count] = git__strdup(src->strings[i]);
+		if (!src->strings[i])
+			continue;
 
+		tgt->strings[tgt->count] = git__strdup(src->strings[i]);
 		if (!tgt->strings[tgt->count]) {
 			git_strarray_free(tgt);
 			memset(tgt, 0, sizeof(*tgt));
diff --git a/src/win32/findfile.c b/src/win32/findfile.c
index 6fc7c75..bc36b6b 100644
--- a/src/win32/findfile.c
+++ b/src/win32/findfile.c
@@ -10,23 +10,34 @@
 #include "findfile.h"
 
 #define REG_MSYSGIT_INSTALL_LOCAL L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Git_is1"
+
 #ifndef _WIN64
 #define REG_MSYSGIT_INSTALL REG_MSYSGIT_INSTALL_LOCAL
 #else
 #define REG_MSYSGIT_INSTALL L"SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Git_is1"
 #endif
 
-int win32_expand_path(struct win32_path *s_root, const wchar_t *templ)
+int git_win32__expand_path(struct git_win32__path *s_root, const wchar_t *templ)
 {
 	s_root->len = ExpandEnvironmentStringsW(templ, s_root->path, MAX_PATH);
 	return s_root->len ? 0 : -1;
 }
 
-int win32_find_file(git_buf *path, const struct win32_path *root, const char *filename)
+static int win32_path_utf16_to_8(git_buf *path_utf8, const wchar_t *path_utf16)
+{
+	char temp_utf8[GIT_PATH_MAX];
+
+	git__utf16_to_8(temp_utf8, path_utf16);
+	git_path_mkposix(temp_utf8);
+
+	return git_buf_sets(path_utf8, temp_utf8);
+}
+
+int git_win32__find_file(
+	git_buf *path, const struct git_win32__path *root, const char *filename)
 {
 	size_t len, alloc_len;
 	wchar_t *file_utf16 = NULL;
-	char file_utf8[GIT_PATH_MAX];
 
 	if (!root || !filename || (len = strlen(filename)) == 0)
 		return GIT_ENOTFOUND;
@@ -50,15 +61,13 @@ int win32_find_file(git_buf *path, const struct win32_path *root, const char *fi
 		return GIT_ENOTFOUND;
 	}
 
-	git__utf16_to_8(file_utf8, file_utf16);
-	git_path_mkposix(file_utf8);
-	git_buf_sets(path, file_utf8);
-
+	win32_path_utf16_to_8(path, file_utf16);
 	git__free(file_utf16);
+
 	return 0;
 }
 
-wchar_t* win32_nextpath(wchar_t *path, wchar_t *buf, size_t buflen)
+static wchar_t* win32_walkpath(wchar_t *path, wchar_t *buf, size_t buflen)
 {
 	wchar_t term, *base = path;
 
@@ -77,80 +86,153 @@ wchar_t* win32_nextpath(wchar_t *path, wchar_t *buf, size_t buflen)
 	return (path != base) ? path : NULL;
 }
 
-int win32_find_system_file_using_path(git_buf *path, const char *filename)
+static int win32_find_git_in_path(git_buf *buf, const wchar_t *gitexe)
 {
-	wchar_t * env = NULL;
-	struct win32_path root;
+	wchar_t *env = _wgetenv(L"PATH"), lastch;
+	struct git_win32__path root;
+	size_t gitexe_len = wcslen(gitexe);
 
-	env = _wgetenv(L"PATH");
 	if (!env)
 		return -1;
 
-	// search in all paths defined in PATH
-	while ((env = win32_nextpath(env, root.path, MAX_PATH - 1)) != NULL && *root.path)
-	{
-		wchar_t * pfin = root.path + wcslen(root.path) - 1; // last char of the current path entry
+	while ((env = win32_walkpath(env, root.path, MAX_PATH-1)) && *root.path) {
+		root.len = (DWORD)wcslen(root.path);
+		lastch = root.path[root.len - 1];
+
+		/* ensure trailing slash (MAX_PATH-1 to walkpath guarantees space) */
+		if (lastch != L'/' && lastch != L'\\') {
+			root.path[root.len++] = L'\\';
+			root.path[root.len]   = L'\0';
+		}
 
-		// ensure trailing slash
-		if (*pfin != L'/' && *pfin != L'\\')
-			wcscpy(++pfin, L"\\"); // we have enough space left, MAX_PATH - 1 is used in nextpath above
+		if (root.len + gitexe_len >= MAX_PATH)
+			continue;
+		wcscpy(&root.path[root.len], gitexe);
 
-		root.len = (DWORD)wcslen(root.path) + 1;
+		if (_waccess(root.path, F_OK) == 0 && root.len > 5) {
+			/* replace "bin\\" or "cmd\\" with "etc\\" */
+			wcscpy(&root.path[root.len - 4], L"etc\\");
 
-		if (win32_find_file(path, &root, "git.cmd") == 0 || win32_find_file(path, &root, "git.exe") == 0) {
-			// we found the cmd or bin directory of a git installaton
-			if (root.len > 5) {
-				wcscpy(root.path + wcslen(root.path) - 4, L"etc\\");
-				if (win32_find_file(path, &root, filename) == 0)
-					return 0;
-			}
+			win32_path_utf16_to_8(buf, root.path);
+			return 0;
 		}
 	}
-	
+
 	return GIT_ENOTFOUND;
 }
 
-int win32_find_system_file_using_registry(git_buf *path, const char *filename)
+static int win32_find_git_in_registry(
+	git_buf *buf, const HKEY hieve, const wchar_t *key)
 {
-	struct win32_path root;
+	HKEY hKey;
+	DWORD dwType = REG_SZ;
+	struct git_win32__path path16;
+
+	assert(buf);
+
+	path16.len = 0;
+
+	if (RegOpenKeyExW(hieve, key, 0, KEY_ALL_ACCESS, &hKey) == ERROR_SUCCESS) {
+		if (RegQueryValueExW(hKey, L"InstallLocation", NULL, &dwType,
+			(LPBYTE)&path16.path, &path16.len) == ERROR_SUCCESS)
+		{
+			/* InstallLocation points to the root of the git directory */
 
-	if (win32_find_msysgit_in_registry(&root, HKEY_CURRENT_USER, REG_MSYSGIT_INSTALL_LOCAL)) {
-		if (win32_find_msysgit_in_registry(&root, HKEY_LOCAL_MACHINE, REG_MSYSGIT_INSTALL)) {
-			giterr_set(GITERR_OS, "Cannot locate the system's msysgit directory");
-			return -1;
+			if (path16.len + 4 > MAX_PATH) { /* 4 = wcslen(L"etc\\") */
+				giterr_set(GITERR_OS, "Cannot locate git - path too long");
+				return -1;
+			}
+
+			wcscat(path16.path, L"etc\\");
+			path16.len += 4;
+
+			win32_path_utf16_to_8(buf, path16.path);
 		}
-	}
 
-	if (win32_find_file(path, &root, filename) < 0) {
-		giterr_set(GITERR_OS, "The system file '%s' doesn't exist", filename);
-		git_buf_clear(path);
-		return GIT_ENOTFOUND;
+		RegCloseKey(hKey);
 	}
 
-	return 0;
+	return path16.len ? 0 : GIT_ENOTFOUND;
 }
 
-int win32_find_msysgit_in_registry(struct win32_path *root, const HKEY hieve, const wchar_t *key)
+static int win32_find_existing_dirs(
+	git_buf *out, const wchar_t *tmpl[], char *temp[])
 {
-	HKEY hKey;
-	DWORD dwType = REG_SZ;
-	DWORD dwSize = MAX_PATH;
+	struct git_win32__path path16;
+	git_buf buf = GIT_BUF_INIT;
 
-	assert(root);
+	git_buf_clear(out);
 
-	root->len = 0;
-	if (RegOpenKeyExW(hieve, key, 0, KEY_ALL_ACCESS, &hKey) == ERROR_SUCCESS) {
-		if (RegQueryValueExW(hKey, L"InstallLocation", NULL, &dwType, (LPBYTE)&root->path, &dwSize) == ERROR_SUCCESS) {
-			// InstallLocation points to the root of the msysgit directory
-			if (dwSize + 4 > MAX_PATH) {// 4 = wcslen(L"etc\\")
-				giterr_set(GITERR_OS, "Cannot locate the system's msysgit directory - path too long");
-				return -1;
-			}
-			wcscat(root->path, L"etc\\");
-			root->len = (DWORD)wcslen(root->path) + 1;
+	for (; *tmpl != NULL; tmpl++) {
+		if (!git_win32__expand_path(&path16, *tmpl) &&
+			path16.path[0] != L'%' &&
+			!_waccess(path16.path, F_OK))
+		{
+			win32_path_utf16_to_8(&buf, path16.path);
+
+			if (buf.size)
+				git_buf_join(out, GIT_PATH_LIST_SEPARATOR, out->ptr, buf.ptr);
 		}
 	}
-	RegCloseKey(hKey);
 
-	return root->len ? 0 : GIT_ENOTFOUND;
+	git_buf_free(&buf);
+
+	return (git_buf_oom(out) ? -1 : 0);
+}
+
+int git_win32__find_system_dirs(git_buf *out)
+{
+	git_buf buf = GIT_BUF_INIT;
+
+	/* directories where git.exe & git.cmd are found */
+	if (!win32_find_git_in_path(&buf, L"git.exe") && buf.size)
+		git_buf_set(out, buf.ptr, buf.size);
+	else
+		git_buf_clear(out);
+
+	if (!win32_find_git_in_path(&buf, L"git.cmd") && buf.size)
+		git_buf_join(out, GIT_PATH_LIST_SEPARATOR, out->ptr, buf.ptr);
+
+	/* directories where git is installed according to registry */
+	if (!win32_find_git_in_registry(
+			&buf, HKEY_CURRENT_USER, REG_MSYSGIT_INSTALL_LOCAL) && buf.size)
+		git_buf_join(out, GIT_PATH_LIST_SEPARATOR, out->ptr, buf.ptr);
+
+	if (!win32_find_git_in_registry(
+			&buf, HKEY_LOCAL_MACHINE, REG_MSYSGIT_INSTALL) && buf.size)
+		git_buf_join(out, GIT_PATH_LIST_SEPARATOR, out->ptr, buf.ptr);
+
+	git_buf_free(&buf);
+
+	return (git_buf_oom(out) ? -1 : 0);
+}
+
+int git_win32__find_global_dirs(git_buf *out)
+{
+	char *temp[3];
+	static const wchar_t *global_tmpls[4] = {
+		L"%HOME%\\",
+		L"%HOMEDRIVE%%HOMEPATH%\\",
+		L"%USERPROFILE%\\",
+		NULL,
+	};
+
+	return win32_find_existing_dirs(out, global_tmpls, temp);
+}
+
+int git_win32__find_xdg_dirs(git_buf *out)
+{
+	char *temp[6];
+	static const wchar_t *global_tmpls[7] = {
+		L"%XDG_CONFIG_HOME%\\git",
+		L"%APPDATA%\\git",
+		L"%LOCALAPPDATA%\\git",
+		L"%HOME%\\.config\\git",
+		L"%HOMEDRIVE%%HOMEPATH%\\.config\\git",
+		L"%USERPROFILE%\\.config\\git",
+		NULL,
+	};
+
+	return win32_find_existing_dirs(out, global_tmpls, temp);
 }
+
diff --git a/src/win32/findfile.h b/src/win32/findfile.h
index 47fe715..fc79e1b 100644
--- a/src/win32/findfile.h
+++ b/src/win32/findfile.h
@@ -8,17 +8,20 @@
 #ifndef INCLUDE_git_findfile_h__
 #define INCLUDE_git_findfile_h__
 
-struct win32_path {
+struct git_win32__path {
 	wchar_t path[MAX_PATH];
 	DWORD len;
 };
 
-int win32_expand_path(struct win32_path *s_root, const wchar_t *templ);
+extern int git_win32__expand_path(
+	struct git_win32__path *s_root, const wchar_t *templ);
 
-int win32_find_file(git_buf *path, const struct win32_path *root, const char *filename);
-int win32_find_system_file_using_path(git_buf *path, const char *filename);
-int win32_find_system_file_using_registry(git_buf *path, const char *filename);
-int win32_find_msysgit_in_registry(struct win32_path *root, const HKEY hieve, const wchar_t *key);
+extern int git_win32__find_file(
+	git_buf *path, const struct git_win32__path *root, const char *filename);
+
+extern int git_win32__find_system_dirs(git_buf *out);
+extern int git_win32__find_global_dirs(git_buf *out);
+extern int git_win32__find_xdg_dirs(git_buf *out);
 
 #endif
 
diff --git a/tests-clar/clar_libgit2.c b/tests-clar/clar_libgit2.c
index 698aa90..8033cdc 100644
--- a/tests-clar/clar_libgit2.c
+++ b/tests-clar/clar_libgit2.c
@@ -136,7 +136,7 @@ int cl_rename(const char *source, const char *dest)
 #include <stdlib.h>
 char *cl_getenv(const char *name)
 {
-   return getenv(name);
+	return getenv(name);
 }
 
 int cl_setenv(const char *name, const char *value)
diff --git a/tests-clar/core/env.c b/tests-clar/core/env.c
index 2f5e91f..0fa6472 100644
--- a/tests-clar/core/env.c
+++ b/tests-clar/core/env.c
@@ -29,8 +29,24 @@ static char *home_values[] = {
 void test_core_env__initialize(void)
 {
 	int i;
-	for (i = 0; i < NUM_VARS; ++i)
-		env_save[i] = cl_getenv(env_vars[i]);
+	for (i = 0; i < NUM_VARS; ++i) {
+		const char *original = cl_getenv(env_vars[i]);
+#ifdef GIT_WIN32
+		env_save[i] = (char *)original;
+#else
+		env_save[i] = original ? git__strdup(original) : NULL;
+#endif
+	}
+}
+
+static void reset_global_search_path(void)
+{
+	cl_git_pass(git_futils_dirs_set(GIT_FUTILS_DIR_GLOBAL, NULL));
+}
+
+static void reset_system_search_path(void)
+{
+	cl_git_pass(git_futils_dirs_set(GIT_FUTILS_DIR_SYSTEM, NULL));
 }
 
 void test_core_env__cleanup(void)
@@ -40,9 +56,7 @@ void test_core_env__cleanup(void)
 
 	for (i = 0; i < NUM_VARS; ++i) {
 		cl_setenv(env_vars[i], env_save[i]);
-#ifdef GIT_WIN32
 		git__free(env_save[i]);
-#endif
 		env_save[i] = NULL;
 	}
 
@@ -53,6 +67,10 @@ void test_core_env__cleanup(void)
 		if (**val != '\0')
 			(void)p_rmdir(*val);
 	}
+
+	/* reset search paths to default */
+	reset_global_search_path();
+	reset_system_search_path();
 }
 
 static void setenv_and_check(const char *name, const char *value)
@@ -60,6 +78,7 @@ static void setenv_and_check(const char *name, const char *value)
 	char *check;
 
 	cl_git_pass(cl_setenv(name, value));
+
 	check = cl_getenv(name);
 	cl_assert_equal_s(value, check);
 #ifdef GIT_WIN32
@@ -72,12 +91,11 @@ void test_core_env__0(void)
 	git_buf path = GIT_BUF_INIT, found = GIT_BUF_INIT;
 	char testfile[16], tidx = '0';
 	char **val;
+	const char *testname = "testfile";
+	size_t testlen = strlen(testname);
 
-	memset(testfile, 0, sizeof(testfile));
-	cl_assert_equal_s("", testfile);
-
-	memcpy(testfile, "testfile", 8);
-	cl_assert_equal_s("testfile", testfile);
+	strncpy(testfile, testname, sizeof(testfile));
+	cl_assert_equal_s(testname, testfile);
 
 	for (val = home_values; *val != NULL; val++) {
 
@@ -96,7 +114,7 @@ void test_core_env__0(void)
 		 * an environment variable set from a previous iteration won't
 		 * accidentally make this test pass...
 		 */
-		testfile[8] = tidx++;
+		testfile[testlen] = tidx++;
 		cl_git_pass(git_buf_joinpath(&path, path.ptr, testfile));
 		cl_git_mkfile(path.ptr, "find me");
 		git_buf_rtruncate_at_char(&path, '/');
@@ -105,9 +123,13 @@ void test_core_env__0(void)
 			GIT_ENOTFOUND, git_futils_find_global_file(&found, testfile));
 
 		setenv_and_check("HOME", path.ptr);
+		reset_global_search_path();
+
 		cl_git_pass(git_futils_find_global_file(&found, testfile));
 
 		cl_setenv("HOME", env_save[0]);
+		reset_global_search_path();
+
 		cl_assert_equal_i(
 			GIT_ENOTFOUND, git_futils_find_global_file(&found, testfile));
 
@@ -115,6 +137,7 @@ void test_core_env__0(void)
 		setenv_and_check("HOMEDRIVE", NULL);
 		setenv_and_check("HOMEPATH", NULL);
 		setenv_and_check("USERPROFILE", path.ptr);
+		reset_global_search_path();
 
 		cl_git_pass(git_futils_find_global_file(&found, testfile));
 
@@ -124,6 +147,7 @@ void test_core_env__0(void)
 
 			if (root >= 0) {
 				setenv_and_check("USERPROFILE", NULL);
+				reset_global_search_path();
 
 				cl_assert_equal_i(
 					GIT_ENOTFOUND, git_futils_find_global_file(&found, testfile));
@@ -133,6 +157,7 @@ void test_core_env__0(void)
 				setenv_and_check("HOMEDRIVE", path.ptr);
 				path.ptr[root] = old;
 				setenv_and_check("HOMEPATH", &path.ptr[root]);
+				reset_global_search_path();
 
 				cl_git_pass(git_futils_find_global_file(&found, testfile));
 			}
@@ -146,6 +171,7 @@ void test_core_env__0(void)
 	git_buf_free(&found);
 }
 
+
 void test_core_env__1(void)
 {
 	git_buf path = GIT_BUF_INIT;
@@ -158,6 +184,7 @@ void test_core_env__1(void)
 	cl_git_pass(cl_setenv("HOMEPATH", "doesnotexist"));
 	cl_git_pass(cl_setenv("USERPROFILE", "doesnotexist"));
 #endif
+	reset_global_search_path();
 
 	cl_assert_equal_i(
 		GIT_ENOTFOUND, git_futils_find_global_file(&path, "nonexistentfile"));
@@ -167,6 +194,8 @@ void test_core_env__1(void)
 	cl_git_pass(cl_setenv("HOMEPATH", NULL));
 	cl_git_pass(cl_setenv("USERPROFILE", NULL));
 #endif
+	reset_global_search_path();
+	reset_system_search_path();
 
 	cl_assert_equal_i(
 		GIT_ENOTFOUND, git_futils_find_global_file(&path, "nonexistentfile"));
@@ -176,9 +205,99 @@ void test_core_env__1(void)
 
 #ifdef GIT_WIN32
 	cl_git_pass(cl_setenv("PROGRAMFILES", NULL));
+	reset_system_search_path();
+
 	cl_assert_equal_i(
 		GIT_ENOTFOUND, git_futils_find_system_file(&path, "nonexistentfile"));
 #endif
 
 	git_buf_free(&path);
 }
+
+static void check_global_searchpath(
+	const char *path, int position, const char *file, git_buf *temp)
+{
+	char out[GIT_PATH_MAX];
+
+	/* build and set new path */
+	if (position < 0)
+		cl_git_pass(git_buf_join(temp, GIT_PATH_LIST_SEPARATOR, path, "$PATH"));
+	else if (position > 0)
+		cl_git_pass(git_buf_join(temp, GIT_PATH_LIST_SEPARATOR, "$PATH", path));
+	else
+		cl_git_pass(git_buf_sets(temp, path));
+
+	cl_git_pass(git_libgit2_opts(
+		GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, temp->ptr));
+
+	/* get path and make sure $PATH expansion worked */
+	cl_git_pass(git_libgit2_opts(
+		GIT_OPT_GET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, out, sizeof(out)));
+
+	if (position < 0)
+		cl_assert(git__prefixcmp(out, path) == 0);
+	else if (position > 0)
+		cl_assert(git__suffixcmp(out, path) == 0);
+	else
+		cl_assert_equal_s(out, path);
+
+	/* find file using new path */
+	cl_git_pass(git_futils_find_global_file(temp, file));
+
+	/* reset path and confirm file not found */
+	cl_git_pass(git_libgit2_opts(
+		GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, NULL));
+	cl_assert_equal_i(
+		GIT_ENOTFOUND, git_futils_find_global_file(temp, file));
+}
+
+void test_core_env__2(void)
+{
+	git_buf path = GIT_BUF_INIT, found = GIT_BUF_INIT;
+	char testfile[16], tidx = '0';
+	char **val;
+	const char *testname = "alternate";
+	size_t testlen = strlen(testname);
+
+	strncpy(testfile, testname, sizeof(testfile));
+	cl_assert_equal_s(testname, testfile);
+
+	for (val = home_values; *val != NULL; val++) {
+
+		/* if we can't make the directory, let's just assume
+		 * we are on a filesystem that doesn't support the
+		 * characters in question and skip this test...
+		 */
+		if (p_mkdir(*val, 0777) != 0 && errno != EEXIST) {
+			*val = ""; /* mark as not created */
+			continue;
+		}
+
+		cl_git_pass(git_path_prettify(&path, *val, NULL));
+
+		/* vary testfile name so any sloppiness is resetting variables or
+		 * deleting files won't accidentally make a test pass.
+		 */
+		testfile[testlen] = tidx++;
+		cl_git_pass(git_buf_joinpath(&path, path.ptr, testfile));
+		cl_git_mkfile(path.ptr, "find me");
+		git_buf_rtruncate_at_char(&path, '/');
+
+		/* default should be NOTFOUND */
+		cl_assert_equal_i(
+			GIT_ENOTFOUND, git_futils_find_global_file(&found, testfile));
+
+		/* try plain, append $PATH, and prepend $PATH */
+		check_global_searchpath(path.ptr,  0, testfile, &found);
+		check_global_searchpath(path.ptr, -1, testfile, &found);
+		check_global_searchpath(path.ptr,  1, testfile, &found);
+
+		/* cleanup */
+		cl_git_pass(git_buf_joinpath(&path, path.ptr, testfile));
+		(void)p_unlink(path.ptr);
+		(void)p_rmdir(*val);
+	}
+
+	git_buf_free(&path);
+	git_buf_free(&found);
+}