將本地Project放到Github

2018/03/18 posted in  Git comments

TL;DR

$ git init
$ git add .
$ git commit -m "First commit"
$ git remote add origin https://github.com/NAME/REPO.git
$ git push -u origin master

詳細步驟

1. Initialize git

$ git init # 新增.git資料夾
$ git status # 查看檔案狀態
$ git add . # 加入所有檔案到下個commit
$ git commit -m "First commit" # commit已加入的檔案

2. 加入git push目的地

先在Github新增一個repo,並複製remote url (clone或download那裡)。

$ git remote add origin https://github.com/NAME/REPO.git

Remote是一個git directory的遠端位置,在這個情況,我們的remote就是放在github上的repository網址。

現在可以執行git remote -v看一看。

origin  https://github.com/NAME/REPO.git (fetch)
origin  https://github.com/NAME/REPO.git (push)

(這些都是git的configuration,儲存在.git/config裡面)

3. push到目的地

所有檔案都加入並commit好了,remote url也設置好了,這時可以push到github了。

$ git push

fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin master

此時會出現fatal error,因為我們的push沒有指明push到甚麼remote和branch。

這是個防護機制,一個git專案可以有多個remote和branch,所以我們第一次push要指明現在這個 local branch 要push到哪個 remote branch

我們現在是由 localmaster push到 githubmaster

$ git push origin master # push到origin(剛剛新增的remote)的master branch

--set-upstream-u就是代表以後 local master 都是直接push到 origin master ,下次就直接打git push可以了。

4. git pull

git pull也是同樣情況,如果push的時候local branch不夠remote branch up-to-date的話,會有以下error:

! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/carsonwah/gohugo-demo.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 integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

意思是要先git fetch remote branch的東西下來,然後merge到local branch讓它up-to-date,最後才能push

git pull就是fetchmerge的合體,但直接git pull又會有以下error:

 * [new branch]      master     -> origin/master
There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details.

    git pull <remote> <branch>

If you wish to set tracking information for this branch you can do so with:

    git branch --set-upstream-to=origin/<branch> master

原來git pull也要和git push一樣,設置對應的remote branch。剛才還沒完成git push --set-upstream,所以還未有upstream目的地。pull不能用-u(不知道為甚麼),要透過git branch 直接設置:

$ git branch --set-upstream-to=origin/master master  # 或 git branch -u origin/master master
# 然後pull
$ git pull --allow-unrelated-histories  # 需要加上--allow-unrelated-histories,因為local和remote完全沒有共同history,git default是不允許的

這時填好merge的commit message就可以直接git push了。

(老實說直接在某處git clone,然後手動將project搬家好像更方便)