diff options
author | Lennart Poettering <lennart@poettering.net> | 2015-05-13 17:42:10 +0200 |
---|---|---|
committer | Sven Eden <yamakuzure@gmx.net> | 2017-03-14 09:56:08 +0100 |
commit | 6785155e4ec3e478918481cd6321d96ec30c83b7 (patch) | |
tree | a0e7d6ed157706967a5842eb5de1834ebe9567c5 /src/shared/path-util.c | |
parent | f0b159f2e7b4ac8a75997834d240459f5436d36e (diff) |
util: add generic calls for prefixing a root directory to a path
So far a number of utilities implemented their own calls for this, unify
them in prefix_root() and prefix_roota(). The former uses heap memory,
the latter allocates from the stack via alloca().
Port over most users of a --root= logic.
Diffstat (limited to 'src/shared/path-util.c')
-rw-r--r-- | src/shared/path-util.c | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/src/shared/path-util.c b/src/shared/path-util.c index 635ce33b2..7090989fc 100644 --- a/src/shared/path-util.c +++ b/src/shared/path-util.c @@ -793,3 +793,37 @@ int fsck_exists(const char *fstype) { return 0; } + +char *prefix_root(const char *root, const char *path) { + char *n, *p; + size_t l; + + /* If root is passed, prefixes path with it. Otherwise returns + * it as is. */ + + assert(path); + + /* First, drop duplicate prefixing slashes from the path */ + while (path[0] == '/' && path[1] == '/') + path++; + + if (isempty(root) || path_equal(root, "/")) + return strdup(path); + + l = strlen(root) + 1 + strlen(path) + 1; + + n = new(char, l); + if (!n) + return NULL; + + p = stpcpy(n, root); + + while (p > n && p[-1] == '/') + p--; + + if (path[0] != '/') + *(p++) = '/'; + + strcpy(p, path); + return n; +} |