Commit fcb2164ff1a0ab0eab22e08cefa87880590bdbbf

Vicent Martí 2012-04-13T10:51:58

Merge pull request #623 from arrbee/refactor-open Update git_repository_open

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
diff --git a/include/git2/repository.h b/include/git2/repository.h
index 34dd904..d760c23 100644
--- a/include/git2/repository.h
+++ b/include/git2/repository.h
@@ -70,6 +70,20 @@ GIT_EXTERN(int) git_repository_discover(
 		int across_fs,
 		const char *ceiling_dirs);
 
+enum {
+	GIT_REPOSITORY_OPEN_NO_SEARCH = (1 << 0),
+	GIT_REPOSITORY_OPEN_CROSS_FS  = (1 << 1),
+};
+
+/**
+ * Find and open a repository with extended controls.
+ */
+GIT_EXTERN(int) git_repository_open_ext(
+	git_repository **repo,
+	const char *start_path,
+	uint32_t flags,
+	const char *ceiling_dirs);
+
 /**
  * Free a previously allocated repository
  *
diff --git a/src/attr.c b/src/attr.c
index 5cf96ac..c022893 100644
--- a/src/attr.c
+++ b/src/attr.c
@@ -347,6 +347,7 @@ static int collect_attr_files(
 
 int git_attr_cache__init(git_repository *repo)
 {
+	int ret;
 	git_attr_cache *cache = git_repository_attr_cache(repo);
 	git_config *cfg;
 
@@ -354,17 +355,18 @@ int git_attr_cache__init(git_repository *repo)
 		return 0;
 
 	/* cache config settings for attributes and ignores */
-	if (git_repository_config(&cfg, repo) < 0)
+	if (git_repository_config__weakptr(&cfg, repo) < 0)
 		return -1;
-	if (git_config_get_string(cfg, GIT_ATTR_CONFIG, &cache->cfg_attr_file)) {
-		giterr_clear();
-		cache->cfg_attr_file = NULL;
-	}
-	if (git_config_get_string(cfg, GIT_IGNORE_CONFIG, &cache->cfg_excl_file)) {
-		giterr_clear();
-		cache->cfg_excl_file = NULL;
-	}
-	git_config_free(cfg);
+
+	ret = git_config_get_string(cfg, GIT_ATTR_CONFIG, &cache->cfg_attr_file);
+	if (ret < 0 && ret != GIT_ENOTFOUND)
+		return ret;
+
+	ret = git_config_get_string(cfg, GIT_IGNORE_CONFIG, &cache->cfg_excl_file);
+	if (ret < 0 && ret != GIT_ENOTFOUND)
+		return ret;
+
+	giterr_clear();
 
 	/* allocate hashtable for attribute and ignore file contents */
 	if (cache->files == NULL) {
diff --git a/src/config.c b/src/config.c
index 250bfa6..f5cfa9e 100644
--- a/src/config.c
+++ b/src/config.c
@@ -327,11 +327,11 @@ int git_config_lookup_map_value(
 int git_config_get_mapped(git_config *cfg, const char *name, git_cvar_map *maps, size_t map_n, int *out)
 {
 	const char *value;
-	int error;
+	int ret;
 
-	error = git_config_get_string(cfg, name, &value);
-	if (error < 0)
-		return error;
+	ret = git_config_get_string(cfg, name, &value);
+	if (ret < 0)
+		return ret;
 
 	if (!git_config_lookup_map_value(maps, map_n, value, out))
 		return 0;
@@ -371,7 +371,7 @@ int git_config_get_int32(git_config *cfg, const char *name, int32_t *out)
 		giterr_set(GITERR_CONFIG, "Failed to parse '%s' as a 32-bit integer", value);
 		return -1;
 	}
-	
+
 	return 0;
 }
 
@@ -399,26 +399,17 @@ int git_config_get_bool(git_config *cfg, const char *name, int *out)
 int git_config_get_string(git_config *cfg, const char *name, const char **out)
 {
 	file_internal *internal;
-	git_config_file *file;
-	int ret = GIT_ENOTFOUND;
 	unsigned int i;
 
 	assert(cfg->files.length);
 
-	for (i = 0; i < cfg->files.length; ++i) {
-		internal = git_vector_get(&cfg->files, i);
-		file = internal->file;
-
-		ret = file->get(file, name, out);
-		if (ret == 0)
-			return 0;
+	*out = NULL;
 
-		/* File backend doesn't set error message on variable
-		 * not found */
-		if (ret == GIT_ENOTFOUND)
-			continue;
-
-		return ret;
+	git_vector_foreach(&cfg->files, i, internal) {
+		git_config_file *file = internal->file;
+		int ret = file->get(file, name, out);
+		if (ret != GIT_ENOTFOUND)
+			return ret;
 	}
 
 	giterr_set(GITERR_CONFIG, "Config variable '%s' not found", name);
diff --git a/src/diff.c b/src/diff.c
index 54e8dd1..fa841f7 100644
--- a/src/diff.c
+++ b/src/diff.c
@@ -253,7 +253,7 @@ static git_diff_list *git_diff_list_alloc(
 	diff->repo = repo;
 
 	/* load config values that affect diff behavior */
-	if (git_repository_config(&cfg, repo) < 0)
+	if (git_repository_config__weakptr(&cfg, repo) < 0)
 		goto fail;
 	if (config_bool(cfg, "core.symlinks", 1))
 		diff->diffcaps = diff->diffcaps | GIT_DIFFCAPS_HAS_SYMLINKS;
@@ -264,7 +264,6 @@ static git_diff_list *git_diff_list_alloc(
 	if (config_bool(cfg, "core.trustctime", 1))
 		diff->diffcaps = diff->diffcaps | GIT_DIFFCAPS_TRUST_CTIME;
 	/* Don't set GIT_DIFFCAPS_USE_DEV - compile time option in core git */
-	git_config_free(cfg);
 
 	if (opts == NULL)
 		return diff;
diff --git a/src/errors.c b/src/errors.c
index 70aa641..aad6c44 100644
--- a/src/errors.c
+++ b/src/errors.c
@@ -92,8 +92,12 @@ const char *git_lasterror(void)
 {
 	char *last_error = GIT_GLOBAL->error.last;
 
-	if (!last_error[0])
+	if (!last_error[0]) {
+		const git_error *err = git_error_last();
+		if (err != NULL)
+			return err->message;
 		return NULL;
+	}
 
 	return last_error;
 }
diff --git a/src/path.c b/src/path.c
index 31d2e72..3c1a723 100644
--- a/src/path.c
+++ b/src/path.c
@@ -172,20 +172,22 @@ int git_path_root(const char *path)
 	if (isalpha(path[0]) && (path[1] == ':'))
 		offset += 2;
 
-	/* Are we dealing with a network path? */
-	else if (path[0] == '/' && path[1] == '/') {
+	/* Are we dealing with a windows network path? */
+	else if ((path[0] == '/' && path[1] == '/') ||
+		(path[0] == '\\' && path[1] == '\\'))
+	{
 		offset += 2;
-	
+
 		/* Skip the computer name segment */
-		while (*(path + offset) && *(path + offset) != '/')
+		while (path[offset] && path[offset] != '/' && path[offset] != '\\')
 			offset++;
 	}
 #endif
 
-	if (*(path + offset) == '/')
+	if (path[offset] == '/' || path[offset] == '\\')
 		return offset;
 
-	return -1;	/* Not a real error. Rather a signal than the path is not rooted */
+	return -1;	/* Not a real error - signals that path is not rooted */
 }
 
 int git_path_prettify(git_buf *path_out, const char *path, const char *base)
@@ -193,26 +195,21 @@ int git_path_prettify(git_buf *path_out, const char *path, const char *base)
 	char buf[GIT_PATH_MAX];
 
 	assert(path && path_out);
-	git_buf_clear(path_out);
 
 	/* construct path if needed */
 	if (base != NULL && git_path_root(path) < 0) {
 		if (git_buf_joinpath(path_out, base, path) < 0)
 			return -1;
-
 		path = path_out->ptr;
 	}
 
 	if (p_realpath(path, buf) == NULL) {
-		giterr_set(GITERR_OS, "Failed to resolve path '%s': %s",
-			path, strerror(errno));
+		giterr_set(GITERR_OS, "Failed to resolve path '%s'", path);
+		git_buf_clear(path_out);
 		return (errno == ENOENT) ? GIT_ENOTFOUND : -1;
 	}
 
-	if (git_buf_sets(path_out, buf) < 0)
-		return -1;
-
-	return 0;
+	return git_buf_sets(path_out, buf);
 }
 
 int git_path_prettify_dir(git_buf *path_out, const char *path, const char *base)
diff --git a/src/repository.c b/src/repository.c
index ce31328..413bb17 100644
--- a/src/repository.c
+++ b/src/repository.c
@@ -5,6 +5,7 @@
  * a Linking Exception. For full terms see the included COPYING file.
  */
 #include <stdarg.h>
+#include <ctype.h>
 
 #include "git2/object.h"
 
@@ -20,7 +21,7 @@
 #define GIT_OBJECTS_INFO_DIR GIT_OBJECTS_DIR "info/"
 #define GIT_OBJECTS_PACK_DIR GIT_OBJECTS_DIR "pack/"
 
-#define GIT_FILE_CONTENT_PREFIX "gitdir: "
+#define GIT_FILE_CONTENT_PREFIX "gitdir:"
 
 #define GIT_BRANCH_MASTER "master"
 
@@ -132,76 +133,294 @@ static int load_config_data(git_repository *repo)
 	return 0;
 }
 
-static int load_workdir(git_repository *repo)
+static int load_workdir(git_repository *repo, git_buf *parent_path)
 {
-	git_buf workdir_buf = GIT_BUF_INIT;
+	int         error;
+	git_config *config;
+	const char *worktree;
+	git_buf     worktree_buf = GIT_BUF_INIT;
 
 	if (repo->is_bare)
 		return 0;
 
-	git_path_dirname_r(&workdir_buf, repo->path_repository);
-	git_path_to_dir(&workdir_buf);
-
-	if (git_buf_oom(&workdir_buf))
+	if (git_repository_config__weakptr(&config, repo) < 0)
 		return -1;
 
-	repo->workdir = git_buf_detach(&workdir_buf);
-	git_buf_free(&workdir_buf);
+	error = git_config_get_string(config, "core.worktree", &worktree);
+	if (!error && worktree != NULL)
+		repo->workdir = git__strdup(worktree);
+	else if (error != GIT_ENOTFOUND)
+		return error;
+	else {
+		giterr_clear();
+
+		if (parent_path && git_path_isdir(parent_path->ptr))
+			repo->workdir = git_buf_detach(parent_path);
+		else {
+			git_path_dirname_r(&worktree_buf, repo->path_repository);
+			git_path_to_dir(&worktree_buf);
+			repo->workdir = git_buf_detach(&worktree_buf);
+		}
+	}
+
+	GITERR_CHECK_ALLOC(repo->workdir);
 
 	return 0;
 }
 
-int git_repository_open(git_repository **repo_out, const char *path)
+/*
+ * This function returns furthest offset into path where a ceiling dir
+ * is found, so we can stop processing the path at that point.
+ *
+ * Note: converting this to use git_bufs instead of GIT_PATH_MAX buffers on
+ * the stack could remove directories name limits, but at the cost of doing
+ * repeated malloc/frees inside the loop below, so let's not do it now.
+ */
+static int find_ceiling_dir_offset(
+	const char *path,
+	const char *ceiling_directories)
 {
-	git_buf path_buf = GIT_BUF_INIT;
-	git_repository *repo = NULL;
-	int res;
+	char buf[GIT_PATH_MAX + 1];
+	char buf2[GIT_PATH_MAX + 1];
+	const char *ceil, *sep;
+	int len, max_len = -1;
+	int min_len;
 
-	res = git_path_prettify_dir(&path_buf, path, NULL);
-	if (res < 0)
-		return res;
+	assert(path);
+
+	min_len = git_path_root(path) + 1;
 
-	/**
-	 * Check if the path we've been given is actually the path
-	 * of the working dir, by testing if it contains a `.git`
-	 * folder inside of it.
-	 */
-	if (git_path_contains_dir(&path_buf, GIT_DIR) == true)
-		git_buf_joinpath(&path_buf, path_buf.ptr, GIT_DIR);
+	if (ceiling_directories == NULL || min_len == 0)
+		return min_len;
+
+	for (sep = ceil = ceiling_directories; *sep; ceil = sep + 1) {
+		for (sep = ceil; *sep && *sep != GIT_PATH_LIST_SEPARATOR; sep++);
+		len = sep - ceil;
+
+		if (len == 0 || len >= (int)sizeof(buf) || git_path_root(ceil) == -1)
+			continue;
+
+		strncpy(buf, ceil, len);
+		buf[len] = '\0';
+
+		if (p_realpath(buf, buf2) == NULL)
+			continue;
+
+		len = strlen(buf2);
+		if (len > 0 && buf2[len-1] == '/')
+			buf[--len] = '\0';
+
+		if (!strncmp(path, buf2, len) &&
+			path[len] == '/' &&
+			len > max_len)
+		{
+			max_len = len;
+		}
+	}
+
+	return max_len <= min_len ? min_len : max_len;
+}
+
+/*
+ * Read the contents of `file_path` and set `path_out` to the repo dir that
+ * it points to.  Before calling, set `path_out` to the base directory that
+ * should be used if the contents of `file_path` are a relative path.
+ */
+static int read_gitfile(git_buf *path_out, const char *file_path)
+{
+	int     error = 0;
+	git_buf file = GIT_BUF_INIT;
+	size_t  prefix_len = strlen(GIT_FILE_CONTENT_PREFIX);
+
+	assert(path_out && file_path);
+
+	if (git_futils_readbuffer(&file, file_path) < 0)
+		return -1;
+
+	git_buf_rtrim(&file);
+
+	if (file.size <= prefix_len ||
+		memcmp(file.ptr, GIT_FILE_CONTENT_PREFIX, prefix_len) != 0)
+	{
+		giterr_set(GITERR_REPOSITORY, "The `.git` file at '%s' is malformed", file_path);
+		error = -1;
+	}
+	else if ((error = git_path_dirname_r(path_out, file_path)) >= 0) {
+		const char *gitlink = ((const char *)file.ptr) + prefix_len;
+		while (*gitlink && isspace(*gitlink)) gitlink++;
+		error = git_path_prettify_dir(path_out, gitlink, path_out->ptr);
+	}
 
-	if (valid_repository_path(&path_buf) == false) {
+	git_buf_free(&file);
+	return error;
+}
+
+static int find_repo(
+	git_buf *repo_path,
+	git_buf *parent_path,
+	const char *start_path,
+	uint32_t flags,
+	const char *ceiling_dirs)
+{
+	int error;
+	git_buf path = GIT_BUF_INIT;
+	struct stat st;
+	dev_t initial_device = 0;
+	bool try_with_dot_git = false;
+	int ceiling_offset;
+
+	git_buf_free(repo_path);
+
+	if ((error = git_path_prettify_dir(&path, start_path, NULL)) < 0)
+		return error;
+
+	ceiling_offset = find_ceiling_dir_offset(path.ptr, ceiling_dirs);
+
+	if ((error = git_buf_joinpath(&path, path.ptr, DOT_GIT)) < 0)
+		return error;
+
+	while (!error && !repo_path->size) {
+		if (p_stat(path.ptr, &st) == 0) {
+			/* check that we have not crossed device boundaries */
+			if (initial_device == 0)
+				initial_device = st.st_dev;
+			else if (st.st_dev != initial_device &&
+				(flags & GIT_REPOSITORY_OPEN_CROSS_FS) == 0)
+				break;
+
+			if (S_ISDIR(st.st_mode)) {
+				if (valid_repository_path(&path)) {
+					git_path_to_dir(&path);
+					git_buf_set(repo_path, path.ptr, path.size);
+					break;
+				}
+			}
+			else if (S_ISREG(st.st_mode)) {
+				git_buf repo_link = GIT_BUF_INIT;
+
+				if (!(error = read_gitfile(&repo_link, path.ptr))) {
+					if (valid_repository_path(&repo_link))
+						git_buf_swap(repo_path, &repo_link);
+					break;
+				}
+				git_buf_free(&repo_link);
+			}
+		}
+
+		/* move up one directory level */
+		if (git_path_dirname_r(&path, path.ptr) < 0) {
+			error = -1;
+			break;
+		}
+
+		if (try_with_dot_git) {
+			/* if we tried original dir with and without .git AND either hit
+			 * directory ceiling or NO_SEARCH was requested, then be done.
+			 */
+			if (path.ptr[ceiling_offset] == '\0' ||
+				(flags & GIT_REPOSITORY_OPEN_NO_SEARCH) != 0)
+				break;
+			/* otherwise look first for .git item */
+			error = git_buf_joinpath(&path, path.ptr, DOT_GIT);
+		}
+		try_with_dot_git = !try_with_dot_git;
+	}
+
+	if (!error && parent_path != NULL) {
+		if (!repo_path->size)
+			git_buf_clear(parent_path);
+		else {
+			git_path_dirname_r(parent_path, path.ptr);
+			git_path_to_dir(parent_path);
+		}
+		if (git_buf_oom(parent_path))
+			return -1;
+	}
+
+	git_buf_free(&path);
+
+	if (!repo_path->size && !error) {
 		giterr_set(GITERR_REPOSITORY,
-			"The given path (%s) is not a valid Git repository", git_buf_cstr(&path_buf));
-		git_buf_free(&path_buf);
-		return GIT_ENOTFOUND;
+			"Could not find repository from '%s'", start_path);
+		error = GIT_ENOTFOUND;
 	}
 
+	return error;
+}
+
+int git_repository_open_ext(
+	git_repository **repo_ptr,
+	const char *start_path,
+	uint32_t flags,
+	const char *ceiling_dirs)
+{
+	int error;
+	git_buf path = GIT_BUF_INIT, parent = GIT_BUF_INIT;
+	git_repository *repo;
+
+	*repo_ptr = NULL;
+
+	if ((error = find_repo(&path, &parent, start_path, flags, ceiling_dirs)) < 0)
+		return error;
+
 	repo = repository_alloc();
 	GITERR_CHECK_ALLOC(repo);
 
-	repo->path_repository = git_buf_detach(&path_buf);
+	repo->path_repository = git_buf_detach(&path);
 	GITERR_CHECK_ALLOC(repo->path_repository);
 
-	if (load_config_data(repo) < 0)
-		goto cleanup;
-
-	if (load_workdir(repo) < 0)
-		goto cleanup;
+	if ((error = load_config_data(repo)) < 0 ||
+		(error = load_workdir(repo, &parent)) < 0)
+	{
+		git_repository_free(repo);
+		return error;
+	}
 
-	*repo_out = repo;
+	*repo_ptr = repo;
 	return 0;
+}
 
- cleanup:
-	git_repository_free(repo);
-	git_buf_free(&path_buf);
-	return -1;
+int git_repository_open(git_repository **repo_out, const char *path)
+{
+	return git_repository_open_ext(
+		repo_out, path, GIT_REPOSITORY_OPEN_NO_SEARCH, NULL);
+}
+
+int git_repository_discover(
+	char *repository_path,
+	size_t size,
+	const char *start_path,
+	int across_fs,
+	const char *ceiling_dirs)
+{
+	git_buf path = GIT_BUF_INIT;
+	uint32_t flags = across_fs ? GIT_REPOSITORY_OPEN_CROSS_FS : 0;
+
+	assert(start_path && repository_path && size > 0);
+
+	*repository_path = '\0';
+
+	if (find_repo(&path, NULL, start_path, flags, ceiling_dirs) < 0)
+		return -1;
+
+	if (size < (size_t)(path.size + 1)) {
+		giterr_set(GITERR_REPOSITORY,
+			"The given buffer is too long to store the discovered path");
+		git_buf_free(&path);
+		return -1;
+	}
+
+	/* success: we discovered a repository */
+	git_buf_copy_cstr(repository_path, size, &path);
+	git_buf_free(&path);
+	return 0;
 }
 
 static int load_config(
-		git_config **out,
-		git_repository *repo,
-		const char *global_config_path,
-		const char *system_config_path)
+	git_config **out,
+	git_repository *repo,
+	const char *global_config_path,
+	const char *system_config_path)
 {
 	git_buf config_path = GIT_BUF_INIT;
 	git_config *cfg = NULL;
@@ -375,240 +594,6 @@ void git_repository_set_index(git_repository *repo, git_index *index)
 	GIT_REFCOUNT_OWN(repo->_index, repo);
 }
 
-
-static int retrieve_device(dev_t *device_out, const char *path)
-{
-	int error;
-	struct stat path_info;
-
-	assert(device_out);
-
-	if ((error = git_path_lstat(path, &path_info)) == 0)
-		*device_out = path_info.st_dev;
-
-	return error;
-}
-
-/*
- * This function returns furthest offset into path where a ceiling dir
- * is found, so we can stop processing the path at that point.
- *
- * Note: converting this to use git_bufs instead of GIT_PATH_MAX buffers on
- * the stack could remove directories name limits, but at the cost of doing
- * repeated malloc/frees inside the loop below, so let's not do it now.
- */
-static int retrieve_ceiling_directories_offset(
-	const char *path,
-	const char *ceiling_directories)
-{
-	char buf[GIT_PATH_MAX + 1];
-	char buf2[GIT_PATH_MAX + 1];
-	const char *ceil, *sep;
-	int len, max_len = -1;
-	int min_len;
-
-	assert(path);
-
-	min_len = git_path_root(path) + 1;
-
-	if (ceiling_directories == NULL || min_len == 0)
-		return min_len;
-
-	for (sep = ceil = ceiling_directories; *sep; ceil = sep + 1) {
-		for (sep = ceil; *sep && *sep != GIT_PATH_LIST_SEPARATOR; sep++);
-		len = sep - ceil;
-
-		if (len == 0 || len >= (int)sizeof(buf) || git_path_root(ceil) == -1)
-			continue;
-
-		strncpy(buf, ceil, len);
-		buf[len] = '\0';
-
-		if (p_realpath(buf, buf2) == NULL)
-			continue;
-
-		len = strlen(buf2);
-		if (len > 0 && buf2[len-1] == '/')
-			buf[--len] = '\0';
-
-		if (!strncmp(path, buf2, len) &&
-			path[len] == '/' &&
-			len > max_len)
-		{
-			max_len = len;
-		}
-	}
-
-	return max_len <= min_len ? min_len : max_len;
-}
-
-/*
- * Read the contents of `file_path` and set `path_out` to the repo dir that
- * it points to.  Before calling, set `path_out` to the base directory that
- * should be used if the contents of `file_path` are a relative path.
- */
-static int read_gitfile(git_buf *path_out, const char *file_path, const char *base_path)
-{
-	git_buf file = GIT_BUF_INIT;
-
-	assert(path_out && file_path);
-
-	if (git_futils_readbuffer(&file, file_path) < 0)
-		return -1;
-
-	git_buf_rtrim(&file);
-
-	if (git__prefixcmp((char *)file.ptr, GIT_FILE_CONTENT_PREFIX) != 0 ||
-		strlen(GIT_FILE_CONTENT_PREFIX) == file.size) {
-		git_buf_free(&file);
-		giterr_set(GITERR_REPOSITORY, "The `.git` file at '%s' is corrupted", file_path);
-		return -1;
-	}
-
-	if (git_path_prettify_dir(path_out,
-		((char *)file.ptr) + strlen(GIT_FILE_CONTENT_PREFIX), base_path) < 0) {
-		git_buf_free(&file);
-		giterr_set(GITERR_REPOSITORY,
-			"The `.git` file at '%s' points to an invalid path.", file_path);
-		return -1;
-	}
-
-	git_buf_free(&file);
-	return 0;
-}
-
-int git_repository_discover(
-	char *repository_path,
-	size_t size,
-	const char *start_path,
-	int across_fs,
-	const char *ceiling_dirs)
-{
-	int res, ceiling_offset;
-	git_buf bare_path = GIT_BUF_INIT;
-	git_buf normal_path = GIT_BUF_INIT;
-	git_buf *found_path = NULL;
-	dev_t current_device = 0;
-
-	assert(start_path && repository_path);
-
-	*repository_path = '\0';
-
-	res = git_path_prettify_dir(&bare_path, start_path, NULL);
-	if (res < 0)
-		return res;
-
-	if (!across_fs) {
-		if (retrieve_device(&current_device, bare_path.ptr) < 0)
-			goto on_error;
-	}
-
-	ceiling_offset = retrieve_ceiling_directories_offset(bare_path.ptr, ceiling_dirs);
-
-	while(1) {
-		if (git_buf_joinpath(&normal_path, bare_path.ptr, DOT_GIT) < 0)
-			goto on_error;
-
-		/**
-		 * If the `.git` file is regular instead of
-		 * a directory, it should contain the path of the actual git repository
-		 */
-		if (git_path_isfile(normal_path.ptr) == true) {
-			git_buf gitfile_path = GIT_BUF_INIT;
-
-			if (read_gitfile(&gitfile_path, normal_path.ptr, bare_path.ptr) < 0) {
-				git_buf_free(&gitfile_path);
-				goto on_error;
-			}
-
-			if (valid_repository_path(&gitfile_path) == false) {
-				git_buf_free(&gitfile_path);
-				giterr_set(GITERR_REPOSITORY,
-					"The `.git` file found at '%s' points to an invalid git folder", normal_path.ptr);
-				goto on_error;
-			}
-
-			git_buf_swap(&normal_path, &gitfile_path);
-			found_path = &normal_path;
-
-			git_buf_free(&gitfile_path);
-			break;
-		}
-
-		/**
-		 * If the `.git` file is a folder, we check inside of it
-		 */
-		if (git_path_isdir(normal_path.ptr) == true) {
-			if (valid_repository_path(&normal_path) == true) {
-				found_path = &normal_path;
-				break;
-			}
-		}
-
-		/**
-		 * Otherwise, the repository may be bare, let's check
-		 * the root anyway
-		 */
-		if (valid_repository_path(&bare_path) == true) {
-			found_path = &bare_path;
-			break;
-		}
-
-		/**
-		 * If we didn't find it, walk up the tree
-		 */
-		if (git_path_dirname_r(&normal_path, bare_path.ptr) < 0)
-			goto on_error;
-
-		git_buf_swap(&bare_path, &normal_path);
-
-		if (!across_fs) {
-			dev_t new_device;
-			if (retrieve_device(&new_device, bare_path.ptr) < 0)
-				goto on_error;
-
-			if (current_device != new_device)
-				goto on_not_found;
-
-			current_device = new_device;
-		}
-
-		/* nothing has been found, lets try the parent directory
-		 * but stop if we hit one of the ceiling directories
-		 */
-		if (bare_path.ptr[ceiling_offset] == '\0')
-			goto on_not_found;
-	}
-
-	assert(found_path);
-
-	if (git_path_to_dir(found_path) < 0)
-		goto on_error;
-
-	if (size < (size_t)(found_path->size + 1)) {
-		giterr_set(GITERR_REPOSITORY,
-			"The given buffer is too long to store the discovered path");
-		goto on_error;
-	}
-
-	/* success: we discovered a repository */
-	git_buf_copy_cstr(repository_path, size, found_path);
-
-	git_buf_free(&bare_path);
-	git_buf_free(&normal_path);
-	return 0;
-
-on_error: /* unrecoverable error */
-	git_buf_free(&bare_path);
-	git_buf_free(&normal_path);
-	return -1;
-
-on_not_found: /* failed to discover the repository */
-	git_buf_free(&bare_path);
-	git_buf_free(&normal_path);
-	return GIT_ENOTFOUND;
-}
-
 static int check_repositoryformatversion(git_repository *repo)
 {
 	git_config *config;
diff --git a/tests-clar/clar_helpers.c b/tests-clar/clar_helpers.c
index 22db56f..0010453 100644
--- a/tests-clar/clar_helpers.c
+++ b/tests-clar/clar_helpers.c
@@ -28,9 +28,9 @@ void cl_git_mkfile(const char *filename, const char *content)
 	cl_must_pass(p_close(fd));
 }
 
-void cl_git_append2file(const char *filename, const char *new_content)
+void cl_git_write2file(const char *filename, const char *new_content, int flags)
 {
-	int fd = p_open(filename, O_WRONLY | O_APPEND | O_CREAT);
+	int fd = p_open(filename, flags);
 	cl_assert(fd != 0);
 	if (!new_content)
 		new_content = "\n";
@@ -39,6 +39,16 @@ void cl_git_append2file(const char *filename, const char *new_content)
 	cl_must_pass(p_chmod(filename, 0644));
 }
 
+void cl_git_append2file(const char *filename, const char *new_content)
+{
+	cl_git_write2file(filename, new_content, O_WRONLY | O_APPEND | O_CREAT);
+}
+
+void cl_git_rewritefile(const char *filename, const char *new_content)
+{
+	cl_git_write2file(filename, new_content, O_WRONLY | O_CREAT | O_TRUNC);
+}
+
 static const char *_cl_sandbox = NULL;
 static git_repository *_cl_repo = NULL;
 
@@ -52,11 +62,12 @@ git_repository *cl_git_sandbox_init(const char *sandbox)
 
 	p_chdir(sandbox);
 
-	/* Rename `sandbox/.gitted` to `sandbox/.git` which must be done since
-	 * we cannot store a folder named `.git` inside the fixtures folder of
-	 * our libgit2 repo.
+	/* If this is not a bare repo, then rename `sandbox/.gitted` to
+	 * `sandbox/.git` which must be done since we cannot store a folder
+	 * named `.git` inside the fixtures folder of our libgit2 repo.
 	 */
-	cl_git_pass(p_rename(".gitted", ".git"));
+	if (p_access(".gitted", F_OK) == 0)
+		cl_git_pass(p_rename(".gitted", ".git"));
 
 	/* If we have `gitattributes`, rename to `.gitattributes`.  This may
 	 * be necessary if we don't want the attributes to be applied in the
diff --git a/tests-clar/clar_libgit2.h b/tests-clar/clar_libgit2.h
index 5c034a3..bb2feee 100644
--- a/tests-clar/clar_libgit2.h
+++ b/tests-clar/clar_libgit2.h
@@ -57,6 +57,8 @@ GIT_INLINE(void) cl_assert_strequal_internal(
 /* Write the contents of a buffer to disk */
 void cl_git_mkfile(const char *filename, const char *content);
 void cl_git_append2file(const char *filename, const char *new_content);
+void cl_git_rewritefile(const char *filename, const char *new_content);
+void cl_git_write2file(const char *filename, const char *new_content, int mode);
 
 /* Git sandbox setup helpers */
 
diff --git a/tests-clar/repo/open.c b/tests-clar/repo/open.c
index c3a7dad..28bae40 100644
--- a/tests-clar/repo/open.c
+++ b/tests-clar/repo/open.c
@@ -1,25 +1,27 @@
 #include "clar_libgit2.h"
-#include "posix.h"
-
-static git_repository *repo;
+#include "fileops.h"
 
 void test_repo_open__cleanup(void)
 {
-	git_repository_free(repo);
+	cl_git_sandbox_cleanup();
+
+	if (git_path_isdir("alternate"))
+		git_futils_rmdir_r("alternate", 1);
 }
 
 void test_repo_open__bare_empty_repo(void)
 {
-	cl_git_pass(git_repository_open(&repo, cl_fixture("empty_bare.git")));
+	git_repository *repo = cl_git_sandbox_init("empty_bare.git");
 
 	cl_assert(git_repository_path(repo) != NULL);
 	cl_assert(git__suffixcmp(git_repository_path(repo), "/") == 0);
-
 	cl_assert(git_repository_workdir(repo) == NULL);
 }
 
 void test_repo_open__standard_empty_repo_through_gitdir(void)
 {
+	git_repository *repo;
+
 	cl_git_pass(git_repository_open(&repo, cl_fixture("empty_standard_repo/.gitted")));
 
 	cl_assert(git_repository_path(repo) != NULL);
@@ -27,20 +29,246 @@ void test_repo_open__standard_empty_repo_through_gitdir(void)
 
 	cl_assert(git_repository_workdir(repo) != NULL);
 	cl_assert(git__suffixcmp(git_repository_workdir(repo), "/") == 0);
+
+	git_repository_free(repo);
 }
 
 void test_repo_open__standard_empty_repo_through_workdir(void)
 {
-	cl_fixture_sandbox("empty_standard_repo");
-	cl_git_pass(p_rename("empty_standard_repo/.gitted", "empty_standard_repo/.git"));
-
-	cl_git_pass(git_repository_open(&repo, "empty_standard_repo"));
+	git_repository *repo = cl_git_sandbox_init("empty_standard_repo");
 
 	cl_assert(git_repository_path(repo) != NULL);
 	cl_assert(git__suffixcmp(git_repository_path(repo), "/") == 0);
 
 	cl_assert(git_repository_workdir(repo) != NULL);
 	cl_assert(git__suffixcmp(git_repository_workdir(repo), "/") == 0);
+}
+
+
+void test_repo_open__open_with_discover(void)
+{
+	static const char *variants[] = {
+		"attr", "attr/", "attr/.git", "attr/.git/",
+		"attr/sub", "attr/sub/", "attr/sub/sub", "attr/sub/sub/",
+		NULL
+	};
+	git_repository *repo;
+	const char **scan;
+
+	cl_fixture_sandbox("attr");
+	cl_git_pass(p_rename("attr/.gitted", "attr/.git"));
+
+	for (scan = variants; *scan != NULL; scan++) {
+		cl_git_pass(git_repository_open_ext(&repo, *scan, 0, NULL));
+		cl_assert(git__suffixcmp(git_repository_path(repo), "attr/.git/") == 0);
+		cl_assert(git__suffixcmp(git_repository_workdir(repo), "attr/") == 0);
+		git_repository_free(repo);
+	}
+
+	cl_fixture_cleanup("attr");
+}
+
+void test_repo_open__gitlinked(void)
+{
+	/* need to have both repo dir and workdir set up correctly */
+	git_repository *repo = cl_git_sandbox_init("empty_standard_repo");
+	git_repository *repo2;
+
+	cl_must_pass(p_mkdir("alternate", 0777));
+	cl_git_mkfile("alternate/.git", "gitdir: ../empty_standard_repo/.git");
+
+	cl_git_pass(git_repository_open(&repo2, "alternate"));
+
+	cl_assert(git_repository_path(repo2) != NULL);
+	cl_assert_(git__suffixcmp(git_repository_path(repo2), "empty_standard_repo/.git/") == 0, git_repository_path(repo2));
+	cl_assert_equal_s(git_repository_path(repo), git_repository_path(repo2));
+
+	cl_assert(git_repository_workdir(repo2) != NULL);
+	cl_assert_(git__suffixcmp(git_repository_workdir(repo2), "alternate/") == 0, git_repository_workdir(repo2));
+
+	git_repository_free(repo2);
+}
+
+void test_repo_open__from_git_new_workdir(void)
+{
+	/* The git-new-workdir script that ships with git sets up a bunch of
+	 * symlinks to create a second workdir that shares the object db with
+	 * another checkout.  Libgit2 can open a repo that has been configured
+	 * this way.
+	 */
+	cl_git_sandbox_init("empty_standard_repo");
+
+#ifndef GIT_WIN32
+	git_repository *repo2;
+	git_buf link_tgt = GIT_BUF_INIT, link = GIT_BUF_INIT, body = GIT_BUF_INIT;
+	const char **scan;
+	int link_fd;
+	static const char *links[] = {
+		"config", "refs", "logs/refs", "objects", "info", "hooks",
+		"packed-refs", "remotes", "rr-cache", "svn", NULL
+	};
+	static const char *copies[] = {
+		"HEAD", NULL
+	};
+
+	cl_git_pass(p_mkdir("alternate", 0777));
+	cl_git_pass(p_mkdir("alternate/.git", 0777));
+
+	for (scan = links; *scan != NULL; scan++) {
+		git_buf_joinpath(&link_tgt, "empty_standard_repo/.git", *scan);
+		if (git_path_exists(link_tgt.ptr)) {
+			git_buf_joinpath(&link_tgt, "../../empty_standard_repo/.git", *scan);
+			git_buf_joinpath(&link, "alternate/.git", *scan);
+			if (strchr(*scan, '/'))
+				git_futils_mkpath2file(link.ptr, 0777);
+			cl_assert_(symlink(link_tgt.ptr, link.ptr) == 0, strerror(errno));
+		}
+	}
+	for (scan = copies; *scan != NULL; scan++) {
+		git_buf_joinpath(&link_tgt, "empty_standard_repo/.git", *scan);
+		if (git_path_exists(link_tgt.ptr)) {
+			git_buf_joinpath(&link, "alternate/.git", *scan);
+			cl_git_pass(git_futils_readbuffer(&body, link_tgt.ptr));
+
+			cl_assert((link_fd = git_futils_creat_withpath(link.ptr, 0777, 0666)) >= 0);
+			cl_must_pass(p_write(link_fd, body.ptr, body.size));
+			p_close(link_fd);
+		}
+	}
+
+	git_buf_free(&link_tgt);
+	git_buf_free(&link);
+	git_buf_free(&body);
+
+
+	cl_git_pass(git_repository_open(&repo2, "alternate"));
+
+	cl_assert(git_repository_path(repo2) != NULL);
+	cl_assert_(git__suffixcmp(git_repository_path(repo2), "alternate/.git/") == 0, git_repository_path(repo2));
+
+	cl_assert(git_repository_workdir(repo2) != NULL);
+	cl_assert_(git__suffixcmp(git_repository_workdir(repo2), "alternate/") == 0, git_repository_workdir(repo2));
+
+	git_repository_free(repo2);
+#endif
+}
+
+void test_repo_open__failures(void)
+{
+	git_repository *base, *repo;
+	git_buf ceiling = GIT_BUF_INIT;
+
+	base = cl_git_sandbox_init("attr");
+	cl_git_pass(git_buf_sets(&ceiling, git_repository_workdir(base)));
+
+	/* fail with no searching */
+	cl_git_fail(git_repository_open(&repo, "attr/sub"));
+	cl_git_fail(git_repository_open_ext(
+		&repo, "attr/sub", GIT_REPOSITORY_OPEN_NO_SEARCH, NULL));
+
+	/* fail with ceiling too low */
+	cl_git_pass(git_buf_joinpath(&ceiling, ceiling.ptr, "sub"));
+	cl_git_fail(git_repository_open_ext(&repo, "attr/sub", 0, ceiling.ptr));
+
+	/* fail with no repo */
+	cl_git_pass(p_mkdir("alternate", 0777));
+	cl_git_pass(p_mkdir("alternate/.git", 0777));
+	cl_git_fail(git_repository_open_ext(&repo, "alternate", 0, NULL));
+	cl_git_fail(git_repository_open_ext(&repo, "alternate/.git", 0, NULL));
+
+	git_buf_free(&ceiling);
+}
+
+void test_repo_open__bad_gitlinks(void)
+{
+	git_repository *repo;
+	static const char *bad_links[] = {
+		"garbage\n", "gitdir", "gitdir:\n", "gitdir: foobar",
+		"gitdir: ../invalid", "gitdir: ../invalid2",
+		"gitdir: ../attr/.git with extra stuff",
+		NULL
+	};
+	const char **scan;
+
+	cl_git_sandbox_init("attr");
+
+	cl_git_pass(p_mkdir("alternate", 0777));
+	cl_git_pass(p_mkdir("invalid", 0777));
+	cl_git_pass(git_futils_mkdir_r("invalid2/.git", NULL, 0777));
+
+	for (scan = bad_links; *scan != NULL; scan++) {
+		cl_git_rewritefile("alternate/.git", *scan);
+		cl_git_fail(git_repository_open_ext(&repo, "alternate", 0, NULL));
+	}
+
+	git_futils_rmdir_r("invalid", 1);
+	git_futils_rmdir_r("invalid2", 1);
+}
+
+static void unposix_path(git_buf *path)
+{
+	char *src, *tgt;
+
+	src = tgt = path->ptr;
+
+	/* convert "/d/..." to "d:\..." */
+	if (src[0] == '/' && isalpha(src[1]) && src[2] == '/') {
+		*tgt++ = src[1];
+		*tgt++ = ':';
+		*tgt++ = '\\';
+		src += 3;
+	}
+
+	while (*src) {
+		*tgt++ = (*src == '/') ? '\\' : *src;
+		src++;
+	}
+
+	*tgt = '\0';
+}
+
+void test_repo_open__win32_path(void)
+{
+#ifdef GIT_WIN32
+	git_repository *repo = cl_git_sandbox_init("empty_standard_repo"), *repo2;
+	git_buf winpath = GIT_BUF_INIT;
+	char *src, *tgt;
+	static const char *repo_path = "empty_standard_repo/.git/";
+	static const char *repo_wd   = "empty_standard_repo/";
+
+	cl_assert(git__suffixcmp(git_repository_path(repo), repo_path) == 0);
+	cl_assert(git__suffixcmp(git_repository_workdir(repo), repo_wd) == 0);
+
+	cl_git_pass(git_buf_sets(&winpath, git_repository_path(repo)));
+	unposix_path(&winpath);
+	cl_git_pass(git_repository_open(&repo2, winpath.ptr));
+	cl_assert(git__suffixcmp(git_repository_path(repo2), repo_path) == 0);
+	cl_assert(git__suffixcmp(git_repository_workdir(repo2), repo_wd) == 0);
+	git_repository_free(repo2);
+
+	cl_git_pass(git_buf_sets(&winpath, git_repository_path(repo)));
+	git_buf_truncate(&winpath, winpath.size - 1); /* remove trailing '/' */
+	unposix_path(&winpath);
+	cl_git_pass(git_repository_open(&repo2, winpath.ptr));
+	cl_assert(git__suffixcmp(git_repository_path(repo2), repo_path) == 0);
+	cl_assert(git__suffixcmp(git_repository_workdir(repo2), repo_wd) == 0);
+	git_repository_free(repo2);
+
+	cl_git_pass(git_buf_sets(&winpath, git_repository_workdir(repo)));
+	unposix_path(&winpath);
+	cl_git_pass(git_repository_open(&repo2, winpath.ptr));
+	cl_assert(git__suffixcmp(git_repository_path(repo2), repo_path) == 0);
+	cl_assert(git__suffixcmp(git_repository_workdir(repo2), repo_wd) == 0);
+	git_repository_free(repo2);
+
+	cl_git_pass(git_buf_sets(&winpath, git_repository_workdir(repo)));
+	git_buf_truncate(&winpath, winpath.size - 1); /* remove trailing '/' */
+	unposix_path(&winpath);
+	cl_git_pass(git_repository_open(&repo2, winpath.ptr));
+	cl_assert(git__suffixcmp(git_repository_path(repo2), repo_path) == 0);
+	cl_assert(git__suffixcmp(git_repository_workdir(repo2), repo_wd) == 0);
+	git_repository_free(repo2);
 
-	cl_fixture_cleanup("empty_standard_repo");
+	git_buf_free(&winpath);
+#endif
 }