# Remote container 使用 git

在 Visual Studio Code (下面使用 VSCode 稱呼) 內使用 devcontainer 開發時,怎麼使用 git?

我的開發方式都是從 git hub 上 clone 程式後建立 devcontainer 環境進行開發

當建立完 devcontainer 環境進入 container 後,點選 VSCode 左邊的 Source Control 項目時,會出現

The folder currently open doesn't have a git repository

且右下角出現提示

Git not found. Install it or configure it using the 'git.path' setting

出現這種情況表示 container 內沒有安裝 git

# 安裝 git

在 container 內安裝 git 的方法,可以在 Dockerfile 內加上

Dockerfile
RUN apk update && apk upgrade && apk add --no-cache \
    git

如果是使用 apt-get (不過我沒有用 apt-get 測試過)

Dockerfile
RUN apt-get update && apt-get install -y --no-install-recommends \
    git \
    && rm -rf /var/lib/apt/lists/*

# CAfile: none

如果在 container 內 git pull 時出現 CAfile: none 的訊息

Git: fatal: server certificate verification failed. CAfile: none CRLfile: none

修改 Dockerfile,加上 ca-certificates 變成

Dockerfile
RUN apt-get update && apt-get install -y --no-install-recommends \
    git \
    ca-certificates \
    && update-ca-certificates \
    && rm -rf /var/lib/apt/lists/*

# So many pending changes

改完 Dockerfile 後執行 Rebuild container 再次進入 container 查看 Source Control

可能會出現很多 change 的檔案

So Many Pending Changes

但實際上你並沒有修改這些檔案,查看 diff 也看沒看到有變更的地方

# Git AutoCrLf

如果你跟我一樣是使用 Windows 安裝 docker 的話,很有可能會遇到這個狀況

這是因為 Windows 跟 Linux 的跳行符號不一樣的關係

DOS/Windows 跳行使用 CR/LF (\r\n)
UNIX/Linux 跳行使用 LF (\n)

可以執行

git config
git config --global core.autocrlf true

然後在 Source Control refresh 就可以看到 change 的檔案變少了

如果不想每次建立 devcontainer 環境都要執行一次的話,可以修改 Windows 的 git config

使用 TortoiseGit 可以參考
https://tortoisegit.org/docs/tortoisegit/tgit-dug-settings.html#tgit-dug-settings-config

不建議在 Dockerfile 內使用 RUN 或者在 devcontainer.json 內設定 autocrlf

因為原本 user.name , user.email ... 相關資訊會不見,導致無法執行 push/pull 等動作

如果要在 Dockerfile 內設定 autocrlf 可以用

Dockerfile
RUN git config --global core.autocrlf true

可以自己測試看看加跟不加時,進入 container 後 config 的差異

list git config
git config --global -l