mitchellh/go-homedir

When `$USER` and `$HOME` are unset and shell is `dash`, `go-homedir` fails to expand the `~`

kkoroviev opened this issue · 6 comments

Thanks for reporting this. :) I think we should at least detect when USER/HOME are not set and error, but even better we should add more fallbacks to detect the directory.

You can use /proc/self/status on Linux:

$ cat /proc/self/status | grep "^[UG]id:"
Uid:    1000    1000    1000    1000
Gid:    1000    1000    1000    1000

From man proc:

* Uid, Gid: Real, effective, saved set, and filesystem UIDs (GIDs).

I don't quite understand the difference.

And sudo cat /proc/self/status | grep "^[UG]id:" gives you:

Uid:    0   0   0   0
Gid:    0   0   0   0

You (or me) may dig deeper or just use the first one.

Then, when we have a UID, we may use it to look up the homedir in /etc/passwd.

How about attempting to shell out to getent before we try the shell option, which can accept a UID?

$ getent passwd 1000
tianon:x:1000:1000::/home/tianon:/bin/bash

(Also worth noting is os.Getuid, which exists on all platforms and thus will cross-compile just fine.)

(Or os.Geteuid depending -- maybe worth trying both if the first doesn't get a result?)

Also, to make the shell fallback slightly more resilient, it could instead use something like cd && pwd which won't rely quite so directly on optional environment variables. 😄