我想提交一个自定义日期的文件。
到目前为止,我已经创建了一个Commit对象,但我不明白如何将它绑定到repo。
from git import *
repo = Repo('path/to/repo')
comm = Commit(repo=repo, binsha=repo.head.commit.binsha, tree=repo.index.write_tree(), message='Test Message', committed_date=1357020000)
谢谢!
答案 0 :(得分:3)
我找到了解决方案。
我不知道,但我必须提供所有参数,否则在尝试序列化时,Commit对象会抛出BadObject异常。
from git import *
from time import (time, altzone)
import datetime
from cStringIO import StringIO
from gitdb import IStream
repo = Repo('path/to/repo')
message = 'Commit message'
tree = repo.index.write_tree()
parents = [ repo.head.commit ]
# Committer and Author
cr = repo.config_reader()
committer = Actor.committer(cr)
author = Actor.author(cr)
# Custom Date
time = int(datetime.date(2013, 1, 1).strftime('%s'))
offset = altzone
author_time, author_offset = time, offset
committer_time, committer_offset = time, offset
# UTF-8 Default
conf_encoding = 'UTF-8'
comm = Commit(repo, Commit.NULL_BIN_SHA, tree,
author, author_time, author_offset,
committer, committer_time, committer_offset,
message, parents, conf_encoding)
创建提交对象后,必须放置一个正确的SHA,我不知道这是怎么做的,但是对GitPython源代码的一些研究得到了答案。
stream = StringIO()
new_commit._serialize(stream)
streamlen = stream.tell()
stream.seek(0)
istream = repo.odb.store(IStream(Commit.type, streamlen, stream))
new_commit.binsha = istream.binsha
然后将提交设置为HEAD提交
repo.head.set_commit(new_commit, logmsg="commit: %s" % message)
答案 1 :(得分:1)
一个更简单的解决方案,它可以避免手动创建提交对象(如果您还想添加文件,还可以手动创建新索引):
from git import Repo, Actor # GitPython
import git.exc as GitExceptions # GitPython
import os # Python Core
# Example values
respository_directory = "."
new_file_path = "MyNewFile"
action_date = str(datetime.date(2013, 1, 1))
message = "I am a commit log! See commit log run. Run! Commit log! Run!"
actor = Actor("Bob", "Bob@McTesterson.dev" )
# Open repository
try:
repo = Repo(respository_directory)
except GitExceptions.InvalidGitRepositoryError:
print "Error: %s isn't a git repo" % respository_directory
sys.exit(5)
# Set some environment variables, the repo.index commit function
# pays attention to these.
os.environ["GIT_AUTHOR_DATE"] = action_date
os.environ["GIT_COMMITTER_DATE"] = action_date
# Add your new file/s
repo.index.add([new_file_path])
# Do the commit thing.
repo.index.commit(message, author=actor, committer=actor)
答案 2 :(得分:0)
我还将指定的日期/时间用于提交目的。在经过长期研究之后,我发现我必须不像GitPython建议的那样以datetime
格式提供timestamp
,而不是像GitPython建议的那样以ISO格式。它实际上是在做错觉,因为它本身具有“解析”功能,应该是标准的python格式。
不。您必须以git本身可以理解的格式提供它。
例如:
# commit_date is your specified date in datetime format
commit_date_as_text = commit_date.strftime('%Y-%m-%d %H:%M:%S %z')
git_repository.index.commit(commit_message, author=commit_author, commit_date=commit_date_as_text)
可以在another topic on StackOverflow中找到可接受格式的列表。
答案 3 :(得分:0)
您可以在进行提交时设置commit_date
。
r.index.commit(
"Initial Commit",
commit_date=datetime.date(2020, 7, 21).strftime('%Y-%m-%d %H:%M:%S')
)