Visual Studioでローカルリポジトリを開くと「1つ以上のエラーが発生しました。」のメッセージが表示され、リポジトリを開けない - Visual Studio

Visual Studioでローカルリポジトリを開くと「1つ以上のエラーが発生しました。」のメッセージが表示され、リポジトリを開けない現象と対処法について紹介します。

現象の確認

Visual Studioでローカルリポジトリを開くと[Git変更]パネルに次のエラーメッセージが表示されます。
エラーメッセージ
1つ以上のエラーが発生しました。


エラーの調査

コマンドプロンプトやPowerShellでリポジトリのディレクトリに移動し、次のコマンドを実行します。
cd (リポジトリのディレクトリ)
git pull

コマンドを実行すると次のエラーが表示されます。
エラーメッセージ
fatal: unsafe repository ('(リポジトリのディレクトリ)' is owned by someone else)
To add an exception for this directory, call:

        git config --global --add safe.directory '(リポジトリのディレクトリ)'

対処法1: クローンしなおす

リポジトリの複製を再度作成します。

対処法2: safe directoryを追加する

エラーメッセージにある git config --global --add safe.directory コマンドを実行します。
コマンドプロンプト、PowerShellで次のコマンドを実行します。

git config --global --add safe.directory '(リポジトリのディレクトリ)'


実行後にローカルリポジトリを開くとエラーメッセージは表示されなくなります。

コマンド実行による設定の変化

git config --global --add safe.directoryコマンドを実行すると C:\Users\(ユーザー名)\.gitconfig ファイルに [safe]セクションが追加されます。
下記の例は git config --global --add safe.directory 'C:/storage/Develop Repository/iPentecDemo' を実行した場合の結果です。

実行前の.gitconfigファイルは以下です。
.gitconfig "C:\Users\(ユーザー名)\.gitconfig"
[user]
	name = ExamplePerson(ユーザー名)
	email = example-person@ipentec.com(メールアドレス)
[credential "https://(リポジトリのホスト名)"]
	provider = generic

実行後の.gitconfigファイルは以下です。
.gitconfig "C:\Users\(ユーザー名)\.gitconfig" コマンド実行後
[user]
	name = ExamplePerson(ユーザー名)
	email = example-person@ipentec.com(メールアドレス)
[credential "https://(リポジトリのホスト名)"]
	provider = generic
[safe]
	directory = C:/storage/Develop Repository/iPentecDemo (リポジトリのローカルパス)
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
掲載日: 2022-04-21
iPentec all rights reserverd.