Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

parse ssh host info from per host string using 'net/url' #143

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
37 changes: 22 additions & 15 deletions ssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"io"
"io/ioutil"
"net"
"net/url"
"os"
"os/user"
"path/filepath"
Expand Down Expand Up @@ -43,16 +44,29 @@ func (e ErrConnect) Error() string {

// parseHost parses and normalizes <user>@<host:port> from a given string.
func (c *SSHClient) parseHost(host string) error {
c.host = host
// https://golang.org/pkg/net/url/#URL
// [scheme:][//[userinfo@]host][/]path[?query][#fragment]
if !strings.Contains(host, "://") && !strings.HasPrefix(host, "//") {
host = "ssh://" + host
}

// Remove extra "ssh://" schema
if len(c.host) > 6 && c.host[:6] == "ssh://" {
c.host = c.host[6:]
hostURL, err := url.Parse(host)
if err != nil {
return err
}

if at := strings.Index(c.host, "@"); at != -1 {
c.user = c.host[:at]
c.host = c.host[at+1:]
// Add default port, if not set
hostname := hostURL.Hostname()
port := hostURL.Port()
if port == "" {
port = "22"
}
c.host = net.JoinHostPort(hostname, port)

if hostURL.User != nil {
if u := hostURL.User.Username(); u != "" {
c.user = u
}
}

// Add default user, if not set
Expand All @@ -64,14 +78,7 @@ func (c *SSHClient) parseHost(host string) error {
c.user = u.Username
}

if strings.Index(c.host, "/") != -1 {
return ErrConnect{c.user, c.host, "unexpected slash in the host URL"}
}

// Add default port, if not set
if strings.Index(c.host, ":") == -1 {
c.host += ":22"
}
c.env = c.env + `export SUP_HOST="` + c.host + `";`

return nil
}
Expand Down
2 changes: 1 addition & 1 deletion sup.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func (sup *Stackup) Run(network *Network, envVars EnvList, commands ...*Command)

// SSH client.
remote := &SSHClient{
env: env + `export SUP_HOST="` + host + `";`,
env: env,
user: network.User,
color: Colors[i%len(Colors)],
}
Expand Down