Add functions get_relative_cwd() and is_inside_dir()
The function get_relative_cwd() works just as getcwd(), only that it takes an absolute path as additional parameter, returning the prefix of the current working directory relative to the given path. If the cwd is no subdirectory of the given path, it returns NULL. is_inside_dir() is just a trivial wrapper over get_relative_cwd(). Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Johannes Schindelin committed
Aug 1, 2007 at 01:29 UTC
e663674722d8a64a208d8c176d5bfc340c04b964
2 files changed
+41
dir.c
+38
@@ -642,3 +642,41 @@ file_exists(const char *f)
642
struct stat sb;
643
return stat(f, &sb) == 0;
644
}
645
+
646
+/*
647
+ * get_relative_cwd() gets the prefix of the current working directory
648
+ * relative to 'dir'. If we are not inside 'dir', it returns NULL.
649
+ * As a convenience, it also returns NULL if 'dir' is already NULL.
650
+ */
651
+char *get_relative_cwd(char *buffer, int size, const char *dir)
652
+{
653
+ char *cwd = buffer;
654
+
655
+ /*
656
+ * a lazy caller can pass a NULL returned from get_git_work_tree()
657
+ * and rely on this function to return NULL.
658
+ */
659
+ if (!dir)
660
+ return NULL;
661
+ if (!getcwd(buffer, size))
662
+ die("can't find the current directory: %s", strerror(errno));
663
+
664
+ if (!is_absolute_path(dir))
665
+ dir = make_absolute_path(dir);
666
+
667
+ while (*dir && *dir == *cwd) {
668
+ dir++;
669
+ cwd++;
670
+ }
671
+ if (*dir)
672
+ return NULL;
673
+ if (*cwd == '/')
674
+ return cwd + 1;
675
+ return cwd;
676
+}
677
+
678
+int is_inside_dir(const char *dir)
679
+{
680
+ char buffer[PATH_MAX];
681
+ return get_relative_cwd(buffer, sizeof(buffer), dir) != NULL;
682
+}
dir.h
+3
@@ -61,4 +61,7 @@ extern void add_exclude(const char *string, const char *base,
61
extern int file_exists(const char *);
62
extern struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len);
63
64
+extern char *get_relative_cwd(char *buffer, int size, const char *dir);
65
+extern int is_inside_dir(const char *dir);
66
+
67
#endif