ターミナルからVSCodeのSSHリモートディレクトリを開く

はじめに

今回紹介するのは VSCode の SSH リモートディレクトリをターミナルから直接開くときに使う便利なコマンドです。

VSCode には Remote SSH という拡張機能があり、 SSH 接続先のディレクトリをワークスペースとして起動することができます。

しかし、手元のターミナルから code コマンドを使って code user@host などと実行しても開くことはできません。

そこで今回は sshcode というコマンドを新たに作って、 ターミナルからサクッと SSH ディレクトリを開く方法を紹介します。

つくったもの

今回作成した sshcode コマンドは下記リポジトリに保存されています。

上記ファイルの内容を .zshrc などに記述することで使用可能です。

要件

  • zsh を使用していること
  • code コマンドへのパスが通っていること
  • VSCode に Remote - SSH 拡張機能がインストールされていること

使用例

下記の例のように sshcode コマンドで SSH リモートディレクトリを VSCode で開くことができます。

# SSH 接続先のホームディレクトリを VSCode で開く
sshcode username@example.com
# ホームディレクトリからの相対パス ~/project を開く
sshcode username@example.com:project
# 絶対パス /var/log を開く
sshcode username@example.com/var/log
# SSH ポートを指定する
sshcode -p 2222 username@example.com
# ~/.ssh/config に設定したエイリアスで開く
sshcode my_server

ディレクトリ指定の文法は scp コマンドの文法と同じです。

実装内容

ここからは実装したコマンドの内容の解説です。

今回作成したのは shell function です。

.zshrc などに書いて置くことでそのシェルで有効になります。

sshcode コマンドを作成

メインの sshcode コマンドの定義は下記のようになっています。

# main command
function sshcode() {
  # variables to use
  local port destination host dir
  # parse option
  local -A opthash
  zparseopts -D -E -A opthash -- p:
  port=${opthash[-p]}
  # check argument
  if [ $# -eq 0 ]; then
    echo "usage: $0 [-p port] host[:path]"
    return -1
  fi
  # find host and dir
  destination="$1"
  host="${destination%%:*}" # before ':'
  dir="${destination##*:}" # after ':'
  # fix dir if ':' does not exist
  [ "$host" = "$dir" ] && dir=""
  # find abs path if $dir does not start with '/'
  [ "${dir:0:1}" != "/" ] && dir="$(ssh ${port:+-p $port} $host pwd)/$dir"
  # open with code
  code --folder-uri "vscode-remote://ssh-remote+$host${port:+:$port}$dir"
}

引数をパースして、最終的には code コマンドでリモートディレクトリを開いています。

zsh の補完関数を設定

zsh では scp コマンドなどを使用したとき ssh の接続先のディレクトリ名なども補完してくれてとても便利です。

今回はその scp コマンドの補完を参考にして sshcode コマンドの補完機能を実装しました。

# sshcode zsh completion
function _sshcode_completion () {
  # ref: /usr/share/zsh/functions/Completion/Unix/_ssh
  local expl suf ret=1
  typeset -A opt_args
  if compset -P 1 '[^./][^/]#:'; then
    _remote_files -- ssh ${(kv)~opt_args[(I)-[FP1246]]/-P/-p} && ret=0
  elif compset -P 1 '*@'; then
    suf=( -S '' )
    compset -S ':*' || suf=( -r: -S: )
    _wanted hosts expl 'remote host name' _ssh_hosts $suf && ret=0
  else
    _alternative 'hosts:remote host name:_ssh_hosts -r: -S:'
  fi
  return ret
}

補完関数を実装したら、下記コマンドで補完を適用します。

# setup zsh completion
compdef _sshcode_completion sshcode

おわりに

VSCode でリモートディレクトリを開いた場合、 統合ターミナルも SSH 接続先のターミナルになっていて、とても開発しやすいです。

ローカルの VSCode を開いてからいちいち SSH 接続先とディレクトリを指定するのは結構面倒だったので、 sshcode によって一発で開けるのはとても便利でした。

是非試してみてください!

参考記事