LoginSignup
1
1

More than 3 years have passed since last update.

【Git】リモートリポジトリのURLを変える

Last updated at Posted at 2019-07-24

目的

  • 外部サーバにあるソースコードをbitbucket経由でローカルリポジトリにいれる
  • 既存のリモートリポジトリ(git cloneしてきたリポジトリ)を変更

前提

  • リモートリポジトリ作成済み
  • ローカルリポジトリとすでに同期済み
  • 外部サーバのソースコードフォルダは別のリモートリポジトリで管理されていた
  • 外部サーバのソースコード優先
  • ローカルで変更したものは無視していい

外部サーバで

git管理されているかどうか確認

$ git status
# On branch master
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)

リモートリポジトリのURLを確認

$ git remote -v
origin  git@bitbucket.org:hogehoge/hugahuga.git (fetch)
origin  git@bitbucket.org:hogehoge/hugahuga.git (push)

リモートリポジトリを変更

$ git remote set-url origin https://piyopiyo@bitbucket.org/piyopiyo/nyaanyaa.git
$ git remote -v
origin  https://piyopiyo@bitbucket.org/piyopiyo/nyaanyaa.git (fetch)
origin  https://piyopiyo@bitbucket.org/piyopiyo/nyaanyaa.git (push)

コミットしてpushします

$ git push origin master
Password for 'https://piyopiyo@bitbucket.org': 

httpsなのでpasswordが必要(外部サーバなので結果オーライ)

To https://piyopiyo@bitbucket.org/piyopiyo/nyaanyaa.git
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://piyopiyo@bitbucket.org/piyopiyo/nyaanyaa.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first merge the remote changes (e.g.,
hint: 'git pull') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

リモートリポジトリにはすでにローカルで行なっていた変更が記録されているため、マージか強制上書きしないといけないようです

なので強制上書き-fオプションをつけてpush

$ git push -f origin master

今度はうまくいきました

ローカル(自分のマシン)で

$ git pull
remote: Counting objects: 422, done.
remote: Compressing objects: 100% (213/213), done.
remote: Total 422 (delta 196), reused 422 (delta 196)
Receiving objects: 100% (422/422), 1.60 MiB | 1.13 MiB/s, done.
Resolving deltas: 100% (196/196), done.
From https://bitbucket.org/piyopiyo/nyaanyaa
 + a38b3bb...dabba87 master     -> origin/master  (forced update)
fatal: refusing to merge unrelated histories

エラーになってしまったので--allow-unrelated-historiesをつけてpullします

$ git pull --allow-unrelated-histories

通りました

これからは外部サーバでソースコードを変更してもリモートリポジトリとローカルで同期できます

向き間違えないようにしないと(汗

1
1
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
1
1