Git 使用经验总结

常用命令

按使用频度排序

  • git pull
  • git log
  • git diff
  • git commit
  • git commit –amend
  • git review
  • git clone
  • git push
  • git reset –hard/soft
  • git checkout
  • git fetch –all
  • git merge
  • git branch -b develop origin/develop
  • git clean -df

git 命令非常多,但常用的只有以上几个

常用配置

用户名和密码

$ git config --global user.name liuzuocheng

$ git config --global user.email zuocheng.liu@gmail.com

权限验证

在git pull/push/clone 时输入密码会比较麻烦。在所有的解决方法中,除了使用密钥之外,还可以使用.git-credentials配置文件。这种方法的坏处则是密码用明文存储,安全风险大。

touch ${HOME}/.git-credentials
输入内容
https://username:password@gitlab.zuocheng.net
执行下面命令使其生效
git config --global credential.helper store

默认编辑器

$ git config --global core.editor vim

配置比较工具

git config --global merge.tool vimdiff

git config --global diff.tool vimdiff

git config --global difftool.prompt false

git config --global alias.d difftool

或者直接更改配置文件 ~/.gitconfig,添加手工添加配置

常用经验

  • 将远程主干合并到本地分支

在代码上线前,这一步非常重要

git fetch && git rebase origin/master

git fetch --all && git merge origin master

分支间文件差异大,频繁切换显示aborting, git status后发现大量为trace的文件

通过下面的命令清理它们
git clean -df

解决版本冲突

暂存本地修改

$ git stash

拉取版本库中最新版本

$ git pull

将本地修改与版本库中最新版本合并

$ git stash pop stash@{0}

解决冲突,使用下面的工具会非常方便

$ git d

  • 将源码导出tar包

git对应的功能是归档

mkdir ../working

git archive master | tar -x -C ../working

Git 高级功能

submodule

git submodule add 仓库地址 路径

git submodule update --init

git submodule update

fork后如何同步源的新更新 ?

  • 首先要先确定一下是否建立了主repo的远程源

git remote -v

  • 如果里面只能看到你自己的两个源(fetch 和 push),那就需要添加主repo的源:

git remote add upstream URL

  • 查看主repo的远程源

git remote -v

  • 拉取主repo源的代码

git fetch upstream

  • 合并

git merge upstream/master

  • 提交

git push

git 项目打包导出

示例, 项目中有为1.0的tag

git archive 1.0 | bzip2 > v1.0.tar.bz2

示例,打包master分支

git archive --format tar.gz --output "../project.tar.gz" master

与 Gerrit 配合使用

提交代码审核 git push origin HEAD:refs/for/mybranch

submodule

一键更新所有submodule,包含所有层级

git submodule update --init --recursive

submodule 更新后,版本不一致,引发意外出core

重新初始化并拉取所有的submodule

git submodule deinit -f --all
git submodule update --init --recursive

高级用法

git rebase

这是介绍rebase用法特别好的博客,http://blog.chinaunix.net/uid-27714502-id-3436706.html

git清除所有commit历史记录

# 新建初始分支
git checkout --orphan new_branch 
# 添加文件
git add -A
# 提交修改
git commit -m "Initial commit" -s
# 覆盖原master分支后push
git branch -D master
git branch -m master
git push origin master -f

常见异常处理

fatal: Not possible to fast-forward, aborting.

处理方法是 rebase
git pull origin master --rebase
git rebase --continue

error: remote unpack failed: error Missing tree

执行push时添加–no-thin选项,参考stackoverflow
git push --no-thin

Server does not allow request for unadvertised object

常为更改了submodule的引用地址造成,可以使用git submodule sync命令解决,参考stackoverflow

Git 使用经验总结》上有3个想法

回复 律鹤扬 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注