On Wed, 28 Dec 2016 10:25:54 -0300
Aldrin Leal <ald...@leal.eng.br> wrote:

> > As explain ~/ in golang
> > <https://github.com/golang/go/issues/18443> , I am trying to
> > request the user to cat a file with a gocat program.
> >
> > The point is that if the user tell to the terminal the full address,
> > /home/user/file, the program works, but if the user use ~/file the
> > program brokes.
> >
> > How can I use Golang to use ~/ in terminal request?
> I believe this sums it up pretty well:
> 
> http://stackoverflow.com/questions/17609732/expand-tilde-to-home-directory

The accepted answer presents an obvious solution -- since dealing
with tilde expantion is what Unix shells do, make a shell do it -- but
that solution contains a subtle problem: we accept the input from the
user and then submit it as a script to `/bin/sh -c`.  So the user can
happily enter "rm -rf something" or something like this.
Validating such input for sanity is an excersise in futility IMO.

BTW Aurélien seems to have asked this same question over there on SO,
and I provided them with an an answer [1].
The answer is

----------------8<----------------
The ~ and a more general ~username "things" belong to the so-called
"tilde expansion" of the standard Unix shell (as standardized by
POSIX). They have no bearing on environment.

So in order to interpret those shortcuts, you'd need to parse them
manually and substitute them in the input string¹ or see if
path/filepath.Abs() is able to help you (I'm afraid it's not).

----

¹ Parsing ~ and ~username is hard because you need to

1. For just ~, heck the environment variable "HOME", and if it
   exists use its value.

2. Otherwise ask whatever subsystem of your OS is responsible for
   this for the location of the user's home directory. For ~ this will
   be the current user; for ~username this will be the user with the
   username login name.

   Note that on *nix it does not have to be equal to the user's
   login name. Instead it's located in a special database.

   And if you think this database is the /etc/passwd you're wrong
   because the login subsystem can be configured to use other sources
   for this information—with LDAP servers being one common example.

Note that the Unix shell itself does not fail if the ~username cannot
be expanded; consider:

  $ whoami
  kostix
  $ echo ~kostix
  /home/kostix
  $ echo ~doesnotexist
  ~doesnotexist
----------------8<----------------

Aurélien, can you elaborate on what's wrong with it?

1. http://stackoverflow.com/a/41361431/720999

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to