Merge branch 'mk/blame-error-message' into maint
[git] / path.c
1 /*
2  * Utilities for paths and pathnames
3  */
4 #include "cache.h"
5 #include "strbuf.h"
6 #include "string-list.h"
7 #include "dir.h"
8
9 static int get_st_mode_bits(const char *path, int *mode)
10 {
11         struct stat st;
12         if (lstat(path, &st) < 0)
13                 return -1;
14         *mode = st.st_mode;
15         return 0;
16 }
17
18 static char bad_path[] = "/bad-path/";
19
20 static struct strbuf *get_pathname(void)
21 {
22         static struct strbuf pathname_array[4] = {
23                 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
24         };
25         static int index;
26         struct strbuf *sb = &pathname_array[3 & ++index];
27         strbuf_reset(sb);
28         return sb;
29 }
30
31 static char *cleanup_path(char *path)
32 {
33         /* Clean it up */
34         if (!memcmp(path, "./", 2)) {
35                 path += 2;
36                 while (*path == '/')
37                         path++;
38         }
39         return path;
40 }
41
42 static void strbuf_cleanup_path(struct strbuf *sb)
43 {
44         char *path = cleanup_path(sb->buf);
45         if (path > sb->buf)
46                 strbuf_remove(sb, 0, path - sb->buf);
47 }
48
49 char *mksnpath(char *buf, size_t n, const char *fmt, ...)
50 {
51         va_list args;
52         unsigned len;
53
54         va_start(args, fmt);
55         len = vsnprintf(buf, n, fmt, args);
56         va_end(args);
57         if (len >= n) {
58                 strlcpy(buf, bad_path, n);
59                 return buf;
60         }
61         return cleanup_path(buf);
62 }
63
64 static int dir_prefix(const char *buf, const char *dir)
65 {
66         int len = strlen(dir);
67         return !strncmp(buf, dir, len) &&
68                 (is_dir_sep(buf[len]) || buf[len] == '\0');
69 }
70
71 /* $buf =~ m|$dir/+$file| but without regex */
72 static int is_dir_file(const char *buf, const char *dir, const char *file)
73 {
74         int len = strlen(dir);
75         if (strncmp(buf, dir, len) || !is_dir_sep(buf[len]))
76                 return 0;
77         while (is_dir_sep(buf[len]))
78                 len++;
79         return !strcmp(buf + len, file);
80 }
81
82 static void replace_dir(struct strbuf *buf, int len, const char *newdir)
83 {
84         int newlen = strlen(newdir);
85         int need_sep = (buf->buf[len] && !is_dir_sep(buf->buf[len])) &&
86                 !is_dir_sep(newdir[newlen - 1]);
87         if (need_sep)
88                 len--;   /* keep one char, to be replaced with '/'  */
89         strbuf_splice(buf, 0, len, newdir, newlen);
90         if (need_sep)
91                 buf->buf[newlen] = '/';
92 }
93
94 static const char *common_list[] = {
95         "/branches", "/hooks", "/info", "!/logs", "/lost-found",
96         "/objects", "/refs", "/remotes", "/worktrees", "/rr-cache", "/svn",
97         "config", "!gc.pid", "packed-refs", "shallow",
98         NULL
99 };
100
101 static void update_common_dir(struct strbuf *buf, int git_dir_len, const char *common_dir)
102 {
103         char *base = buf->buf + git_dir_len;
104         const char **p;
105
106         if (is_dir_file(base, "logs", "HEAD") ||
107             is_dir_file(base, "info", "sparse-checkout"))
108                 return; /* keep this in $GIT_DIR */
109         for (p = common_list; *p; p++) {
110                 const char *path = *p;
111                 int is_dir = 0;
112                 if (*path == '!')
113                         path++;
114                 if (*path == '/') {
115                         path++;
116                         is_dir = 1;
117                 }
118
119                 if (!common_dir)
120                         common_dir = get_git_common_dir();
121
122                 if (is_dir && dir_prefix(base, path)) {
123                         replace_dir(buf, git_dir_len, common_dir);
124                         return;
125                 }
126                 if (!is_dir && !strcmp(base, path)) {
127                         replace_dir(buf, git_dir_len, common_dir);
128                         return;
129                 }
130         }
131 }
132
133 void report_linked_checkout_garbage(void)
134 {
135         struct strbuf sb = STRBUF_INIT;
136         const char **p;
137         int len;
138
139         if (!git_common_dir_env)
140                 return;
141         strbuf_addf(&sb, "%s/", get_git_dir());
142         len = sb.len;
143         for (p = common_list; *p; p++) {
144                 const char *path = *p;
145                 if (*path == '!')
146                         continue;
147                 strbuf_setlen(&sb, len);
148                 strbuf_addstr(&sb, path);
149                 if (file_exists(sb.buf))
150                         report_garbage("unused in linked checkout", sb.buf);
151         }
152         strbuf_release(&sb);
153 }
154
155 static void adjust_git_path(struct strbuf *buf, int git_dir_len)
156 {
157         const char *base = buf->buf + git_dir_len;
158         if (git_graft_env && is_dir_file(base, "info", "grafts"))
159                 strbuf_splice(buf, 0, buf->len,
160                               get_graft_file(), strlen(get_graft_file()));
161         else if (git_index_env && !strcmp(base, "index"))
162                 strbuf_splice(buf, 0, buf->len,
163                               get_index_file(), strlen(get_index_file()));
164         else if (git_db_env && dir_prefix(base, "objects"))
165                 replace_dir(buf, git_dir_len + 7, get_object_directory());
166         else if (git_common_dir_env)
167                 update_common_dir(buf, git_dir_len, NULL);
168 }
169
170 static void do_git_path(struct strbuf *buf, const char *fmt, va_list args)
171 {
172         int gitdir_len;
173         strbuf_addstr(buf, get_git_dir());
174         if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
175                 strbuf_addch(buf, '/');
176         gitdir_len = buf->len;
177         strbuf_vaddf(buf, fmt, args);
178         adjust_git_path(buf, gitdir_len);
179         strbuf_cleanup_path(buf);
180 }
181
182 void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
183 {
184         va_list args;
185         va_start(args, fmt);
186         do_git_path(sb, fmt, args);
187         va_end(args);
188 }
189
190 const char *git_path(const char *fmt, ...)
191 {
192         struct strbuf *pathname = get_pathname();
193         va_list args;
194         va_start(args, fmt);
195         do_git_path(pathname, fmt, args);
196         va_end(args);
197         return pathname->buf;
198 }
199
200 char *git_pathdup(const char *fmt, ...)
201 {
202         struct strbuf path = STRBUF_INIT;
203         va_list args;
204         va_start(args, fmt);
205         do_git_path(&path, fmt, args);
206         va_end(args);
207         return strbuf_detach(&path, NULL);
208 }
209
210 char *mkpathdup(const char *fmt, ...)
211 {
212         struct strbuf sb = STRBUF_INIT;
213         va_list args;
214         va_start(args, fmt);
215         strbuf_vaddf(&sb, fmt, args);
216         va_end(args);
217         strbuf_cleanup_path(&sb);
218         return strbuf_detach(&sb, NULL);
219 }
220
221 const char *mkpath(const char *fmt, ...)
222 {
223         va_list args;
224         struct strbuf *pathname = get_pathname();
225         va_start(args, fmt);
226         strbuf_vaddf(pathname, fmt, args);
227         va_end(args);
228         return cleanup_path(pathname->buf);
229 }
230
231 static void do_submodule_path(struct strbuf *buf, const char *path,
232                               const char *fmt, va_list args)
233 {
234         const char *git_dir;
235         struct strbuf git_submodule_common_dir = STRBUF_INIT;
236         struct strbuf git_submodule_dir = STRBUF_INIT;
237
238         strbuf_addstr(buf, path);
239         if (buf->len && buf->buf[buf->len - 1] != '/')
240                 strbuf_addch(buf, '/');
241         strbuf_addstr(buf, ".git");
242
243         git_dir = read_gitfile(buf->buf);
244         if (git_dir) {
245                 strbuf_reset(buf);
246                 strbuf_addstr(buf, git_dir);
247         }
248         strbuf_addch(buf, '/');
249         strbuf_addstr(&git_submodule_dir, buf->buf);
250
251         strbuf_vaddf(buf, fmt, args);
252
253         if (get_common_dir_noenv(&git_submodule_common_dir, git_submodule_dir.buf))
254                 update_common_dir(buf, git_submodule_dir.len, git_submodule_common_dir.buf);
255
256         strbuf_cleanup_path(buf);
257
258         strbuf_release(&git_submodule_dir);
259         strbuf_release(&git_submodule_common_dir);
260 }
261
262 char *git_pathdup_submodule(const char *path, const char *fmt, ...)
263 {
264         va_list args;
265         struct strbuf buf = STRBUF_INIT;
266         va_start(args, fmt);
267         do_submodule_path(&buf, path, fmt, args);
268         va_end(args);
269         return strbuf_detach(&buf, NULL);
270 }
271
272 void strbuf_git_path_submodule(struct strbuf *buf, const char *path,
273                                const char *fmt, ...)
274 {
275         va_list args;
276         va_start(args, fmt);
277         do_submodule_path(buf, path, fmt, args);
278         va_end(args);
279 }
280
281 int validate_headref(const char *path)
282 {
283         struct stat st;
284         char *buf, buffer[256];
285         unsigned char sha1[20];
286         int fd;
287         ssize_t len;
288
289         if (lstat(path, &st) < 0)
290                 return -1;
291
292         /* Make sure it is a "refs/.." symlink */
293         if (S_ISLNK(st.st_mode)) {
294                 len = readlink(path, buffer, sizeof(buffer)-1);
295                 if (len >= 5 && !memcmp("refs/", buffer, 5))
296                         return 0;
297                 return -1;
298         }
299
300         /*
301          * Anything else, just open it and try to see if it is a symbolic ref.
302          */
303         fd = open(path, O_RDONLY);
304         if (fd < 0)
305                 return -1;
306         len = read_in_full(fd, buffer, sizeof(buffer)-1);
307         close(fd);
308
309         /*
310          * Is it a symbolic ref?
311          */
312         if (len < 4)
313                 return -1;
314         if (!memcmp("ref:", buffer, 4)) {
315                 buf = buffer + 4;
316                 len -= 4;
317                 while (len && isspace(*buf))
318                         buf++, len--;
319                 if (len >= 5 && !memcmp("refs/", buf, 5))
320                         return 0;
321         }
322
323         /*
324          * Is this a detached HEAD?
325          */
326         if (!get_sha1_hex(buffer, sha1))
327                 return 0;
328
329         return -1;
330 }
331
332 static struct passwd *getpw_str(const char *username, size_t len)
333 {
334         struct passwd *pw;
335         char *username_z = xmemdupz(username, len);
336         pw = getpwnam(username_z);
337         free(username_z);
338         return pw;
339 }
340
341 /*
342  * Return a string with ~ and ~user expanded via getpw*.  If buf != NULL,
343  * then it is a newly allocated string. Returns NULL on getpw failure or
344  * if path is NULL.
345  */
346 char *expand_user_path(const char *path)
347 {
348         struct strbuf user_path = STRBUF_INIT;
349         const char *to_copy = path;
350
351         if (path == NULL)
352                 goto return_null;
353         if (path[0] == '~') {
354                 const char *first_slash = strchrnul(path, '/');
355                 const char *username = path + 1;
356                 size_t username_len = first_slash - username;
357                 if (username_len == 0) {
358                         const char *home = getenv("HOME");
359                         if (!home)
360                                 goto return_null;
361                         strbuf_addstr(&user_path, home);
362                 } else {
363                         struct passwd *pw = getpw_str(username, username_len);
364                         if (!pw)
365                                 goto return_null;
366                         strbuf_addstr(&user_path, pw->pw_dir);
367                 }
368                 to_copy = first_slash;
369         }
370         strbuf_addstr(&user_path, to_copy);
371         return strbuf_detach(&user_path, NULL);
372 return_null:
373         strbuf_release(&user_path);
374         return NULL;
375 }
376
377 /*
378  * First, one directory to try is determined by the following algorithm.
379  *
380  * (0) If "strict" is given, the path is used as given and no DWIM is
381  *     done. Otherwise:
382  * (1) "~/path" to mean path under the running user's home directory;
383  * (2) "~user/path" to mean path under named user's home directory;
384  * (3) "relative/path" to mean cwd relative directory; or
385  * (4) "/absolute/path" to mean absolute directory.
386  *
387  * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
388  * in this order. We select the first one that is a valid git repository, and
389  * chdir() to it. If none match, or we fail to chdir, we return NULL.
390  *
391  * If all goes well, we return the directory we used to chdir() (but
392  * before ~user is expanded), avoiding getcwd() resolving symbolic
393  * links.  User relative paths are also returned as they are given,
394  * except DWIM suffixing.
395  */
396 const char *enter_repo(const char *path, int strict)
397 {
398         static char used_path[PATH_MAX];
399         static char validated_path[PATH_MAX];
400
401         if (!path)
402                 return NULL;
403
404         if (!strict) {
405                 static const char *suffix[] = {
406                         "/.git", "", ".git/.git", ".git", NULL,
407                 };
408                 const char *gitfile;
409                 int len = strlen(path);
410                 int i;
411                 while ((1 < len) && (path[len-1] == '/'))
412                         len--;
413
414                 if (PATH_MAX <= len)
415                         return NULL;
416                 strncpy(used_path, path, len); used_path[len] = 0 ;
417                 strcpy(validated_path, used_path);
418
419                 if (used_path[0] == '~') {
420                         char *newpath = expand_user_path(used_path);
421                         if (!newpath || (PATH_MAX - 10 < strlen(newpath))) {
422                                 free(newpath);
423                                 return NULL;
424                         }
425                         /*
426                          * Copy back into the static buffer. A pity
427                          * since newpath was not bounded, but other
428                          * branches of the if are limited by PATH_MAX
429                          * anyway.
430                          */
431                         strcpy(used_path, newpath); free(newpath);
432                 }
433                 else if (PATH_MAX - 10 < len)
434                         return NULL;
435                 len = strlen(used_path);
436                 for (i = 0; suffix[i]; i++) {
437                         struct stat st;
438                         strcpy(used_path + len, suffix[i]);
439                         if (!stat(used_path, &st) &&
440                             (S_ISREG(st.st_mode) ||
441                             (S_ISDIR(st.st_mode) && is_git_directory(used_path)))) {
442                                 strcat(validated_path, suffix[i]);
443                                 break;
444                         }
445                 }
446                 if (!suffix[i])
447                         return NULL;
448                 gitfile = read_gitfile(used_path) ;
449                 if (gitfile)
450                         strcpy(used_path, gitfile);
451                 if (chdir(used_path))
452                         return NULL;
453                 path = validated_path;
454         }
455         else if (chdir(path))
456                 return NULL;
457
458         if (access("objects", X_OK) == 0 && access("refs", X_OK) == 0 &&
459             validate_headref("HEAD") == 0) {
460                 set_git_dir(".");
461                 check_repository_format();
462                 return path;
463         }
464
465         return NULL;
466 }
467
468 static int calc_shared_perm(int mode)
469 {
470         int tweak;
471
472         if (shared_repository < 0)
473                 tweak = -shared_repository;
474         else
475                 tweak = shared_repository;
476
477         if (!(mode & S_IWUSR))
478                 tweak &= ~0222;
479         if (mode & S_IXUSR)
480                 /* Copy read bits to execute bits */
481                 tweak |= (tweak & 0444) >> 2;
482         if (shared_repository < 0)
483                 mode = (mode & ~0777) | tweak;
484         else
485                 mode |= tweak;
486
487         return mode;
488 }
489
490
491 int adjust_shared_perm(const char *path)
492 {
493         int old_mode, new_mode;
494
495         if (!shared_repository)
496                 return 0;
497         if (get_st_mode_bits(path, &old_mode) < 0)
498                 return -1;
499
500         new_mode = calc_shared_perm(old_mode);
501         if (S_ISDIR(old_mode)) {
502                 /* Copy read bits to execute bits */
503                 new_mode |= (new_mode & 0444) >> 2;
504                 new_mode |= FORCE_DIR_SET_GID;
505         }
506
507         if (((old_mode ^ new_mode) & ~S_IFMT) &&
508                         chmod(path, (new_mode & ~S_IFMT)) < 0)
509                 return -2;
510         return 0;
511 }
512
513 static int have_same_root(const char *path1, const char *path2)
514 {
515         int is_abs1, is_abs2;
516
517         is_abs1 = is_absolute_path(path1);
518         is_abs2 = is_absolute_path(path2);
519         return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
520                (!is_abs1 && !is_abs2);
521 }
522
523 /*
524  * Give path as relative to prefix.
525  *
526  * The strbuf may or may not be used, so do not assume it contains the
527  * returned path.
528  */
529 const char *relative_path(const char *in, const char *prefix,
530                           struct strbuf *sb)
531 {
532         int in_len = in ? strlen(in) : 0;
533         int prefix_len = prefix ? strlen(prefix) : 0;
534         int in_off = 0;
535         int prefix_off = 0;
536         int i = 0, j = 0;
537
538         if (!in_len)
539                 return "./";
540         else if (!prefix_len)
541                 return in;
542
543         if (have_same_root(in, prefix)) {
544                 /* bypass dos_drive, for "c:" is identical to "C:" */
545                 if (has_dos_drive_prefix(in)) {
546                         i = 2;
547                         j = 2;
548                 }
549         } else {
550                 return in;
551         }
552
553         while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
554                 if (is_dir_sep(prefix[i])) {
555                         while (is_dir_sep(prefix[i]))
556                                 i++;
557                         while (is_dir_sep(in[j]))
558                                 j++;
559                         prefix_off = i;
560                         in_off = j;
561                 } else {
562                         i++;
563                         j++;
564                 }
565         }
566
567         if (
568             /* "prefix" seems like prefix of "in" */
569             i >= prefix_len &&
570             /*
571              * but "/foo" is not a prefix of "/foobar"
572              * (i.e. prefix not end with '/')
573              */
574             prefix_off < prefix_len) {
575                 if (j >= in_len) {
576                         /* in="/a/b", prefix="/a/b" */
577                         in_off = in_len;
578                 } else if (is_dir_sep(in[j])) {
579                         /* in="/a/b/c", prefix="/a/b" */
580                         while (is_dir_sep(in[j]))
581                                 j++;
582                         in_off = j;
583                 } else {
584                         /* in="/a/bbb/c", prefix="/a/b" */
585                         i = prefix_off;
586                 }
587         } else if (
588                    /* "in" is short than "prefix" */
589                    j >= in_len &&
590                    /* "in" not end with '/' */
591                    in_off < in_len) {
592                 if (is_dir_sep(prefix[i])) {
593                         /* in="/a/b", prefix="/a/b/c/" */
594                         while (is_dir_sep(prefix[i]))
595                                 i++;
596                         in_off = in_len;
597                 }
598         }
599         in += in_off;
600         in_len -= in_off;
601
602         if (i >= prefix_len) {
603                 if (!in_len)
604                         return "./";
605                 else
606                         return in;
607         }
608
609         strbuf_reset(sb);
610         strbuf_grow(sb, in_len);
611
612         while (i < prefix_len) {
613                 if (is_dir_sep(prefix[i])) {
614                         strbuf_addstr(sb, "../");
615                         while (is_dir_sep(prefix[i]))
616                                 i++;
617                         continue;
618                 }
619                 i++;
620         }
621         if (!is_dir_sep(prefix[prefix_len - 1]))
622                 strbuf_addstr(sb, "../");
623
624         strbuf_addstr(sb, in);
625
626         return sb->buf;
627 }
628
629 /*
630  * A simpler implementation of relative_path
631  *
632  * Get relative path by removing "prefix" from "in". This function
633  * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
634  * to increase performance when traversing the path to work_tree.
635  */
636 const char *remove_leading_path(const char *in, const char *prefix)
637 {
638         static char buf[PATH_MAX + 1];
639         int i = 0, j = 0;
640
641         if (!prefix || !prefix[0])
642                 return in;
643         while (prefix[i]) {
644                 if (is_dir_sep(prefix[i])) {
645                         if (!is_dir_sep(in[j]))
646                                 return in;
647                         while (is_dir_sep(prefix[i]))
648                                 i++;
649                         while (is_dir_sep(in[j]))
650                                 j++;
651                         continue;
652                 } else if (in[j] != prefix[i]) {
653                         return in;
654                 }
655                 i++;
656                 j++;
657         }
658         if (
659             /* "/foo" is a prefix of "/foo" */
660             in[j] &&
661             /* "/foo" is not a prefix of "/foobar" */
662             !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
663            )
664                 return in;
665         while (is_dir_sep(in[j]))
666                 j++;
667         if (!in[j])
668                 strcpy(buf, ".");
669         else
670                 strcpy(buf, in + j);
671         return buf;
672 }
673
674 /*
675  * It is okay if dst == src, but they should not overlap otherwise.
676  *
677  * Performs the following normalizations on src, storing the result in dst:
678  * - Ensures that components are separated by '/' (Windows only)
679  * - Squashes sequences of '/'.
680  * - Removes "." components.
681  * - Removes ".." components, and the components the precede them.
682  * Returns failure (non-zero) if a ".." component appears as first path
683  * component anytime during the normalization. Otherwise, returns success (0).
684  *
685  * Note that this function is purely textual.  It does not follow symlinks,
686  * verify the existence of the path, or make any system calls.
687  *
688  * prefix_len != NULL is for a specific case of prefix_pathspec():
689  * assume that src == dst and src[0..prefix_len-1] is already
690  * normalized, any time "../" eats up to the prefix_len part,
691  * prefix_len is reduced. In the end prefix_len is the remaining
692  * prefix that has not been overridden by user pathspec.
693  *
694  * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
695  * For everything but the root folder itself, the normalized path should not
696  * end with a '/', then the callers need to be fixed up accordingly.
697  *
698  */
699 int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
700 {
701         char *dst0;
702
703         if (has_dos_drive_prefix(src)) {
704                 *dst++ = *src++;
705                 *dst++ = *src++;
706         }
707         dst0 = dst;
708
709         if (is_dir_sep(*src)) {
710                 *dst++ = '/';
711                 while (is_dir_sep(*src))
712                         src++;
713         }
714
715         for (;;) {
716                 char c = *src;
717
718                 /*
719                  * A path component that begins with . could be
720                  * special:
721                  * (1) "." and ends   -- ignore and terminate.
722                  * (2) "./"           -- ignore them, eat slash and continue.
723                  * (3) ".." and ends  -- strip one and terminate.
724                  * (4) "../"          -- strip one, eat slash and continue.
725                  */
726                 if (c == '.') {
727                         if (!src[1]) {
728                                 /* (1) */
729                                 src++;
730                         } else if (is_dir_sep(src[1])) {
731                                 /* (2) */
732                                 src += 2;
733                                 while (is_dir_sep(*src))
734                                         src++;
735                                 continue;
736                         } else if (src[1] == '.') {
737                                 if (!src[2]) {
738                                         /* (3) */
739                                         src += 2;
740                                         goto up_one;
741                                 } else if (is_dir_sep(src[2])) {
742                                         /* (4) */
743                                         src += 3;
744                                         while (is_dir_sep(*src))
745                                                 src++;
746                                         goto up_one;
747                                 }
748                         }
749                 }
750
751                 /* copy up to the next '/', and eat all '/' */
752                 while ((c = *src++) != '\0' && !is_dir_sep(c))
753                         *dst++ = c;
754                 if (is_dir_sep(c)) {
755                         *dst++ = '/';
756                         while (is_dir_sep(c))
757                                 c = *src++;
758                         src--;
759                 } else if (!c)
760                         break;
761                 continue;
762
763         up_one:
764                 /*
765                  * dst0..dst is prefix portion, and dst[-1] is '/';
766                  * go up one level.
767                  */
768                 dst--;  /* go to trailing '/' */
769                 if (dst <= dst0)
770                         return -1;
771                 /* Windows: dst[-1] cannot be backslash anymore */
772                 while (dst0 < dst && dst[-1] != '/')
773                         dst--;
774                 if (prefix_len && *prefix_len > dst - dst0)
775                         *prefix_len = dst - dst0;
776         }
777         *dst = '\0';
778         return 0;
779 }
780
781 int normalize_path_copy(char *dst, const char *src)
782 {
783         return normalize_path_copy_len(dst, src, NULL);
784 }
785
786 /*
787  * path = Canonical absolute path
788  * prefixes = string_list containing normalized, absolute paths without
789  * trailing slashes (except for the root directory, which is denoted by "/").
790  *
791  * Determines, for each path in prefixes, whether the "prefix"
792  * is an ancestor directory of path.  Returns the length of the longest
793  * ancestor directory, excluding any trailing slashes, or -1 if no prefix
794  * is an ancestor.  (Note that this means 0 is returned if prefixes is
795  * ["/"].) "/foo" is not considered an ancestor of "/foobar".  Directories
796  * are not considered to be their own ancestors.  path must be in a
797  * canonical form: empty components, or "." or ".." components are not
798  * allowed.
799  */
800 int longest_ancestor_length(const char *path, struct string_list *prefixes)
801 {
802         int i, max_len = -1;
803
804         if (!strcmp(path, "/"))
805                 return -1;
806
807         for (i = 0; i < prefixes->nr; i++) {
808                 const char *ceil = prefixes->items[i].string;
809                 int len = strlen(ceil);
810
811                 if (len == 1 && ceil[0] == '/')
812                         len = 0; /* root matches anything, with length 0 */
813                 else if (!strncmp(path, ceil, len) && path[len] == '/')
814                         ; /* match of length len */
815                 else
816                         continue; /* no match */
817
818                 if (len > max_len)
819                         max_len = len;
820         }
821
822         return max_len;
823 }
824
825 /* strip arbitrary amount of directory separators at end of path */
826 static inline int chomp_trailing_dir_sep(const char *path, int len)
827 {
828         while (len && is_dir_sep(path[len - 1]))
829                 len--;
830         return len;
831 }
832
833 /*
834  * If path ends with suffix (complete path components), returns the
835  * part before suffix (sans trailing directory separators).
836  * Otherwise returns NULL.
837  */
838 char *strip_path_suffix(const char *path, const char *suffix)
839 {
840         int path_len = strlen(path), suffix_len = strlen(suffix);
841
842         while (suffix_len) {
843                 if (!path_len)
844                         return NULL;
845
846                 if (is_dir_sep(path[path_len - 1])) {
847                         if (!is_dir_sep(suffix[suffix_len - 1]))
848                                 return NULL;
849                         path_len = chomp_trailing_dir_sep(path, path_len);
850                         suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
851                 }
852                 else if (path[--path_len] != suffix[--suffix_len])
853                         return NULL;
854         }
855
856         if (path_len && !is_dir_sep(path[path_len - 1]))
857                 return NULL;
858         return xstrndup(path, chomp_trailing_dir_sep(path, path_len));
859 }
860
861 int daemon_avoid_alias(const char *p)
862 {
863         int sl, ndot;
864
865         /*
866          * This resurrects the belts and suspenders paranoia check by HPA
867          * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
868          * does not do getcwd() based path canonicalization.
869          *
870          * sl becomes true immediately after seeing '/' and continues to
871          * be true as long as dots continue after that without intervening
872          * non-dot character.
873          */
874         if (!p || (*p != '/' && *p != '~'))
875                 return -1;
876         sl = 1; ndot = 0;
877         p++;
878
879         while (1) {
880                 char ch = *p++;
881                 if (sl) {
882                         if (ch == '.')
883                                 ndot++;
884                         else if (ch == '/') {
885                                 if (ndot < 3)
886                                         /* reject //, /./ and /../ */
887                                         return -1;
888                                 ndot = 0;
889                         }
890                         else if (ch == 0) {
891                                 if (0 < ndot && ndot < 3)
892                                         /* reject /.$ and /..$ */
893                                         return -1;
894                                 return 0;
895                         }
896                         else
897                                 sl = ndot = 0;
898                 }
899                 else if (ch == 0)
900                         return 0;
901                 else if (ch == '/') {
902                         sl = 1;
903                         ndot = 0;
904                 }
905         }
906 }
907
908 static int only_spaces_and_periods(const char *path, size_t len, size_t skip)
909 {
910         if (len < skip)
911                 return 0;
912         len -= skip;
913         path += skip;
914         while (len-- > 0) {
915                 char c = *(path++);
916                 if (c != ' ' && c != '.')
917                         return 0;
918         }
919         return 1;
920 }
921
922 int is_ntfs_dotgit(const char *name)
923 {
924         int len;
925
926         for (len = 0; ; len++)
927                 if (!name[len] || name[len] == '\\' || is_dir_sep(name[len])) {
928                         if (only_spaces_and_periods(name, len, 4) &&
929                                         !strncasecmp(name, ".git", 4))
930                                 return 1;
931                         if (only_spaces_and_periods(name, len, 5) &&
932                                         !strncasecmp(name, "git~1", 5))
933                                 return 1;
934                         if (name[len] != '\\')
935                                 return 0;
936                         name += len + 1;
937                         len = -1;
938                 }
939 }
940
941 char *xdg_config_home(const char *filename)
942 {
943         const char *home, *config_home;
944
945         assert(filename);
946         config_home = getenv("XDG_CONFIG_HOME");
947         if (config_home && *config_home)
948                 return mkpathdup("%s/git/%s", config_home, filename);
949
950         home = getenv("HOME");
951         if (home)
952                 return mkpathdup("%s/.config/git/%s", home, filename);
953         return NULL;
954 }
955
956 GIT_PATH_FUNC(git_path_cherry_pick_head, "CHERRY_PICK_HEAD")
957 GIT_PATH_FUNC(git_path_revert_head, "REVERT_HEAD")
958 GIT_PATH_FUNC(git_path_squash_msg, "SQUASH_MSG")
959 GIT_PATH_FUNC(git_path_merge_msg, "MERGE_MSG")
960 GIT_PATH_FUNC(git_path_merge_rr, "MERGE_RR")
961 GIT_PATH_FUNC(git_path_merge_mode, "MERGE_MODE")
962 GIT_PATH_FUNC(git_path_merge_head, "MERGE_HEAD")
963 GIT_PATH_FUNC(git_path_fetch_head, "FETCH_HEAD")
964 GIT_PATH_FUNC(git_path_shallow, "shallow")