(command: string, name?: string)
| 124 | * Attempts to convert an SSH command to an SSH config entry. |
| 125 | */ |
| 126 | export function sshCommandToConfig(command: string, name?: string): { [key: string]: string } { |
| 127 | const parts: string[] = parse(command) as string[]; |
| 128 | |
| 129 | // ignore 'ssh' if the user entered that as their first word |
| 130 | if (parts[0] === 'ssh') { |
| 131 | parts.shift(); |
| 132 | } |
| 133 | |
| 134 | // Once again following what OpenSSH does internally. libc getopt, and our library |
| 135 | // here, stop when they reach the end of the flags. When that happens we pull |
| 136 | // out the host if we can, and restart it to try to read any remaining flags. |
| 137 | const entries: { [key: string]: string } = {}; |
| 138 | for (let offset: number = 0; offset < parts.length; offset++) { |
| 139 | offset += parseFlags(parts.slice(offset), entries); |
| 140 | |
| 141 | // Only parse the first positional/non-flag argument. The SSH command |
| 142 | // line allows trailing arguments as commands to execute, but we |
| 143 | // don't care about those here. |
| 144 | if (offset < parts.length && !entries.Host) { |
| 145 | const { hostname, port, username } = parseConnectionString(parts[offset]); |
| 146 | entries.Host = name || hostname; |
| 147 | entries.HostName = hostname; |
| 148 | |
| 149 | // In OpenSSH, provided flags take precedence over options in the connection string: |
| 150 | if (!entries.Port && port) { |
| 151 | entries.Port = port; |
| 152 | } |
| 153 | if (!entries.User && username) { |
| 154 | entries.User = username; |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | if (!entries.Host) { |
| 160 | throw new CommandParseError('Missing host in SSH connection string'); |
| 161 | } |
| 162 | |
| 163 | // ssh-config requires that the "Host" be the first key in the object |
| 164 | // in order to nest things correctly. Rewrite the object so that |
| 165 | // this is the case. |
| 166 | const { Host, HostName, ...options } = entries; |
| 167 | return { Host, HostName, ...options }; |
| 168 | } |
| 169 | |
| 170 | /** |
| 171 | * Parses flags from the given array of arguments, returning the index of the |
no test coverage detected