The Moment

阿宅的筆記

Auto deployment on vs code

一直進入不了開發狀態,一定是 editor 不順手造成的 (牽拖貌

記錄一下小改造的過程

Visual studio code 應該是目前免費的程式碼編輯器中算相當好用的,但美中不足的一個小地方是缺乏內建的自動佈署到遠端主機的機制,在只能在遠端進行測試的情況,頻繁的手動搬移檔案有點惱人,好在它跟目前多數的編輯器一樣,提供了一些客製功能的空間。以下是一個在 windows 10 的環境下的方式

  1. 安裝 vs code

  2. 因為在 win 10,習慣的同步工具(rsync, scp … )通通從缺,好在還有一個免費的 winscp 可以用,為了自己好,裝了它。 (有 windows 版的 rsync ,但… 如果你需要走 ssh ,那… 還是直接裝 winscp 省心點)

  3. vs code 中安裝 Run on save 這個人家寫好的 extension,並在 vs code 的環境設定檔( settings.json ) 內加上相關的設定。設定完它什麼事都還不會做,你必須指定它在存檔時要做的事 (cmd)。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    // run on save
    "emeraldwalk.runonsave": {
    "commands": [
    {
    "match": ".*",
    "cmd": "sync_file.bat ${workspaceRoot} ${file}"
    }
    ]
    }
  4. 要下的 cmd 如果是在 un*x 下,大概只要下個 scp/rsync 就能收工,只可惜,我們是在他媽的 windows 上,必要很苦命的寫個 batch 完成要做的事。run on save 預設的執行路徑是 vs code 的 home 的路徑,安裝時沒有手賤的話,通常會在 C:\Program Files (x86)\Microsoft VS Code,如果不想解決 run on save 解析執行路徑的問題,就把要它在存檔時執行的程式放這邊就好,,在上面的設定範例中,要執行的檔案叫 sync_file.bat 後頭接兩個參數: 目前 vs code 的工作目錄,跟目前正在編輯檔案的完整路徑,

  5. 要做的事很簡單,就是存檔後,上傳到遠端的某個相對的目錄下即可,範例程式碼如下 (不會寫 batch file ,從 stackoverflow 七拼八湊而來,有點蠢我知道 orz),其中的重點在於"C:\Program Files (x86)\WinSCP\winscp" <remote_id>:<password>@<remote_host> /command "!script!" "exit" 這個 winscp 提供的 command line script 方式,請它把對的檔案 PUT 到對的地方去就。好。了,收工。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    @echo off
    setlocal enabledelayedexpansion
    set "REMOTE_HOME=/<your>/<remote>/<director>"
    set allargs=%*
    IF NOT DEFINED allargs echo no args provided&GOTO :EOF
    call set curr_file=%%allargs:*%1=%%
    :: trim first white space character
    set curr_file=!curr_file:~1!
    set I=0
    set Idx=-1
    :l
    if "!curr_file:~%I%,1!"=="" goto ld
    if "!curr_file:~%I%,1!"=="\" set Idx=%I%
    set /a I+=1
    goto l
    :ld
    set curr_dir=!curr_file:~0, %Idx%!
    set I=0
    set Idx=-1
    set workspace=%1
    :l2
    if "!workspace:~%I%,1!"=="" goto ld2
    if "!workspace:~%I%,1!"=="\" set Idx=%I%
    set /a I+=1
    goto l2
    :ld2
    set /A idx+=1
    :: if current working directory == workspace , sync the file to remote
    echo.%curr_dir% | findstr /C:"%1" > nul && (
    set relative_filename=!curr_file:~%Idx%!
    :: replace "\" with "/"
    set relative_filename=!relative_filename:\=/!
    set "script=put !curr_file! !REMOTE_HOME!/!relative_filename!"
    "C:\Program Files (x86)\WinSCP\winscp" <remote_id>:<password>@<remote_host> /command "!script!" "exit"
    ) || (
    REM echo "not match, do nothing."
    )

p.s
winscp 同時也提供了 synchronize 指令(類似 rsync ),要的話也可以用 synchronize 同步兩地目錄即可,只是在目前我的情況下,我的開發環境不完全等同於測試環境,全部同步會有問題,而 synchronize 的-filemask (exclude) 用起來有點問題,短時間內不想處理,加上不一致這件事感覺不是什麼好事,也許之後留在 docker 一併解決吧。

p.s
如果你害怕太自動的事情,似乎也可以寫在 vs code 的 Task 裡,在要的時候才手動執行。