本文整理汇总了Python中pygit2.Repository.create_commit方法的典型用法代码示例。如果您正苦于以下问题:Python Repository.create_commit方法的具体用法?Python Repository.create_commit怎么用?Python Repository.create_commit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pygit2.Repository
的用法示例。
在下文中一共展示了Repository.create_commit方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: commit_new_tickets_to_git
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import create_commit [as 别名]
def commit_new_tickets_to_git(queue, repo_path):
global last_push_ts
#repo
repo = Repository(os.path.join(repo_path, '.git'))
index = repo.index
author = Signature('yourname', 'youremail')
while True:
#write tickets into file
ticket = queue.get(block=True)
#filename format is yyyy-mm-dd
d = datetime.utcnow().date()
filename = '%s.txt' % d.strftime('%Y-%m-%d')
f = open(os.path.join(repo_path, filename), 'ab')
f.write('%s\n' % ticket.toJson())
f.close()
#commit
index.add(filename)
index.write()
oid = index.write_tree()
repo.create_commit('HEAD', author, author, ticket.toJson(), oid, [repo.head.oid])
#push
d_ts = datetime.utcnow()
if last_push_ts is None or d_ts > (last_push_ts + timedelta(seconds = 60)):
push_to_github(repo_path)
last_push_ts = datetime.utcnow()
示例2: GitRepositoryTestCase
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import create_commit [as 别名]
class GitRepositoryTestCase(unittest.TestCase):
def setUp(self):
self.repo_path = mkdtemp()
init_repository(self.repo_path, False)
self.repo = Repository(self.repo_path)
def tearDown(self):
try:
rmtree(self.repo_path)
except:
pass
def test_create_repo(self):
repo_path = mkdtemp()
try:
GitRepository.create_repo(repo_path)
for f in [os.path.join('content', 'attachments', 'mercurial.png'),
os.path.join('content', 'post', 'example-post.rst'),
os.path.join('content', 'post', 'lorem-ipsum.rst'),
os.path.join('content', 'about.rst'),
os.path.join('static', 'screen.css'),
os.path.join('templates', 'base.html'),
os.path.join('templates', 'posts.html'),
os.path.join('templates', 'post_list.html'),
'config.yaml', '.gitignore', '.git']:
self.assertTrue(os.path.exists(os.path.join(repo_path, f)),
'Not found: %s' % f)
finally:
rmtree(repo_path)
def test_get_changectx_rev_default(self):
git_repo = GitRepository(self.repo_path)
with codecs.open(os.path.join(self.repo_path, 'foo.rst'), 'w',
encoding='utf-8') as fp:
fp.write('foo')
sign = Signature('foo', '[email protected]')
tree = self.repo.TreeBuilder().write()
self.repo.index.add('foo.rst')
self.repo.create_commit('refs/heads/master', sign, sign, 'foo', tree,
[])
self.assertTrue(isinstance(git_repo.get_changectx(REVISION_DEFAULT),
ChangeCtxDefault),
'changectx object is not an instance of '
'ChangeCtxDefault')
def test_get_changectx_rev_working_dir(self):
git_repo = GitRepository(self.repo_path)
with codecs.open(os.path.join(self.repo_path, 'foo.rst'), 'w',
encoding='utf-8') as fp:
fp.write('foo')
sign = Signature('foo', '[email protected]')
tree = self.repo.TreeBuilder().write()
self.repo.index.add('foo.rst')
self.repo.create_commit('refs/heads/master', sign, sign, 'foo', tree,
[])
self.assertTrue(
isinstance(git_repo.get_changectx(REVISION_WORKING_DIR),
ChangeCtxWorkingDir),
'changectx object is not an instance of ChangeCtxWorkingDir')
示例3: get_new_articles
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import create_commit [as 别名]
def get_new_articles():
blog = PelicanBlog()
content_dir = blog.get_content_directory()
repo = Repository(os.path.abspath(os.path.dirname(__file__)))
diff = repo.revparse_single("HEAD").tree.diff_to_tree()
existing_articles = set(os.path.relpath(obj.old_file_path, content_dir)
for obj in diff
if obj.old_file_path.startswith(content_dir))
all_articles = set(blog.get_posts())
new_articles = {art for art in all_articles - existing_articles
if blog.get_post_lang(art) in (TWITTER_LANGUAGE, "")}
new_titles = []
repo.index.read()
for newart in new_articles:
title = blog.get_post_title(newart)
yield Article(title, blog.get_post_url(newart),
blog.get_post_authors(newart))
new_titles.append(title)
repo.index.add(os.path.join(content_dir, newart))
blogger = Signature(repo.config["user.name"], repo.config["user.email"])
repo.create_commit("HEAD", blogger, blogger,
"[BLOG] %s" % ", ".join(new_titles),
repo.index.write_tree(), [repo.head.peel().oid])
repo.index.write()
# TODO(v.markovtsev): implement git push using pygit2
subprocess.call(("git", "push", "origin", repo.head.shorthand))
示例4: Repo
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import create_commit [as 别名]
class Repo(object):
def __init__(self,path,username,password):
self.repo = Repository(path)
self.username = username
self.password = password
self.path=path
def commit(self,file,refspec,email,author_username,message):
self.repo.index.add(file)
index = self.repo.index
index.write()
tree = self.repo.index.write_tree()
author = Signature(author_username,email)
self.repo.create_commit(refspec,
author,
author,message,tree, [self.repo.head.get_object().hex] )
def commit_fallback(self,message):
return subprocess.check_output(["git","commit","-m",message],cwd=self.path)
def push(self,refspec):
credentials = UserPass(self.username,self.password)
remoteCall = RemoteCallbacks(credentials)
remo = self.repo.remotes["origin"]
remo.push(refspec,remoteCall)
示例5: createcommit
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import create_commit [as 别名]
def createcommit(self):
"""Prepare a git repository with one existing commit.
Create a directory, initialize a git Repository, add
and commit a file.
Returns:
A list containing the directory and file
"""
self.addfile()
# Create commit
repo = Repository(self.dir.name)
index = repo.index
index.read()
tree = index.write_tree()
message = "First commit of temporary test repo"
repo.create_commit('HEAD',
self.author, self.comitter, message,
tree,
[])
示例6: shift
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import create_commit [as 别名]
def shift(amount, repo_path):
repo = Repository(repo_path)
head = repo.lookup_reference('HEAD').resolve()
adder = partial(add, amount=amount)
changelog = dict()
reference = REF_FMT.format(time=time(), pid=getpid())
for commit in repo.walk(head.oid, GIT_SORT_REVERSE | GIT_SORT_TOPOLOGICAL):
newmsg, nsubs = ISSUE_RE.subn(adder, commit.message)
if nsubs != 0 or any(pnt.oid in changelog for pnt in commit.parents):
parents = [changelog.get(c.oid, c.oid) for c in commit.parents]
new_oid = repo.create_commit(reference, commit.author,
commit.committer, newmsg, commit.tree.oid, parents)
changelog[commit.oid] = new_oid
return changelog, reference
示例7: DictRepository
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import create_commit [as 别名]
class DictRepository(object):
"""The :class:`DictRepository <DictRepository>` object.
:param repo_or_path:
The path to a repository, or an existing pygit2.Repository object.
If it is a path that does not exist, a new bare git repository will
be initialized there. If it is a path that does exist, then the
directory will be used as a bare git repository.
:type repo_or_path: string or pygit2.Repository
"""
def __init__(self, repo_or_path=None):
self._default_author = get_default_author()
if isinstance(repo_or_path, Repository):
self._repo = repo_or_path
elif os.path.isdir(repo_or_path):
self._repo = Repository(repo_or_path)
else:
self._repo = init_repository(repo_or_path, True) # bare repo
def _key_to_ref(self, key):
return "refs/%s/HEAD" % key
def get_commit_oid_for_key(self, key):
return self._repo[self._repo.lookup_reference(self._key_to_ref(key)).oid].oid
def get_raw_dict_for_commit_oid(self, commit_oid):
return json.loads(self._repo[self._repo[commit_oid].tree[DATA].oid].data)
def get_parent_oids_for_commit_oid(self, commit_oid):
return [parent.oid for parent in self._repo[commit_oid].parents]
def raw_commit(self, key, raw_dict, author, committer, message, parents):
"""Commit a dict to this :class:`DictRepository <DictRepository>`.
It is recommended that you use the :class:`GitDict <GitDict>` commit
method instead.
:param raw_dict: the data to commit.
:type raw_dict: dict
:param author:
The author of the commit. If None, will be replaced with default.
:type author: pygit2.Signature
:param committer:
The committer of this commit. If None, will be replaced with author.
:type committer: pygit2.Signature
:param message: The commit message.
:type message: string
:param parents:
A list of 20-byte object IDs of parent commits. An empty list
means this is the first commit.
:return: The oid of the new commit.
:rtype: 20 bytes
"""
if not isinstance(raw_dict, dict):
raise ValueError("%s is not a dict" % raw_dict)
author = author or self._default_author.signature()
committer = committer or author
blob_id = self._repo.write(GIT_OBJ_BLOB, json.dumps(raw_dict))
# TreeBuilder doesn't support inserting into trees, so we roll our own
tree_id = self._repo.write(GIT_OBJ_TREE, "100644 %s\x00%s" % (DATA, blob_id))
return self._repo.create_commit(self._key_to_ref(key), author, committer, message, tree_id, parents)
def create(self, key, dict={}, autocommit=False, message="first commit", author=None, committer=None):
"""Create a new :class:`GitDict <GitDict>`
:param key: The key of the new :class:`GitDict <GitDict>`
:type key: :class:`GitDict <GitDict>`
:param dict: (optional) The value of the dict. Defaults to empty.
:type dict: dict
:param autocommit:
(optional) Whether the :class:`GitDict <GitDict>` should
automatically commit. Defaults to false.
:type autocommit: boolean
:param message:
(optional) Message for first commit. Defaults to "first commit".
:type message: string
:param author:
(optional) The signature for the author of the first commit.
Defaults to global author.
:type author: pygit2.Signature
:param committer:
(optional) The signature for the committer of the first commit.
Defaults to author.
:type author: pygit2.Signature
:returns: the GitDict
:rtype: :class:`GitDict <GitDict>`
"""
self.raw_commit(key, dict, author, committer, message, [])
return self.get(key, autocommit=autocommit)
def has(self, key):
"""Determine whether there is an entry for key in this repository.
#.........这里部分代码省略.........
示例8: open
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import create_commit [as 别名]
from pygit2 import Repository, Signature
import os
from datetime import datetime, date
from subprocess import call
d = datetime.utcnow().date()
path = '/home/xubin/workspace/tickets_history/'
name = '%s.txt' % d.strftime('%Y-%m-%d')
abspath = os.path.join(path, name)
f = open(abspath, 'ab')
f.write('test\n');
f.close()
repo = Repository(os.path.join(path, '.git'))
index = repo.index
index.add(name)
index.write()
oid = index.write_tree()
author = Signature('icefreedom', '[email protected]')
cm = repo.create_commit('HEAD', author, author, 'test', oid, [repo.head.oid])
username = 'icefreedom'
passwd = '87650872ice'
remote_repo = 'https://%s:%[email protected]/icefreedom/tickets_history.git' % (username, passwd)
call(['cd "' + path + '" && git push ' + remote_repo] , shell=True)
示例9: GitStorage
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import create_commit [as 别名]
class GitStorage(Storage):
""" Git file storage backend. """
def __init__(self, path):
"""
Initialize repository.
:param path: Absolute path to the existing Git repository.
:type path: str
"""
super(GitStorage, self).__init__()
self.repo = Repository(path)
self.index = self.repo.index
self.index.read()
@classmethod
def create_storage(cls, path):
"""
Create repository, and return GitStorage object on it
:param path: Absolute path to the Git repository to create.
:type path: str
:returns: GitStorage
"""
init_repository(path, False)
return cls(path)
def commit(self, user, message):
"""
Save previous changes in a new commit.
:param user: The commit author/committer.
:type user: django.contrib.auth.models.User
:param message: The commit message.
:type message: unicode
:returns: pygit2.Commit
"""
# Refresh index before committing
index = self.repo.index
index.read()
# Check the status of the repository
status = self.repo.status()
for filename, flags in status.items():
# the file was deleted
if flags in (GIT_STATUS_INDEX_DELETED, GIT_STATUS_WT_DELETED):
# remove it from the tree
del index[filename]
# or the file was modified/added
elif flags in (GIT_STATUS_INDEX_MODIFIED, GIT_STATUS_INDEX_NEW,
GIT_STATUS_WT_MODIFIED, GIT_STATUS_WT_NEW):
# add it to the tree
index.add(filename)
treeid = index.write_tree()
# Now make the commit
author = Signature(u'{0} {1}'.format(
user.first_name,
user.last_name).encode('utf-8'),
user.email.encode('utf-8')
)
committer = author
try:
parents = [self.repo.head.oid]
except GitError:
parents = []
commit = self.repo.create_commit(
'refs/heads/master',
author, committer, message,
treeid,
parents
)
# Write changes to disk
index.write()
# and refresh index.
self.index.read()
# Return commit object
return self.repo[commit]
def log(self, name=None, limit=10):
"""
Get history of the repository, or of a file if name is not None.
:param name: File name within the repository.
:type name: unicode or None
:param limit: Maximal number of commits to get (default: 10), use a negative number to get all.
#.........这里部分代码省略.........
示例10: GitHandler
# 需要导入模块: from pygit2 import Repository [as 别名]
# 或者: from pygit2.Repository import create_commit [as 别名]
class GitHandler(object):
def __init__(self, path, repo_path=None, update_working_copy=True):
"""
Start a git handler in given repository.
`update_working_copy`: wether also to update the working copy.
By default, the git handler will only work on the git database.
Updating the working copy can take a lot of time in
large repositories.
"""
self.path = path
if repo_path is None:
repo_path = self.path
self.repo_path = repo_path
self.update_working_copy = update_working_copy
self.repo = Repository(self.repo_path)
self.working_tree = self.get_last_tree()
self.tree_modifier = TreeModifier(self.repo, self.working_tree)
self.messages = []
print("Started libgit2 git handler in ", self.path)
def get_last_tree(self):
if self.repo.head_is_unborn:
tree_id = self.repo.TreeBuilder().write()
return self.repo[tree_id]
commit = self.repo[self.getCurrentCommit()]
return commit.tree
def insert_into_working_tree(self, blob_id, filename):
self.tree_modifier.insert_blob(blob_id, filename)
def remove_from_working_tree(self, filename):
self.tree_modifier.remove_blob(filename)
def write_file(self, filename, content):
# TODO: combine writing many files
assert isinstance(content, text_type)
data = content.encode('utf-8')
existing_entry = get_tree_entry(self.repo, self.working_tree, filename)
if existing_entry:
type = 'M'
if existing_entry.id == git_hash(data):
return
else:
type = 'A'
blob_id = self.repo.create_blob(data)
self.insert_into_working_tree(blob_id, filename)
if not self.repo.is_bare and self.update_working_copy:
real_filename = os.path.join(self.path, filename)
mkdir_p(os.path.dirname(real_filename))
with codecs.open(real_filename, 'w', encoding='utf-8') as outfile:
outfile.write(content)
self.messages.append(' {} {}'.format(type, filename))
def remove_file(self, filename):
existing_entry = get_tree_entry(self.repo, self.working_tree, filename)
if existing_entry:
self.remove_from_working_tree(filename)
if not self.repo.is_bare and self.update_working_copy:
remove_file_with_empty_parents(self.path, filename)
self.messages.append(' D {}'.format(filename))
def move_file(self, old_filename, new_filename):
self.tree_modifier.move(old_filename, new_filename)
if not self.repo.is_bare and self.update_working_copy:
real_old_filename = os.path.join(self.path, old_filename)
real_new_filename = os.path.join(self.path, new_filename)
mkdir_p(os.path.dirname(real_new_filename))
os.rename(real_old_filename, real_new_filename)
remove_file_with_empty_parents(self.path, old_filename)
self.messages.append(' R {} -> {}'.format(old_filename,
new_filename))
def commit(self):
if self.tree_modifier.tree.oid != self.get_last_tree().oid:
raise Exception("The repository was modified outside of this process. For safety reasons, we cannot commit!")
self.working_tree = self.tree_modifier.apply()
self.tree_modifier = TreeModifier(self.repo, self.working_tree)
if self.repo.head_is_unborn:
parents = []
else:
commit = self.repo[self.getCurrentCommit()]
if commit.tree.id == self.working_tree.id:
return
parents = [commit.id]
config = self.repo.config
author = Signature(config['user.name'], config['user.email'])
committer = Signature(config['user.name'], config['user.email'])
tree_id = self.working_tree.id
message = '\n'.join(self.messages)
self.repo.create_commit('refs/heads/master',
author, committer, message,
tree_id,
#.........这里部分代码省略.........