]> git.ipfire.org Git - thirdparty/git.git/commitdiff
Add functions get_relative_cwd() and is_inside_dir()
authorJohannes Schindelin <Johannes.Schindelin@gmx.de>
Wed, 1 Aug 2007 00:29:17 +0000 (01:29 +0100)
committerJunio C Hamano <gitster@pobox.com>
Wed, 1 Aug 2007 07:38:30 +0000 (00:38 -0700)
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>
dir.c
dir.h

diff --git a/dir.c b/dir.c
index 8d8faf5d788b402d5fd4f5d724954fd2ee178fdb..b3329f41b2b8830d311f88be59037f7325e2b1e4 100644 (file)
--- a/dir.c
+++ b/dir.c
@@ -642,3 +642,41 @@ file_exists(const char *f)
   struct stat sb;
   return stat(f, &sb) == 0;
 }
+
+/*
+ * get_relative_cwd() gets the prefix of the current working directory
+ * relative to 'dir'.  If we are not inside 'dir', it returns NULL.
+ * As a convenience, it also returns NULL if 'dir' is already NULL.
+ */
+char *get_relative_cwd(char *buffer, int size, const char *dir)
+{
+       char *cwd = buffer;
+
+       /*
+        * a lazy caller can pass a NULL returned from get_git_work_tree()
+        * and rely on this function to return NULL.
+        */
+       if (!dir)
+               return NULL;
+       if (!getcwd(buffer, size))
+               die("can't find the current directory: %s", strerror(errno));
+
+       if (!is_absolute_path(dir))
+               dir = make_absolute_path(dir);
+
+       while (*dir && *dir == *cwd) {
+               dir++;
+               cwd++;
+       }
+       if (*dir)
+               return NULL;
+       if (*cwd == '/')
+               return cwd + 1;
+       return cwd;
+}
+
+int is_inside_dir(const char *dir)
+{
+       char buffer[PATH_MAX];
+       return get_relative_cwd(buffer, sizeof(buffer), dir) != NULL;
+}
diff --git a/dir.h b/dir.h
index ec0e8ababc7fa00d9bf039e0ad97d8639b70450f..f55a87b2cd5f2b4e06e14b4c1b832fc0a60ad319 100644 (file)
--- a/dir.h
+++ b/dir.h
@@ -61,4 +61,7 @@ extern void add_exclude(const char *string, const char *base,
 extern int file_exists(const char *);
 extern struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len);
 
+extern char *get_relative_cwd(char *buffer, int size, const char *dir);
+extern int is_inside_dir(const char *dir);
+
 #endif