diff options
| author | Joseph Hunkeler <jhunkeler@gmail.com> | 2024-11-12 00:59:08 -0500 | 
|---|---|---|
| committer | Joseph Hunkeler <jhunkeler@gmail.com> | 2024-11-12 00:59:08 -0500 | 
| commit | 5a8efc84f7a3c2264926b393aafd5585deaa7195 (patch) | |
| tree | 7055bde796e3b965368d638c6791ce9e37748449 | |
| parent | 6fe076163eaacac892efd83f9ffe967d2d0e8f52 (diff) | |
| download | stasis-5a8efc84f7a3c2264926b393aafd5585deaa7195.tar.gz | |
Add path_manip function
| -rw-r--r-- | include/utils.h | 13 | ||||
| -rw-r--r-- | src/lib/core/utils.c | 43 | 
2 files changed, 56 insertions, 0 deletions
| diff --git a/include/utils.h b/include/utils.h index 4ade817..2756347 100644 --- a/include/utils.h +++ b/include/utils.h @@ -30,6 +30,10 @@  #define STASIS_XML_PRETTY_PRINT_PROG "xmllint"  #define STASIS_XML_PRETTY_PRINT_ARGS "--format" +#define PM_APPEND 1 << 0 +#define PM_PREPEND 1 << 1 +#define PM_ONCE  1 << 2 +  /**   * Change directory. Push path on directory stack.   * @@ -392,4 +396,13 @@ int mkdirs(const char *_path, mode_t mode);   */  char *find_version_spec(char *package_name); +/** +* Manipulate the PATH environment variable +* @param path to insert (does not need to exist) +* @param mode PM_APPEND `$path:$PATH` +* @param mode PM_PREPEND `$PATH:path` +* @param mode PM_ONCE do not manipulate if `path` is present in PATH variable +*/ +int path_manip(char *path, int mode); +  #endif //STASIS_UTILS_H diff --git a/src/lib/core/utils.c b/src/lib/core/utils.c index 5f0807c..793b445 100644 --- a/src/lib/core/utils.c +++ b/src/lib/core/utils.c @@ -808,3 +808,46 @@ int mkdirs(const char *_path, mode_t mode) {  char *find_version_spec(char *str) {      return strpbrk(str, "@~=<>!");  } + +int path_manip(char *path, int mode) { +    if (isempty(path)) { +        SYSERROR("%s", "New PATH element cannot be zero-length or NULL"); +        return -1; +    } + +    const char *system_path_old = getenv("PATH"); +    if (!system_path_old) { +        SYSERROR("%s", "Unable to read PATH"); +        return -1; +    } + +    char *system_path_new = NULL; + +    if (mode & PM_APPEND) { +        asprintf(&system_path_new, "%s:%s", system_path_old, path); +    } else if (mode & PM_PREPEND) { +        asprintf(&system_path_new, "%s:%s", path, system_path_old); +    } + +    if (!system_path_new) { +        SYSERROR("%s", "Unable to allocate memory to update PATH"); +        return -1; +    } + +    if (mode & PM_ONCE) { +        if (!strstr(system_path_old, path)) { +            guard_free(system_path_new); +            return 0; +        } +    } + +    if (setenv("PATH", system_path_new, 1) < 0) { +        SYSERROR("Unable to prepend to PATH: %s", path); +        guard_free(system_path_new); +        return -1; +    } + +    guard_free(system_path_new); +    return 0; +} + | 
