Created
October 28, 2014 17:04
-
-
Save pasela/0450d041abd6723facb1 to your computer and use it in GitHub Desktop.
[go] ExpandTilde
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"os/user" | |
"strings" | |
) | |
func ExpandTilde(path string) (string, error) { | |
if path[0] != '~' { | |
return path, nil | |
} | |
si := strings.IndexAny(path, "/\\") | |
var head, tail string | |
if si == -1 { | |
head, tail = path, "" | |
} else { | |
head, tail = path[:si], path[si:] | |
} | |
var usr *user.User | |
var err error | |
if head == "~" { | |
usr, err = user.Current() | |
} else { | |
usr, err = user.Lookup(head[1:]) | |
} | |
if err != nil { | |
return path, err | |
} | |
return usr.HomeDir + tail, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment