`
scm002
  • 浏览: 309744 次
社区版块
存档分类
最新评论

GitPython 库

 
阅读更多

GitPython is a python library used to interact with git repositories. It provides abstractions of git objects for easy access of repository data, and additionally allows you to access the git repository more directly using either a pure python implementation, or the faster, but more resource intensive git command implementation.

安装:

reference http://packages.python.org/GitPython/0.3.1/intro.html

1、 GitDB

2、 async

3、smmap

由于使用easy_install GitPython失败,于是使用 sudo python setup.py install 来安装,本人机器上的版本如下,:

  1. async-0.6.1.tar.gz   
  2. smmap-0.8.2.tar.gz  
  3. gitdb-0.5.4.tar.gz   
  4. GitPython-0.3.1-beta2.tar.gz 

命令简介:

  1. ####head
  2. >>> from git import * 
  3. >>> repo = Repo.init("/home/test/.git") 
  4. >>> repo.heads 
  5. [<git.Head "refs/heads/rt24-build">
  6. >>> repo.heads[0]
    <git.Head "refs/heads/rt24-build">
  7. >>> repo.head
    <git.HEAD "HEAD">
  8. >>> repo.head.reference
    <git.Head "refs/heads/rt24-build">

 

  1. ####commit
  2. >>> repo.head.commit
    <git.Commit "4500d8151fcdd93087cb599544120ead6f943aa7">
  3. >>> repo.commit('rt24-build')
    <git.Commit "4500d8151fcdd93087cb599544120ead6f943aa7">
  4. >>> repo.commit('HEAD~')
    <git.Commit "04b49ab467ad96bd9c9c7844495b80d1959e716b">
  5. >>> repo.head.commit.parents
    (<git.Commit "04b49ab467ad96bd9c9c7844495b80d1959e716b">,)
  6. >>> repo.head.commit.parents[0]
    <git.Commit "04b49ab467ad96bd9c9c7844495b80d1959e716b">
    >>> repo.head.commit.parents[0].parents[0]
    <git.Commit "aa1b8964c4ec1f994e1b54b1a223db005cb90b16">
  7. >>> repo.commit('HEAD~').parents
    (<git.Commit "aa1b8964c4ec1f994e1b54b1a223db005cb90b16">,)
  1. #from http://packages.python.org/GitPython/0.3.1/tutorial.html
  2. headcommit = repo.head.commit 
  3.  
  4. headcommit.hexsha 
  5. '207c0c4418115df0d30820ab1a9acd2ea4bf4431' 
  6.  
  7. headcommit.parents 
  8. (<git.Commit "a91c45eee0b41bf3cdaad3418ca3850664c4a4b4">,) 
  9.  
  10. headcommit.tree 
  11. <git.Tree "563413aedbeda425d8d9dcbb744247d0c3e8a0ac"> 
  12.  
  13. headcommit.author 
  14. <git.Actor "Michael Trier <mtrier@gmail.com>"> 
  15.  
  16. headcommit.authored_date        # seconds since epoch 
  17. 1256291446 
  18.  
  19. headcommit.committer 
  20. <git.Actor "Michael Trier <mtrier@gmail.com>"> 
  21.  
  22. headcommit.committed_date 
  23. 1256291446 
  24.  
  25. headcommit.message 
  26. 'cleaned up a lot of test information. Fixed escaping so it works with 
  27. subprocess.' 
  1. ####tree 
  2. >>> tree = repo.head.commit.tree 
  3. >>> tree 
  4. <git.Tree "94cdc2be1511d765f9bc2fb05c85bda9e729d902"> 
  5. >>> tree.trees 
  6. [<git.Tree "780675fdf24f573f4d11682d804a68422215f345">
  7. <git.Tree "5844c84155668a2a34c5ce735433e66926904064">
  8. <git.Tree "b0e3ec09efc8ec093d4d37c3fa833464d29851a2">
  9. <git.Tree "0fc969b876f0bdbfb8d24dfaa28b5dd604487813">
  10. <git.Tree "4a801fd4d8874efc7422b65b46ec5446d08269a7">
  11. <git.Tree "22907f24d136e4a8a3f0d6dea74658b222fa4885">
  12. >>> tree[0].name 
  13. '.gitignore' 
  14. >>> tree[0].path 
  15. '.gitignore' 
  16. >>> tree[0].abspath 
  17. '/home/test/.gitignore' 

关于tree:是repo的目录结构,git show 94cdc2be1511d765f9bc2fb05c85bda9e729d902 能显示该目录下的所以目录和文件,每一个目录需要一个tree,从tree.trees的输出有6项知道,该目录下有6个目录。可以对这6个目录分别递归显示其下的目录和文件。

 直接使用git命令:

 GitPython源代码cmd.py文件中 Git::_call_process 函数提供直接使用git命令接口。

  1. >>> print repo.git.show('4500d8151fcd') 
  2. commit 4500d8151fcdd93087cb599544120ead6f943aa7 ......
  3. >>> repo.git.log('-1') 
  4. 'commit 6cba56e7816dd8a7dc591bd097e8e51c5d631679\nAuthor:......' 

 

python setup.py install 来安装python包,如何卸载呢?

只能手动删除安装的文件,可以使用如下命令

python setup.py install --record files.txt 记录安装后文件的路径

cat files.txt | xargs rm -rf  删除这些文件

另外sudo apt-get install python-git也能安装,但是接口会有很大的不一样,例如:

前者安装的

  1. >>> dir(git.Repo) 
  2. ['DAEMON_EXPORT_FILE', '__class__', '__delattr__', '__doc__', '__eq__', '__format__',  
  3. '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__',  
  4. '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__',  
  5. '__subclasshook__', '_bare', '_clone', '_get_alternates', '_get_config_path',  
  6. '_set_alternates', '_working_tree_dir', 'active_branch', 'alternates', 'archive', 'bare', 
  7.  'blame', 'branches', 'clone', 'clone_from', 'commit', 'config_level', 'config_reader',  
  8. 'config_writer', 'create_head', 'create_remote', 'create_submodule', 'create_tag', 'daemon_export', 
  9.  'delete_head', 'delete_remote', 'delete_tag', 'description', 'git', 'git_dir', 'head', 'heads',  
  10. 'index', 'init', 'is_dirty', 'iter_commits', 'iter_submodules', 'iter_trees', 'odb',  
  11. 're_author_committer_start', 're_hexsha_only', 're_hexsha_shortened', 're_tab_full_line',  
  12. 're_whitespace', 'references', 'refs', 'remote', 'remotes', 'rev_parse', 'submodule',  
  13. 'submodule_update', 'submodules', 'tag', 'tags', 'tree', 'untracked_files', 'working_dir',  
  14. 'working_tree_dir'] 

apt 安装的是 python-git 0.1.6-1

  1. >>> dir(git.Repo) 
  2. ['DAEMON_EXPORT_FILE', '__class__', '__delattr__', '__dict__', '__doc__', '__format__',  
  3. '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__',  
  4. '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',  
  5. '__weakref__', '_get_alternates', '_set_alternates', 'active_branch', 'alternates', 'archive_tar',  
  6. 'archive_tar_gz', 'blob', 'branches', 'commit', 'commit_count', 'commit_deltas_from', 'commit_diff',  
  7. 'commits', 'commits_between', 'commits_since', 'create', 'daemon_export', 'description', 'diff', 
  8.  'fork_bare', 'heads', 'init_bare', 'is_dirty', 'log', 'tags', 'tree'] 

 

本文出自 “每日C” 博客,请务必保留此出处http://dailyc.blog.51cto.com/6187762/1064033

 

GitPython git python 的开发库

https://my.oschina.net/hopeMan/blog/141221

工程地址: https://pypi.python.org/pypi/GitPython/ 需要安装先安装: gitdb https://pypi.python.org/pypi/gitdbGitPython使用模块对象访问git配置库。 仓库操作 初始仓库对象 from git import * repo = Repo(repo_path) assert repo.bare == False

创建裸库
    repo = Repo.init(repo_path,bare=True)
    assert repo.bare == True

仓库数据高层接口可以新增/删除 heads/tags/remotes和访问仓库的配置信息
    repo.config_reader() #获得仓库中只读的配置信息
    repo.config_writer() #更新仓库中的配置信息

获取活动分支、未被管理的文件和判断是否有变更
    repo.is_dirty()  #返回布尔值
    repo.untracked_files    #返回未被管理的文件列表

克隆和初始化一个新的仓库
    cloned_repo = repo.clone(to/this/path)
    new_repo = repo.init(path/for/new/repo)

数据库对象 repo对象的性能优于数据库对象,repo对象一般用于获取大数据和新增对象。

GitDB 在操作大文件时,GitDB可以使用更少的内存,但处理速度慢2到5倍 repo = Repo('path/to/repo',odbt=GitDB)

GitCmdObjectDB 使用git-cat-file实例读取配置库信息,访问速度比较快,但内存占用比GitDB严重。 repo = Repo('path/to/repo',odbt=GitCmdObjectDB)

引用操作的实例 head操作 heads = repo.heads master = heads.master #lists can be accessed by name for convenience master.commit #the commit pointed to by head called master master.rename('new_name') #rename heads tag(tag通常是不变的)是一个commit或tag对象的引用 tags = repo.tags tagref = tags[0] #tag可以有一个tag对象,存储额外的信息 tagref.commit #tag总是指向一个commit repo.delete_tag(tagref) #删除一个tag repo.create_tag('my_tag') #创建一个tag 符号引用可以替代具体commit指向一个引用 head = repo.head #the head points to the active branch/ref master = head.reference #but they always point to commits master.commit #from here you use it as any other reference

访问reflog
    log = master.log()
    log[0]  #first reflog entry
    log[-1] #last reflog entry
修改引用
    创建、删除各种引用和修改指向
    repo.delete_head('master') #delete an existing head
    master = repo.create_head('master')  #create a new one
    master.commit = 'HEAD~10'   #set branch to another commit without changing index or working tree
    创建、删除tags
    new_tag = repo.create_tag('my_tag','my message')
    repo.delete_tag(new_tag)
    分支直接切换
    new_branch = repo.craete_head('new_branch')
    repo.head.reference = new_branch

git库的各种对象
    git的所有对象都存在git数据库中。对象包含的信息有类型、未压缩的大小、每个对象都有一个20个字节的唯一的SHA1值。
    git有四类对象Blobs、Trees、Commits and Tags
    git所有的对象都可以访问,但通常是通过引用或git仓库的方法来访问,不是直接从数据库中读取。
        hc = repo.head.commit
        hct = hc.tree
        hc != hct
        hc != repo.tags[0]
        hc == repo.head.reference.commit
    git对象基本字段有
        hct.type
        hct.size
        hct.hexsha
        hct.binsha
    索引对象可以用作git的索引,这些对象是Trees/Blobs和Submodules ,这些对象含有文件路径的信息。
        hct.path    #root tree has no path
        hct.trees[0].path #the first subdirectory has one though
        hct.mode    #trees have the mode of a linux directory
        hct.blobs[0].mode #blobs have a specific mode though compareable to a standard linux fs
    使用stream访问blob数据或者其他对象数据   
        hct.blobs[0].data_stream.read() #stream object to read data from 
        hct.blobs[0].stream_data(open("blob_data","w")) #write data to given stream

Commit对象
    commit对象包含固定commit的信息。通过引用或者指定版本可以获取到commit对象
        repo.commit('master')
        repo.commit('v0.1')
        repo.commit('HEAD~10')
    获取100指定引用上100commit
        repo.iter_commits('master',max_count=100)
    分页显示
        显示21-30的记录
        repo.iter_commits('master',max_count=10,skip=20)

        headcommit = repo.head.commit
        headcommit.hexsha
        headcommit.parents
        headcommit.author
        headcommit.tree
        headcommit.committer
        headcommit.committed_date
        headcommit.message
    时间格式化
        import time
        time.asctime(time.gmtime(headcommit.committed_date))  #'Web May 7 05:56:02 2013'
        tiem.strftime("%a,%d %b %Y %H:%M",time.gmtime(headcommit.committed_date)) #'Web,7 May 2013 05:56'
    访问commit祖先
        headcommit.parents[0].parents[0].parents[0].parents[0]
        等价于master^^^^ 或者master~4

Tree对象
    tree对象指向当前目录的内容。获取master分支最新提交的根tree对象
        tree = repo.heads.master.commit.tree
    通过tree对象可以获取的内容有
        tree.trees  #trees are subdirectories
        tree.blobs  #blobs are files
    可以通过名称获取tree对象
        tree[0] = tree['dir']  #access by index and by sub-path
        blob = tree[0][0]
        blob.name
        blob.path
        blob.abspath
    有简便的方法通过子目录名称就可以获取对象
        tree/"lib"
        tree/"dir/file" == blob
    如果指定tree对象的名称也可以直接从git数据库中读取
        repo.tree() #返回<git.Tree "master">
        repo.tree("c1c7214dde86...")
        repo.tree('0.1.6')
    遍历tree对象
        tree.traverse()
        for entry in tree.traverse():do_something_with(entry)
    如果tree对象返回的是子模块对象,默认为是当前head的commit

索引对象
    git的索引对象包含了commit变更和合并信息。通过索引对象可以获得更复杂的信息
        index = repo.index
    读取、添加、删除实例,Commit变更:
        for stage,blob in index.iter_blobs():do_something(...)  #Access blob object
        for (path,stage),entry in index.entries.iteritems: pass #Access the entries directly
        index.add(['my_new_file'])   #add a new file to the index
        index.remove(['dir/existing_file'])
        new_commit = index.commit("my commit message")
     通过tree或者merge创建新索引
        tmp_index = Index.from_tree(repo,'HEAD~1') #load a tree into a temporary index
        merge_index = Index.from_tree(repo,'base','HEAD','some_branch') #merge two trees three-way
        merge_index.write('merged_index')
远程仓库
    远程名称作为外部从仓库的别名,可以通过它push和fetch数据
        test_remote = repo.create_remote('test','git@server:repo.git')
        repo.delete_remote(test_remote) # create and delete remotes
        origin = repo.remotes.origin #get default remote by name
        origin.refs  #local remote reference
        o = origin.rename('new_origin') #rename remotes
        o.fetch()   #fetch,pull and push from and to the remote 
        o.pull()
        o.push()
    远程库的配置信息
        o.url
    修改配置信息
        o.config_writer.set('pushurl','other_url')
子模块

对象比较
    可以比较index和Trees或者Index和working tree 或者trees和trees以及trees和working copy 
        hcommit = repo.head.commit
        idiff = hcommit.diff()  #diff tree against index
        tdiff = hcommit.diff('HEAD~1')  #diff tree against previous tree
        wdiff = hcommit.diff(None)  #diff tree against working tree

        index = repo.index
        index.diff() #diff index agginst itself yielding empty idff
        index.diff(None) #diff index against working copy
        index.diff('HEAD') #diff index against current HEAD tree
    比较返回的比较索引本质上是一个Diff对象列表,通过额外的过滤方法你可以找到你想要的内容
    for diff_added in wdiff.iter_change_type('A'): do_something_with(diff_added)

分支切换
    想切换分支,你需要设置HEAD指向新分支,重置index和工作区
        repo.head.reference = repo.heads.other_branch
        repo.head.reset(index=True,working_tree=True)
    上面的方法会覆盖掉工作区中所有修改未提交的边更新,下面的方法则不会
        repo.heads.master.checkout() #checkout the branch using git-checkout 
        repo.heads.other_branch.checkout()
直接使用git库
    通过git实例使用git命令
        git = repo.git
        git.checkout('head',b='my_new_branch')  #default command
        git.for_each_ref()  #'-' becomes '_' when calling it
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics