2012/09/14

git命令之update-ref

得空说说git update-ref。该命令用来更新ref引用的object。比如在一个bare repo里更新某个分支指向的提交。
命令用法如下:
git update-ref [-m <reason>] (-d <ref> [<oldvalue>] | [--no-deref] <ref> <newvalue> [<oldvalue>])

当带2个参数使用git update-ref时,会把赋给。同时它会解析遇到ref引用。(比如HEAD就是指向refs/heads/master的引用,更新HEAD实际上是更新refs/heads/master)。

当带3个参数使用时,在赋值之前会检查的当前值是否为。只有这个检查结果为真时,才会实际执行赋值操作。你可以利用这个特性,通过将设置为40个"0"或者一个空字符串来确保创建一个全新的ref。

如果使用--no-deref参数,update-ref会直接更新而不会解析相关的ref引用。

通常情况下,你应该使用更安全的:
git update-ref HEAD "$head"

而不是直接修改HEAD文件内容:
echo "$head" > "$GIT_DIR/HEAD"

2012/09/03

快速搭建SmartHTTP Git服务器

首先确保Git version >= 1.6.6并正确安装了Apache 2.x。

打开Apache配置文件,启用git-http-backend脚本:
SetEnv GIT_PROJECT_ROOT /path/to/repo
SetEnv GIT_HTTP_EXPORT_ALL
ScriptAlias /git/ /usr/lib/git-core/git-http-backend/

接着你就可以到/path/to/repo路径下创建你的Git仓库了。你可以使用git clone http://localhost/git/xxx.git来clone新创建的repo,但是并不能push。

要启用push需要添加认证:
<LocationMatch "^/git/.*/git-receive-pack$">
AuthType Basic
AuthName "Git Access"
Require group committers
...
</LocationMatch>

这样就可以通过匿名clone,认证push的方式使用Git服务器了。

更为细致的配置请参考git-http-backend文档

[GIT] 忽略已经被Git track的文件

我们知道在Git中忽略文件可以使用.gitignore文件或者配置.git/info/exclude。但是这两种方案有一个共同的限制,那就是只能忽略尚未被git track的文件。对那些已经执行过git add的文件就爱莫能助了。

下面介绍2个命令来实现对已经track文件的忽略。
git update-index --assume-unchanged -- path/to/file      # 启用忽略
git update-index --no-assume-unchanged -- path/to/file   # 停用忽略

示例如下:
77 gewang@LM-SHC-00355679@13:15:19:~/test/123
=> git diff
diff --git a/f b/f
index 541d3ff..847939a 100644
--- a/f
+++ b/f
@@ -5,3 +5,4 @@ abcaaa
aaa
dfadfaa
dlfaldf
+#####
78 gewang@LM-SHC-00355679@13:15:22:~/test/123
=> git update-index --assume-unchanged f
79 gewang@LM-SHC-00355679@13:15:36:~/test/123
=> git diff
80 gewang@LM-SHC-00355679@13:15:39:~/test/123
=> git status -s
81 gewang@LM-SHC-00355679@13:15:43:~/test/123
=> echo '-------' >> f
82 gewang@LM-SHC-00355679@13:16:04:~/test/123
=> git diff f
83 gewang@LM-SHC-00355679@13:16:06:~/test/123
=> git status -s
84 gewang@LM-SHC-00355679@13:16:14:~/test/123
=> git update-index --no-assume-unchanged f
85 gewang@LM-SHC-00355679@13:17:50:~/test/123
=> git diff
diff --git a/f b/f
index 541d3ff..6b239cf 100644
--- a/f
+++ b/f
@@ -5,3 +5,5 @@ abcaaa
aaa
dfadfaa
dlfaldf
+#####
+-------

2012/08/30

使用脚本分析git index文件内容

昨晚读了git index文件的格式说明,于是尝试的写了一个简单的ruby脚本用来解析index文件。部分代码如下:

#!/usr/bin/ruby

# Author: loveky <ylzcylx#gmail.com>
# Blog  : http://loveky2012.blogspot.com

# This script will parse the given index file and output all entries in it.
# run 'parse_index_file.rb -h' for help message

$: << File.dirname(__FILE__) 
require 'bindata'
require 'optparse'
require 'IndexEntry'

STANDARD_SIGNATURE  = 'DIRC'
entry_count         = 1

begin
    options = {}
    opts = OptionParser.new do |opts|
        opts.banner = "Parse the index file and show you what is there"
        opts.on('-f FILE ','--file FILE', 'Path to the index file') do |value|
            options[:file] = value
        end
    
        opts.on_tail("-h", "--help", "Show this message") do
            puts opts
            exit
        end
    
    end.parse!

    raise ArgumentError, "No index file given!" if options[:file] == nil

    File.open(options[:file], "rb") do |fd|
        SIGNATURE = fd.read(4)
        raise RuntimeError, "Not an index file!" if SIGNATURE != STANDARD_SIGNATURE
    
        VERSION         = fd.read(4).unpack("N")[0]
        ENTRIES_NUMBER  = fd.read(4).unpack("N")[0]
    
        puts "Index version : #{VERSION}"
        puts "Entries number: #{ENTRIES_NUMBER}"
    
        ENTRIES_NUMBER.times do
            entry = IndexEntry.read(fd)
            puts "Found file: " + entry.path 
            puts "  SHA1    : " + entry.sha1.unpack("H40").join
            puts "  stage   : #{entry.flags << 2 >> 14}"
            puts "  ctime   : " + Time.at(entry.ctime_s + entry.ctime_ns * 10**-9).strftime('%Y-%m-%d %H:%M:%S.%9N')
            puts "  mtime   : " + Time.at(entry.mtime_s + entry.mtime_ns * 10**-9).strftime('%Y-%m-%d %H:%M:%S.%9N')
            puts "  size    : #{entry.file_size}"
        
            if (fd.pos - 12) % 8 != 0
                fd.seek(8 - ((fd.pos - 12) % 8), IO::SEEK_CUR)
            end
        end
    end
rescue => ex
    puts "#{ex.class}: #{ex.message}"
end

使用起来很简单,只需要ruby parse_index_file.rb --file [index文件路径]就好了。

要查看最新的,完整脚本内容请猛击我的github

最后附上index文件的格式说明,E文的,不过写的很简洁,就先不翻译了
GIT index format
================

= The git index file has the following format

All binary numbers are in network byte order. Version 2 is described
here unless stated otherwise.

- A 12-byte header consisting of

4-byte signature:
The signature is { 'D', 'I', 'R', 'C' } (stands for "dircache")

4-byte version number:
The current supported versions are 2 and 3.

32-bit number of index entries.

- A number of sorted index entries (see below).

- Extensions

Extensions are identified by signature. Optional extensions can
be ignored if GIT does not understand them.

GIT currently supports cached tree and resolve undo extensions.

4-byte extension signature. If the first byte is 'A'..'Z' the
extension is optional and can be ignored.

32-bit size of the extension

Extension data

- 160-bit SHA-1 over the content of the index file before this
checksum.

== Index entry

Index entries are sorted in ascending order on the name field,
interpreted as a string of unsigned bytes (i.e. memcmp() order, no
localization, no special casing of directory separator '/'). Entries
with the same name are sorted by their stage field.

32-bit ctime seconds, the last time a file's metadata changed
this is stat(2) data

32-bit ctime nanosecond fractions
this is stat(2) data

32-bit mtime seconds, the last time a file's data changed
this is stat(2) data

32-bit mtime nanosecond fractions
this is stat(2) data

32-bit dev
this is stat(2) data

32-bit ino
this is stat(2) data

32-bit mode, split into (high to low bits)

4-bit object type
valid values ina binary are 1000 (regular file), 1010 (symbolic link)
and 1110 (gitlink)

3-bit unused

9-bit unix permission. Only 0755 and 0644 are valid for regular files.
Symbolic links and gitlinks have value 0 in this field.

32-bit uid
this is stat(2) data

32-bit gid
this is stat(2) data

32-bit file size
This is the on-disk size from stat(2), truncated to 32-bit.

160-bit SHA-1 for the represented object

A 16-bit 'flags' field split into (high to low bits)

1-bit assume-valid flag

1-bit extended flag (must be zero in version 2)

2-bit stage (during merge)

12-bit name length if the length is less than 0xFFF; otherwise 0xFFF
is stored in this field.

(Version 3) A 16-bit field, only applicable if the "extended flag"
above is 1, split into (high to low bits).

1-bit reserved for future

1-bit skip-worktree flag (used by sparse checkout)

1-bit intent-to-add flag (used by "git add -N")

13-bit unused, must be zero

Entry path name (variable length) relative to top level directory
(without leading slash). '/' is used as path separator. The special
path components ".", ".." and ".git" (without quotes) are disallowed.
Trailing slash is also disallowed.

The exact encoding is undefined, but the '.' and '/' characters
are encoded in 7-bit ASCII and the encoding cannot contain a NUL
byte (iow, this is a UNIX pathname).

(Version 4) In version 4, the entry path name is prefix-compressed
relative to the path name for the previous entry (the very first
entry is encoded as if the path name for the previous entry is an
empty string). At the beginning of an entry, an integer N in the
variable width encoding (the same encoding as the offset is encoded
for OFS_DELTA pack entries; see pack-format.txt) is stored, followed
by a NUL-terminated string S. Removing N bytes from the end of the
path name for the previous entry, and replacing it with the string S
yields the path name for this entry.

1-8 nul bytes as necessary to pad the entry to a multiple of eight bytes
while keeping the name NUL-terminated.

(Version 4) In version 4, the padding after the pathname does not
exist.

== Extensions

=== Cached tree

Cached tree extension contains pre-computed hashes for trees that can
be derived from the index. It helps speed up tree object generation
from index for a new commit.

When a path is updated in index, the path must be invalidated and
removed from tree cache.

The signature for this extension is { 'T', 'R', 'E', 'E' }.

A series of entries fill the entire extension; each of which
consists of:

- NUL-terminated path component (relative to its parent directory);

- ASCII decimal number of entries in the index that is covered by the
tree this entry represents (entry_count);

- A space (ASCII 32);

- ASCII decimal number that represents the number of subtrees this
tree has;

- A newline (ASCII 10); and

- 160-bit object name for the object that would result from writing
this span of index as a tree.

An entry can be in an invalidated state and is represented by having
-1 in the entry_count field. In this case, there is no object name
and the next entry starts immediately after the newline.

The entries are written out in the top-down, depth-first order. The
first entry represents the root level of the repository, followed by the
first subtree---let's call this A---of the root level (with its name
relative to the root level), followed by the first subtree of A (with
its name relative to A), ...

=== Resolve undo

A conflict is represented in the index as a set of higher stage entries.
When a conflict is resolved (e.g. with "git add path"), these higher
stage entries will be removed and a stage-0 entry with proper resoluton
is added.

When these higher stage entries are removed, they are saved in the
resolve undo extension, so that conflicts can be recreated (e.g. with
"git checkout -m"), in case users want to redo a conflict resolution
from scratch.

The signature for this extension is { 'R', 'E', 'U', 'C' }.

A series of entries fill the entire extension; each of which
consists of:

- NUL-terminated pathname the entry describes (relative to the root of
the repository, i.e. full pathname);

- Three NUL-terminated ASCII octal numbers, entry mode of entries in
stage 1 to 3 (a missing stage is represented by "0" in this field);
and

- At most three 160-bit object names of the entry in stages from 1 to 3
(nothing is written for a missing stage).


2012/08/29

git diff之diff两个分支

常见的diff用法是比较工作区,index,HEAD或者是diff两个提交。除了这些用法之外diff还可以比较2个分支,用法如下:
git diff topic master     (1)
git diff topic..master    (2)
git diff topic...master   (3)

用法1,直接跟两个使用空格分隔的分支名会直接将两个分支上最新的提交做diff,相当于diff了两个commit。
用法2,用两个点号分隔的分支名,作用同用法1(装酷利器)
用法3,用三个点号分隔的分支名会输出自topic与master分别开发以来,master分支上的change。

需要注意的是这里的..和...不能与git rev-list中的..和...混淆。

2012/08/27

[GIT] 根据文件内容快速定位该文件在哪次历史提交中引入

今天一位同事找到我说到,如何能快速的定位一个文件的某个版本是在哪一次历史提交里引入的。

解决方案如下:
首先根据文件内容确定该文件对应的blob对象的object ID
git hash-object path/to/file
或者直接使用几个shell命令生成:
(echo -e -n "blob $(wc -c path/to/file | awk '{print $1}')\0" ; cat path/to/file) | shasum

得到对应blob对象的object ID以后,使用whatchanged查看该文件的变更历史,默认情况下whatchanged不会输出merge中修改的文件,为了避免遗漏,此处还是用-m来告诉whatchanged还要输出merge的结果:
git whatchanged -m -- path/to/file

此时可以搜索刚刚得到的blob的object ID。需要注意的是由于whatchanged默认显示blob变化信息时只使用blob ID的前7位,因此搜索时也要注意不能使用完整的object ID,也应该使用object ID的前几位。

ruby写了个脚本实现查找:

注:你看到此文章时,该脚本可能已经不是最新版本,需要最新的code请移步loveky's GITHUB

#!/usr/bin/ruby

# Author: loveky <ylzcylx@gmail.com>
# Blog  : http://loveky2012.blogspot.com

#Usage: find_it_in_history.rb --file <file> --repo <path/to/repo> --path_in_repo <file/path/in/repo>

require 'digest/sha1'
require 'optparse'

found   = false
commit  = nil
options = {}
OptionParser.new do |opts|
    opts.banner = "Find the commit who first introduced the specified version of a file"
    opts.on('--file FILE', 'Which file to check') do |value|
        options[:file] = value
    end
    opts.on('--repo REPO', 'which repo to check') do |value|
        options[:repo] = value
    end
    opts.on('--path_in_repo PATH', 'the path of the file in repo') do |value|
        options[:path_in_repo] = value
    end
end.parse!

file_content = File.open(options[:file]) {|f| f.read}
file_sha1    = Digest::SHA1.hexdigest("blob #{file_content.length}\0" + file_content)

puts("#{options[:file]} => #{file_sha1}")

Dir.chdir(options[:repo])

IO.popen("git whatchanged --oneline -m -- #{options[:path_in_repo]}") do |git_whatchanged|
    git_whatchanged.each_line do |line|
        if line[0,1] == ':'
            new_blob = (/\.\.\. ([0-9a-fA-F]{7})\.\.\./.match(line))[1]
            
            if new_blob == file_sha1[0,7]
                puts "Found blob(#{file_sha1[0,7]}) in commit " + commit
                found = true
            elsif found == true
                exit 0
            end
        else
            commit = line[0,7]   
        end
    end
end

2012/08/15

git命令之git stash

在日常的开发过程中,我们会常常会遇到这种情况:当前再分支1上进行开发,开发到一半,突然有需要去修改其他branch上的文件,这时可能会让你感到很尴尬,因为当前开发到一半,工作尚未完成,要么匆忙的进行一个“半成品”提交,要么就要reset工作区,否则当你checkout到分支2时,git会提示你:
error: Your local changes to the following files would be overwritten by checkout:
 b
Please, commit your changes or stash them before you can switch branches.
Aborting
组织你切换分支。

这时就可以用到git stash命令。git stash可以保存当前的工作进度,并reset工作区,这样在不丢失当前工作进度的前提下,你可以切换分支继续工作。
该命令的基本使用方法如下:

保存当前工作进度:
git stath save [message]

查看已经保存的工作进度列表:
git stash list

恢复指定的工作进度:
git stash apply [--index] [stash]

恢复指定的工作进度,并将其从进度列表中删除:
git stash pop [--index] [stash]

删除一个存储的进度:
git stash drop [stash]

删除所有存储的进度:
git stash clear