Skip to content

Commit e663674

Browse files
dschogitster
authored andcommitted
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 <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent e5392c5 commit e663674

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

dir.c

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -642,3 +642,41 @@ file_exists(const char *f)
642642
struct stat sb;
643643
return stat(f, &sb) == 0;
644644
}
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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,4 +61,7 @@ extern void add_exclude(const char *string, const char *base,
6161
extern int file_exists(const char *);
6262
extern struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len);
6363

64+
extern char *get_relative_cwd(char *buffer, int size, const char *dir);
65+
extern int is_inside_dir(const char *dir);
66+
6467
#endif

0 commit comments

Comments
 (0)