ParseSourceInfo parses a given path in the context of given hostname and username and returns SourceInfo. The path may be bare (in which case it's interpreted as local path and canonicalized) or may be 'username@host:path' where path, username and host are not processed.
(path, hostname, username string)
| 31 | // SourceInfo. The path may be bare (in which case it's interpreted as local path and canonicalized) |
| 32 | // or may be 'username@host:path' where path, username and host are not processed. |
| 33 | func ParseSourceInfo(path, hostname, username string) (SourceInfo, error) { |
| 34 | if path == "(global)" { |
| 35 | return SourceInfo{}, nil |
| 36 | } |
| 37 | |
| 38 | p1 := strings.Index(path, "@") |
| 39 | p2 := strings.Index(path, ":") |
| 40 | |
| 41 | if p1 > 0 && p2 > 0 && p1 < p2 && p2 < len(path) { |
| 42 | return SourceInfo{ |
| 43 | UserName: path[0:p1], |
| 44 | Host: path[p1+1 : p2], |
| 45 | Path: path[p2+1:], |
| 46 | }, nil |
| 47 | } |
| 48 | |
| 49 | if p1 >= 0 && p2 < 0 { |
| 50 | if p1+1 < len(path) { |
| 51 | // support @host and user@host without path |
| 52 | return SourceInfo{ |
| 53 | UserName: path[0:p1], |
| 54 | Host: path[p1+1:], |
| 55 | }, nil |
| 56 | } |
| 57 | |
| 58 | return SourceInfo{}, errors.Errorf("invalid hostname in %q", path) |
| 59 | } |
| 60 | |
| 61 | absPath, err := filepath.Abs(path) |
| 62 | if err != nil { |
| 63 | return SourceInfo{}, errors.Errorf("invalid directory: '%s': %s", path, err) |
| 64 | } |
| 65 | |
| 66 | return SourceInfo{ |
| 67 | Host: hostname, |
| 68 | UserName: username, |
| 69 | Path: filepath.Clean(absPath), |
| 70 | }, nil |
| 71 | } |