Skip to content

Commit

Permalink
Add get_user_home
Browse files Browse the repository at this point in the history
Add an utility function for locating the current user's home directory
using either $HOME or their passwd entry.
  • Loading branch information
liff committed Sep 12, 2024
1 parent a6e6c02 commit 39fd2b1
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 9 deletions.
34 changes: 25 additions & 9 deletions src/common-utils/common-utils.c
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,29 @@ void nvfree(void *s)
/* misc */
/****************************************************************************/

/*
* get_user_home() - locate current user's home directory using either
* the enrivonment variable or their passwd entry.
*
* Returns NULL if the home directory cannot be located, otherwise
* returns a statically allocated string that is either the value
* of the environment variable or the passwd entry.
*/
const char *get_user_home()
{
char *home = getenv("HOME");
struct passwd *pw;

if (home) return home;

/* $HOME isn't set; get the home directory from /etc/passwd */

pw = getpwuid(getuid());
if (pw) return pw->pw_dir;

return NULL;
}

/*
* tilde_expansion() - do tilde expansion on the given path name;
* based loosely on code snippets found in the comp.unix.programmer
Expand All @@ -310,7 +333,7 @@ void nvfree(void *s)

char *tilde_expansion(const char *str)
{
char *prefix = NULL;
const char *prefix = NULL;
const char *replace;
char *user, *ret;
struct passwd *pw;
Expand All @@ -324,14 +347,7 @@ char *tilde_expansion(const char *str)

/* expand to the current user's home directory */

prefix = getenv("HOME");
if (!prefix) {

/* $HOME isn't set; get the home directory from /etc/passwd */

pw = getpwuid(getuid());
if (pw) prefix = pw->pw_dir;
}
prefix = get_user_home();

replace = str + 1;

Expand Down
1 change: 1 addition & 0 deletions src/common-utils/common-utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ char *nvasprintf(const char *fmt, ...) NV_ATTRIBUTE_PRINTF(1, 2);
void nv_append_sprintf(char **buf, const char *fmt, ...) NV_ATTRIBUTE_PRINTF(2, 3);
void nvfree(void *s);

const char *get_user_home();
char *tilde_expansion(const char *str);
char *nv_prepend_to_string_list(char *list, const char *item, const char *delim);

Expand Down

0 comments on commit 39fd2b1

Please sign in to comment.