How can I rewrite python __version__ with git?

前端 未结 5 907
日久生厌
日久生厌 2020-12-12 16:40

I would like to define a __version__ variable in my module which should be automatically updated on git commit similarly to what SVN keywords do. Is there a way

5条回答
  •  情书的邮戳
    2020-12-12 16:53

    You can use the following code to retrieve your current git commit version (reported as either a commit id on a branch or as a tag if a tag has been added:

    from git import Repo
    
    def GetGitVersion():
        '''report the git commit/branch/tag on which we are '''
        repo = Repo(".", search_parent_directories=True)
        git = repo.git    
    
        branchOrTag=git.rev_parse('--abbrev-ref', 'HEAD')
    
        if branchOrTag == 'HEAD':
            # get tag name
            # since several tags are sometime put on the same commit we want to retrieve all of them
            # and use the last one as reference
            # Note:
            # branchOrTag=`git describe --tags --exact-match` does not provided the latest created tag in case several point to the same place
            currentSha=git.rev_parse('--verify','HEAD')
    
            # list all tags on the current sha using most recent first:
            allTags=git.tag('--points-at',currentSha,'--sort=-creatordate')
            print (allTags)
    
            allTagsArray=allTags.split(' ') #create an array (assuming tags are separated by space)
    
            # if we checkouted a commit with no tag associated, the allTagsArray is empty we can use directly the sha value
            if len(allTagsArray) == 0:
                branchOrTag=git.rev-rev_parse('--short','HEAD') # take the short sha
            else:
    
                branchOrTag=allTagsArray[0] #first from the list
        else:
            #add the head commit id on the current branch
            branchOrTag="{}[{}]".format(branchOrTag,git.rev_parse('--short', 'HEAD'))
    
        return branchOrTag
    if __name__ == "__main__":
        print (GetGitVersion())
    

提交回复
热议问题