創建repository
可以在Github上無限制使用public repository進行源代碼管理,創建一個repository很簡單,不多說了。
獲取代碼到本地
首先要安裝Git,然后使用命令把代碼從Github上拷貝到本地:
git clone https://github.com/<username>/<repository_name>
如果是第一次使用,自己的repository還是空的,同樣可以使用remote進行鏈接
git remote add origin https://github.com/username/repository_name.git
提交更新到服務器
如果我們要新增或者更新一個文件,比如test.html。我們要先確保這個test.html已經存在,然后用git add 進行添加標記,表示這個文件已經改動或者這個文件是新增文件。
git add test.html
git commit -m "代碼提交信息"
如果沒有commit,那么添加的文件只是放在一個暫存區。 commit后改動才算真正寫到了本地,但是改動還沒有上傳的服務器上去。如果添加多個文件,可以用
git add *
因此,即使是commit了,新增的文件也還沒有上傳到Github上去。需要用push把改動上傳到Github上去。 會提示你輸入用戶和密碼
git push origin master
這個"master",是指分支的名字。默認情況下就只有"master"這個主分支。 "orgin"是在我們從Github上clone代碼到本地的時候,默認的源的名字。可以理解為"orgin"就是我們當前正在工作的源代碼。 上面的意思就是,把我們當前的代碼("orgin")的改動推送到服務器上的"master"分支。
刪除一個文件和添加一個文件的步驟類似。首先使用git rm刪除一個文件,並且commit。注意,直接在目錄下把文件刪掉是沒有用的,必須用git rm刪除文件。
git rm test.html
git commit -m "代碼提交信息"
然后在把改動push到服務端"git push origin master"。
從服務器獲取更新
git status 是一個很有用的命令,用來查看本地repository的狀態,它會顯示文件的新增/修改/刪除的狀態。
如果服務端有更新,git status也會有相應的提示。
D:\Dev\Github\bid>git status
On branch master
Your branch is behind 'origin/master' by 1 commit, and can be fast-forwarded.
(use "git pull" to update your local branch)nothing to commit, working directory clean
上面的顯示的意思就是,有一個更新還沒有反應到我本地來,可能是別人往server上checkin了一點東西。 使用git pull命令拿這些更新到本地來。
D:\Dev\Github\bid>git pull
Updating abf79f6..db7b6e3
Fast-forward
routes.js | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
如果服務端和本地文件都做了改動,使用git pull時就會提示沖突:
D:\Dev\Github\bid>git pull
remote: Counting objects: 5, done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 3 (delta 2), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
From https://github.com/*****/***
db7b6e3..211ff7f master -> origin/master
Updating db7b6e3..211ff7f
error: Your local changes to the following files would be overwritten by merge:
routes.js
Please, commit your changes or stash them before you can merge.
Aborting
這時候推薦手動檢查一下文件的版本,到底需要哪個。有一個git mergetool可以幫助merge code。
使用git checkout可以丟棄掉本地的改動,然后使用git pull去拿server上的最新更新。
比如,我想丟棄一個文件的所有改動:
git checkout routes.js
然后再使用git pull,就可以拿到server上的版本的代碼了。