やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

GitPythonでコミットログを参照してみた

簡単だった。

成果物

GitHubGitPython.Hello.201706191555

参考

インストール

(webapi) $ pip install GitPython
Collecting GitPython
  Downloading GitPython-2.1.5-py2.py3-none-any.whl (443kB)
    100% |████████████████████████████████| 450kB 643kB/s 
Collecting gitdb2>=2.0.0 (from GitPython)
  Downloading gitdb2-2.0.2-py2.py3-none-any.whl (63kB)
    100% |████████████████████████████████| 71kB 1.7MB/s 
Collecting smmap2>=2.0.0 (from gitdb2>=2.0.0->GitPython)
  Downloading smmap2-2.0.3-py2.py3-none-any.whl
Installing collected packages: smmap2, gitdb2, GitPython
Successfully installed GitPython-2.1.5 gitdb2-2.0.2 smmap2-2.0.3

あっさり成功。

コード

import git
import os.path
import datetime
import pytz
path_local_repo = os.path.abspath(os.path.dirname(__file__))
if os.path.isdir(os.path.join(path_local_repo, '.git')): repo = git.Repo(path_local_repo)
else:
    repo = git.Repo.init()
    repo.index.add([__file__])
    repo.index.commit('初回コミット。')
for item in repo.iter_commits('master'):
    print(item)
    print('hexsha:', item.hexsha)
    print(item.__class__) # git.objects.commit.Commit
    print('author:', item.author)
    print('authored_date:', item.authored_date)
    print('author_tz_offset:', item.author_tz_offset)
    print('committer:', item.committer)
    print('committed_date:', item.committed_date)
    print('committer_tz_offset:', item.committer_tz_offset)
    print('message:', item.message)
    print('summary:', item.summary)
    print('stats:', item.stats)
    print('parents:', item.parents)
    print('tree:', item.tree)

    t = datetime.datetime.fromtimestamp(item.authored_date)
    print(t)
$ python main.py 
0adfb13efd21d5a4cda3cd5f0ecec75b701f0c85
hexsha: 0adfb13efd21d5a4cda3cd5f0ecec75b701f0c85
<class 'git.objects.commit.Commit'>
author: xxxxxxx
authored_date: 1497855921
author_tz_offset: -32400
committer: xxxxxxx
committed_date: 1497855921
committer_tz_offset: -32400
message: 初回コミット。
summary: 初回コミット。
stats: <git.util.Stats object at 0xb6c3d52c>
parents: ()
tree: 21bfa88f7b27958727da5bd65b1406012daab89f
2017-06-19 16:05:21

これさえわかればいい。細かいことはハッシュがあれば何とかなるはず。

日時

gitに記録されていた日付はエポックタイムだった。

以下でローカル時刻にできる。

datetime.datetime.fromtimestamp(item.authored_date)
符号なし 符号つき 状態の数 状態1を1秒としたときの表現可能期間 期限
2Byte 4Byte 2147483647 68年 2038年
4Byte 8Byte 4294967296 136年 2106年

C言語のintは符号つき4Byteなので2038年まで。いわゆる2038年問題の原因。SQLite3のINT型は符号つき8Byteなので2106年まで。私はもう死んでいると思われる。

所感

最低限の使い方を確認できた。