Best Practices for Getting Started with Git

Best Practices for Getting Started with Git

  • foreword

  • Introduction to Git

  • pragmatism

  • explore in depth

  • Summarize

  • References

foreword

Git It is programmers who cannot learn and work without development tools. Today I will share with you  Git a summary of common commands.

Introduction to Git

GitIt is a distributed version control system, which is not restricted by network connection, and with many other advantages, it has become the first choice for program developers to manage project versions, and non-developers can also use it Gitto make management tools.

I started to contact and use Git when I was a sophomore. From the zero contact at the beginning to the heavy dependence now, it is Gitreally .

GitThere are many APIs, but in fact, 90% of the needs in the usual projects only need to use a few basic functions, so this article 实用主义will 深入探索talk about how to use them in the project from two aspects Git. Generally speaking, after reading 实用主义this You can start using it in projects in one section.

Note: The operations in this article are all based on the Mac system

pragmatism

Preparation Phase

Go to the Git official website to download the installation package that suits you. GitAfter open the command line tool, enter the working folder ( for easy understanding, we demonstrate it on the system desktop ), and create a new demo folder.

Enter the Github website to register an account and log in, enter my blog, click Clone or download, click again Use HTTPS, copy the project address https://github.com/gafish/gafish.github.com.gitfor .

Go back to the command line tool, everything is ready, and then enter the focus of this article.

common operation

The so-called pragmatism means that you can play with the following knowledge Gitand easily meet more than 90% of the needs. The following is a list of practical Git commands, let’s take a look at them first

  • git clone

  • git config

  • git branch

  • git checkout

  • git status

  • git add

  • git commit

  • git push

  • git pull

  • git log

  • git tag

Next, I will explain how to use the entire process from Gitpulling .

git clone

pull code from git server

git clone https://github.com/gafish/gafish.github.com.git

After the code download is complete, there will be gafish.github.coma , cd gafish.github.comenter the directory through the command.

git config

Configure developer username and email

git config user.name gafishgit config user.email [email protected]

Every time the code is submitted, a submission record will be generated, which will contain the currently configured username and email address.

git branch

Create, rename, view, and delete project branches. When Gitdoing project development, it is generally carried out in the development branch. After the development is completed, the branch is merged into the trunk.

git branch daily/0.0.0

Create a daily development branch daily/0.0.0named as long as the branch name does not contain special characters.

git branch -m daily/0.0.0 daily/0.0.1

If you feel that the previous branch name is inappropriate, you can rename the newly created branch, and the renamed branch name isdaily/0.0.1

git branch

You can view the list of current project branches by using the branch command without parameters

git branch -d daily/0.0.1

If the branch has completed its mission, the branch can be deleted through -dthe parameter . Here, in order to continue to the next step, the deletion operation will not be performed for the time being

git checkout

switch branch

git checkout daily/0.0.1

Switch to daily/0.0.1the branch , and subsequent operations will be performed on this branch

git status

View file change status

Make some changes to README.mdthe file , save it.

git status

You can see the current state of the file through git statusthe command Changes not staged for commit:( the changed file has not been submitted to the temporary storage area )

On branch daily/0.0.1Changes not staged for commit:  (use "git add <file>..." to update what will be committed)  (use "git checkout -- <file>..." to discard changes in working directory)    modified:   README.mdno changes added to commit (use "git add" and/or "git commit -a")

git add

Add file changes to the staging area

git add README.md

By specifying the file name, README.mdyou can add the file to the temporary storage area. If you want to add all files, you can use git add .the command. At this time, you can use to git statussee the current status of the file Changes to be committed:( the file has been submitted to the temporary storage area )

On branch daily/0.0.1Changes to be committed:  (use "git reset HEAD <file>..." to unstage)    modified:   README.md

git commit

Commit file changes to the repository

git commit -m '这里写提交原因'

The commit description text can be entered directly on the command line via -mthe parameter

git push

Push local code changes to the server

git push origin daily/0.0.1

originRefers to the current git server address. This line of command means to push daily/0.0.1the branch to the server. When the command line returns the following characters, the push is successful.

Counting objects: 3, done.Delta compression using up to 8 threads.Compressing objects: 100% (2/2), done.Writing objects: 100% (3/3), 267 bytes | 0 bytes/s, done.Total 3 (delta 1), reused 0 (delta 0)remote: Resolving deltas: 100% (1/1), completed with 1 local objects.To https: * [new branch]      daily/0.0.1 -> daily/0.0.1

Now we go back to the project home page of the Github website, click Branch:masterthe drop-down button, and you will see daily/00.1the branch you just pushed

git pull

Pull the latest code from the server to the local

git pull origin daily/0.0.1

If other project members make changes to the project and push it to the server, we need to update the latest changes locally. Here we simulate this situation.

Enter the project home page of the Github website, enter daily/0.0.1the branch README.md, make some changes to the file online and save it, and then execute the above command in the command, it will pull the part that was just modified online to the local, open it with an editor, and you will find the README.mdfile Already synchronized with online content.

If the online code is changed, and your local code is also changed, the pulled code may conflict with your local changes. Generally, this kind of conflict and merge Gitwill be if the change is the same line, Then you need to manually merge the code, edit the file, save the latest changes, and git add .then git commit -m 'xxx'submit the merge through and .

git log

View version submission history

git log

Through the above command, we can view the version submission record of the entire project, which contains 提交人, 日期, 提交原因and other information, and the results are as follows:

commit c334730f8dba5096c54c8ac04fdc2b31ede7107aAuthor: gafish <[email protected]>Date:   Wed Jan 11 09:44:13 2017 +0800    Update README.mdcommit ba6e3d21fcb1c87a718d2a73cdd11261eb672b2aAuthor: gafish <[email protected]>Date:   Wed Jan 11 09:31:33 2017 +0800    test.....

There may be a lot of submission records, press Jthe key to scroll down, press Kthe key to scroll up, press Qthe key to exit and view

git day

Mark milestones for projects

git tag publish/0.0.1git push origin publish/0.0.1

When we complete a certain functional requirement and prepare to release it online, we should mark the complete project code and release the marked version to the line. Here we think publish/0.0.1of If the following content is returned, the release is successful

Total 0 (delta 0), reused 0 (delta 0)To https: * [new tag]         publish/0.0.1 -> publish/0.0.1

.gitignore

Set what content does not need to be pushed to the server, this is a configuration file

touch .gitignore

.gitignoreIt is not Gita command , but a file in the project, by setting .gitignorethe content to tell Gitwhich files should be ignored and do not need to be pushed to the server, you can create a .gitignorefile through the above command, and open the file in the editor, each line represents a to be ignored file or directory such as:

demo.htmlbuild/

The above means Gitthat demo.htmlfiles and build/directories will be ignored, and these contents will not be pushed to the server

summary

By mastering the above basic commands, you can start to use them in the project. If you pursue practicality, then the learning Gitabout Google.Git Advanced functions, then continue to look 深入探索down .

explore in depth

basic concept

Workspace ( Working Directory )

It is the directory you can see on the computer, for example, gafish.github.comthe folder is a workspace

Local repository ( Local Repository )

There is a hidden directory in the workspace .git, which is not considered a workspace, but a repository Gitof .

Temporary storage area ( stage )

There are many things stored in the local version library, the most important of which is stagethe temporary storage area called (or called index), and the first branch automatically created Gitfor us master, and a pointer masterto called HEAD.

Remote repository ( Remote Repository )

Generally refers to the corresponding warehouse on Gitthe server . githubThe warehouse where the example in this article is located is a remote version library

The relationship between the above concepts

工作区, 暂存区, 本地版本库, 远程版本库several commonly used Gitoperation processes are shown in the following figure:

Branch _ _

Branching is to store the entire process of modifying records separately, so that separate branches are not affected by other branches, so multiple different modifications can be performed simultaneously in the same database

master branch ( Master )

As mentioned earlier, masterit is Gitthe first branch automatically created for us, also called the main branch. After the development of other branches is completed, they must be merged intomaster

Tag ( Tag )

Labels are used to mark a specific point or commit history, usually used to mark the name or version number of the release version (such as: publish/0.0.1), although the label looks a bit like a branch, but the labeled submission is fixed and cannot be arbitrary Changes, see 1.0// in the 2.0picture above3.0

HEAD

HEADPoints to the latest commit of the current branch

The above concepts are almost understood, so you can continue to look down. The following will explain the high-level usage Gitof

operation file

git add

Add files to staging area

git add -i

This command will open the interactive subcommand system, and you will see the following subcommands

***Commands***1: status      2: update      3: revert      4: add untracked5: patch      6: diff      7: quit      8: help

The corresponding function can be selected by entering the serial number or initial letter, and the specific function is explained as follows:

  • status: Functionally git add -isimilar to , no bird use

  • update: see belowgit add -u

  • revert: Remove the files that have been added to the temporary storage area from the temporary storage area, the operation method is updatesimilar to

  • add untracked: You can add new files to the temporary storage area, the operation method is updatesimilar to

  • patch: see belowgit add -p

  • diff: Compare the difference between the staging area file and the local version library, the operation method is updatesimilar to

  • quit: exit git add -icommand system

  • help: View help information

git add -p

Direct access to the most useful patchmode

This is the most useful mode in interactive commands. Its operation mode is updatesimilar to GitAfter selection, it will display the differences between the current content of these files and the local version library, and then you can decide whether to add these modifications to the temporary storage area. In the command line Stage deletion [y,n,q,a,d,/,?]?Then input one y,n,q,a,d,/,?of them to select the operation mode, the specific function is explained as follows:

  • y: accept modification

  • n: ignore modification

  • q: Quit the current command

  • a: add modification

  • d: Discard modification

  • /: Modify content by regular expression matching

  • ?: View help information

git add -u

Directly enter updatethe mode

It will first list the files in the workspace 修改or , and the files in will not be displayed. Enter the corresponding list serial number after indicate that the item is selected, and press Enter to continue the selection. If it is selected, directly press Enter to return to the command Main interface删除新增Update>>

git add --ignore-removal .

Add the list of files for workspace 修改or 新增, 删除the files for will not be added

git commit

Submit the files in the temporary storage area to the local repository

git commit -m '第一行提交原因'  -m '第二行提交原因'

Enter the multi-line submission reason directly on the command line without opening the editor

git commit -am '提交原因'

Submit the files in the workspace 修改or 删除to the local repository, and 新增the files in the workspace will not be submitted

git commit --amend -m '提交原因'

Modify the submission reason of the latest submission record

git commit -C HEAD

Commit the current file changes to HEADor the history ID of the current branch

git mv

Move or rename files, directories

git mv a.md b.md -f

a.mdRename to b.md, and add changes to the temporary storage area at the same time. Adding -fparameters can force renaming, which mv a.md b.mdsaves git addthe operation

git rm

Remove files from workspace and staging area

git rm b.md

Remove files from the workspace and staging area b.md, and add changes to the staging area at the same time, rm b.mdwhich saves git addthe operation compared to using the command

git rm src/ -r

Allow removing directories from workspace and staging area

git status

git status -s

View the status of workspace and staging area files in a short way, an example is as follows:

 M demo.html?? test.html
git status --ignored

View workspace and staging area file status, including ignored files

operation branch

git branch

View, create, delete branches

git branch -a

View the list of branches on the local repository and the remote repository

git branch -r

View the list of branches on the remote repository, and add -dparameters to delete branches on the remote repository

git branch -D

Forcibly delete the branch before submitting it to the local repository

git branch -vv

View the list of branches of the local repository with information such as the last commit id, the reason for the latest commit, etc.

git merge

Merge other branches into current branch

git merge --squash

commitMerge committhe branch to be merged into a new one and put it into the current branch, which is suitable for cases where the commit record of the branch to be merged does not need to be preserved

git merge --no-ff

By default, Gitexecuting " 快进式合并" (fast-farward merge) will directly point Masterthe branch to Developthe branch. After using --no-ffthe parameter , a normal merge will be performed and Mastera new node will be generated on the branch to ensure a clearer version evolution.

git merge --no-edit

Merge without conflicts, don't want to manually edit the commit reason, Gitbut Merge branch 'test'commit directly with auto-generated text like

git checkout

switch branch

git checkout -b daily/0.0.1

Create daily/0.0.1a branch and switch to this newly created branch at the same time

git checkout HEAD demo.html

Check out from the history of the local version library HEAD(it can also be the commit ID, branch name, and tag name) demo.htmlOverwrite the file in the current workspace, if omitted HEAD, it will be checked out from the temporary storage area

git checkout --orphan new_branch

This command will create a brand new branch with no history at all, but all the latest files on the current source branch are still there, which is really a blessing for obsessive-compulsive disorder patients, but this new branch must be git commitdone new branch.

git checkout -p other_branch

This command is mainly used to compare the differences between two branches, and provides an interactive interface to select further operations. This command can not only compare the differences between two branches, but also compare the differences of a single file.

git stash

GitSave the current modified or deleted work progress in the stack of , when you are developing a certain function in a branch, you are notified to release the code that has been tested yesterday and is no problem to the line, but at this time you are already in this Other uncommitted codes are added to the branch, and these uncommitted codes can be stored in the stack at this time.

git stash

Save uncommitted files to the Git stack

git stash list

View the list saved in the stack

git stash show stash@{0}

Display one of the records in the stack

git stash drop stash@{0}

Remove one of the records in the stack

git stash pop

Check out the latest saved record from the Git stack and remove it from the stack

git stash apply stash@{0}

Check out one of the records from the Git stack without removing it from the stack

git stash branch new_banch

Check out the last record in the current stack and create a new branch

git stash clear

Clear all records in the stack

git stash create

Create a custom stack for the currently modified or deleted file and return an ID, which is not actually stored in the stack at this time

git stash store xxxxxx

createPut the ID returned in the method storebehind , at this time a record is actually created in the stack, but the currently modified or deleted file is not removed from the workspace

$ git stash create09eb9a97ad632d0825be1ece361936d1d0bdb5c7$ git stash store 09eb9a97ad632d0825be1ece361936d1d0bdb5c7$ git stash liststash@{0}: Created via "git stash store".

operation history

git log

show commit history

git log -p

Show history with commit diffs

git log demo.html

show demo.htmlfile history

git log --since="2 weeks ago"

Display the historical records from 2 weeks ago to the present, other times can be analogized

git log --before="2 weeks ago"

Display the historical records up to 2 weeks ago, other times can be analogized

git log -10

Display the last 10 historical records

git log f5f630a..HEAD

Display records from commit ID tof5f630a , can be empty or other commit IDsHEADHEAD

git log --pretty=oneline

Output a short history on one line

git log --pretty=format:"%h"

formatted output history

GitUse various placeholderto determine various display contents, I pick a few commonly used ones as follows:

  • %H: commit hash

  • %h: shortened commit hash

  • %T: tree hash

  • %t: shortened tree hash

  • %P: parent hashes

  • %p: shortened parent hashes

  • %an: author name

  • %aN: author name of mailmap

  • %ae: Author email

  • %ad: date (in the format specified by –date=)

  • %ar: date, relative format (1 day ago)

  • %cn: Committer name

  • %ce: Submitter email

  • %cd: commit date (in the format specified by –date=)

  • %cr: commit date, relative format (1 day ago)

  • %d: ref name

  • %s: commit message title

  • %b: commit information content

  • %n: Newline

git cherry-pick

Merge one or several commit records of the branch to the end of the current branch

git cherry-pick 170a305

Merge commit ID 170a305into current branch tip

git reset

Reset the current branch to the specified <commit>orHEAD

git reset --mixed <commit>

--mixedIt is the default parameter without parameters, it returns to a certain version, retains the file content, and rolls back the submission history

git reset --soft <commit>

The content in the temporary storage area and work area will not be changed in any way, just HEADpoint to<commit>

git reset --hard <commit>

<commit>Any changes in the workspace since are discarded and HEADpoint to<commit>

git rebase

Redefine the repository state of a branch

git rebase branch_name

Merge branches, which is mergevery similar to , but there are still essential differences, see the picture below:

The merge process may need to resolve conflicts first, and then executegit rebase --continue

git rebase -i HEAD~~

Open a text editor and you will HEADsee HEAD~~commits from to as follows

pick 9a54fd4 添加commit的说明pick 0d4a808 添加pull的说明# Rebase 326fc9f..0d4a808 onto d286baa## Commands:#  p, pick = use commit#  r, reword = use commit, but edit the commit message#  e, edit = use commit, but stop for amending#  s, squash = use commit, but meld into previous commit#  f, fixup = like "squash", but discard this commit's log message#  x, exec = run command (the rest of the line) using shell#

pickChange the on the first line Commandsto the command listed in , then save and exit, and the corresponding modification will take effect. If you move the order of the commit records, it will change the ordering in the history.

git revert

To undo an operation, the commitand historywill be retained, and this undo will be regarded as the latest submission

git revert HEAD

Undo the previous commit operation

git revert HEAD --no-edit

Undo the previous commit operation, and use the default Revert "xxx"as the commit reason

git revert -n HEAD

Add -nparameters , so that you will not submit every undo operation, but submit it together after all undo operations are completed

git diff

View the file differences between the workspace, temporary storage area, and local repository, and explain it with a picture

git diff --stat

Change statistics can be viewed through --statparameters

 test.md | 1 -1 file changed, 1 deletion(-)

git reflog

reflogYou can view all operation records of all branches (including commit and reset operations, and deleted commit records. The difference git logwith it cannot view deleted commit records.

Remote repository connection

If the files already exist in the local directory before the GitHub project is initialized, you can initialize the local repository locally, and then connect the local repository with the remote repository

git init

A .git folder will be generated inside the local directory

git remote

git remote -v

Without parameters, list existing remote branches, plus -vlist details, and list their remote urls after each name

git remote add origin https://github.com/gafish/gafish.github.com.git

Add a new remote warehouse, specify a name to refer to the following URL

git fetch

Fetch updates from the remote repository to the local repository

git fetch origin daily/0.0.1

By default, git fetchupdates from all branches are fetched. If you only want to fetch updates from a specific branch, you can specify the branch name.

Troubleshooting

git blame

View the history information of each line of code block in the file

git blame -L 1,10 demo.html

Intercept demo.htmlfile 1-10 lines of historical information

git bisect

Binary search history, troubleshooting BUG

git bisect start

start binary search

git bisect bad

Mark the current bipartite commit ID as problematic

git bisect good

Mark the point where the current binary commit ID is OK

git bisect reset

Return to the original branch after finding the problematic commit ID

more operations

git submodule

The external version library can be tracked through the Git submodule, which allows another version library to be stored in a certain version library, and can keep the two version libraries completely independent

git submodule add https://github.com/gafish/demo.git demo

demoAdd the repository as a submodule

git submodule update demo

update submoduledemo

git gc

Run Git's garbage collection function to clean up redundant historical snapshots

git archive

Package and extract a tagged version

git archive -v --format=zip v0.1 > v0.1.zip

--formatIndicates the packaging format, for example zip, -vindicates the corresponding tag name, followed by the tag name, for example v0.1.

Summarize

This article is just an exploration of some of the practical functions in Gitall . Git is very powerful, and there are still many functions waiting for us to discover.

Guess you like

Origin blog.csdn.net/feichangyanse/article/details/129676969