30
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

既存ディレクトリにgit cloneして上書きしようとしたら叱られたので、別の手順で上書き(忘備録)

Posted at

まだgitで管理されていないローカルの「$HOME/foo」ディレクトリに、ソースコードとデータが保存されているとします。
別の誰かによってリモートリポジトリが新規作成され、最新のソースコードがアップされました。
データはバージョン管理の対象にしないため、リモートリポジトリに含まれないとします。
ローカルの「$HOME/foo」配下に古いソースコードとデータを置いたまま、git clone foo.git してリモートの最新ソースコードで上書きしようとしたら...

fatal: destination path 'foo' already exists and is not an empty directory.

上記のように叱られました。
そこで、git cloneに代わる手順を試しましたので、以下に記します。

# 既存ディレクトリに移動(古いソースコードとデータあり)
cd $HOME/foo

# 空のローカルリポジトリを作成
git init

# リモートリポジトリを追加
git remote add origin https://XXXXX/foo.git

# 最新のソースコードを、リモートブランチから追跡ブランチに持ってくる
git fetch origin master

# 1回目のブランチ確認
git branch -a

# 追跡ブランチのソースコードで、ローカルブランチのソースコードを強制上書き
git reset --hard origin/master

# 2回目のブランチ確認
git branch -a

# HEAD設定
git remote set-head origin master

# 3回目のブランチ確認
git branch -a

以上の手順で、バージョン管理の対象にしないデータを残したまま、ローカルのソースコードをリモートの最新で上書きできました。

1回目のブランチ確認では、以下のように表示されました。

  remotes/origin/master

2回目のブランチ確認では、以下のように表示されました。

* master
  remotes/origin/master

3回目のブランチ確認では、以下のように表示されました。

* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/master

参考ページ

git pull で、ローカルを強制上書きする方法
Gitのリモートブランチと追跡ブランチは違うよ
gitのHEAD(ローカルスタート)

30
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?