結論
- pushしようとしているブランチがリモートのどのブランチに対応するのか未知なのが原因。
-
git push <remote> <local-branch>:<remote-branch>
のように対応関係を指定することで解消できる。- もちろん、上記の問題を解消できるならほかの方法でも問題ない。
背景
- リモートリポジトリをcloneし、新たにbranchを作成後、再びリモートにpushしようとすると
error:refspec src <新しく作成したローカルブランチ名> does not match any
というエラーが発生してしまった。
原因
エラーメッセージを読むと、どうやら refspec なるものが原因のようだったので調べてみる。
Pro Git 10.5 Gitの内側 - Refspec に記載があったので、一部引用する。
Suppose you were following along with the last couple sections and had created a small local Git repository, and now wanted to add a remote to it
(筆者訳:こんな感じでリモートに追加したいとします:)$ git remote add origin https://github.com/schacon/simplegit-progit
Running the command above adds a section to your repository’s .git/config file, specifying the name of the remote (origin), the URL of the remote repository, and the refspec to be used for fetching:
(筆者訳:上のコマンド打つと、fetchに使うリモートの名前とURL、それに refspec が.git/configに追加されます:).git/config[remote "origin"] url = https://github.com/schacon/simplegit-progit fetch = +refs/heads/*:refs/remotes/origin/*
The format of the refspec is, first, an optional +, followed by :, where is the pattern for references on the remote side and is where those references will be tracked locally. The + tells Git to update the reference even if it isn’t a fast-forward.
(筆者訳: refspec は + のあとに <src>:<dst> が続く、という書式になっています。<src>はリモートのリファレンスを、<dst>はそれを追跡するローカルのリファレンスを示しています。+ はfast-forwardでなくてもリファレンスを更新することを意味しています。)
(リファレンスというワードが出てきたが、これはGit内のオブジェクトを示すハッシュの別名のようなものらしい。10.3 Gitの内側 - Gitの参照)
以上のことを踏まえると、refspec とは、リモートのオブジェクトとローカルを結びつける対応表のようなもの と思っておけばよさそうだ。
上の例ではfetchの場合のrefspecだったが、pushの場合のrefspecも同様に定義できる。pushのときはfetchのときと逆で、<src>はローカルオブジェクトの参照を、<dst>はリモートオブジェクトの所在を示す。
ここまでの内容を踏まえて最初のエラーメッセージを振り返ってみると、
error:refspec src <新しく作成したローカルブランチ名> does not match any
「ローカルオブジェクト<新しく作成したローカルブランチ名>に対応するrefspecがありません」という意味であることがわかる。
エラーメッセージを検索してこのページにたどり着いた方は、(筆者と同じように)新しく作成したブランチで最初のpushをしようとしてエラーが発生したのではないだろうか?Pro Gitで記載があったように、refspecはpushやfetchしたときにconfigに追記されるが、新規に作成したブランチではrefspecがないので、このようなエラーが発生するようだ。
対処法
push時のrefspecを作ればいい。
Pro Gitのように.git/config に記載してもよいが、push時に手動で指定することもできる。
$ git push <remote> <local-branch>:<remote-branch>
<local-branch>:<remote-branch> となっている部分がrefspec。
まとめ
- refspecとはリモートとローカルのオブジェクトを対応付けているしくみのこと。
- 表記のエラーは、refspecが指定されていないことによるエラー。
- .git/configに記載するか、push時にrefspecを指定することで解消できる。