本文整理汇总了Python中git.Repo.config_writer方法的典型用法代码示例。如果您正苦于以下问题:Python Repo.config_writer方法的具体用法?Python Repo.config_writer怎么用?Python Repo.config_writer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类git.Repo
的用法示例。
在下文中一共展示了Repo.config_writer方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _git_apply_changes
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import config_writer [as 别名]
def _git_apply_changes(self, updates):
""" add/remove changed files.
Keyword arguments:
updates -- list of update message to put in commit message.
notes:
- Will ignore file mode changes and anything in the commonIgnore setting.
"""
os.chdir(self.site_dir)
repo = Repo(self.site_dir)
for ignore_file in self.settings.get('commonIgnore'):
try:
repo.git.checkout(os.path.join(self.site_web_root, ignore_file))
except git.exc.GitCommandError:
pass
if self.repo_status['modules'] and self.settings.get('ignoreCustomModules'):
custom_module_dir = os.path.join(self.site_web_root,
self.repo_status['modules'], 'custom')
try:
repo.git.checkout(custom_module_dir)
except git.exc.GitCommandError:
pass
# Instruct Git to ignore file mode changes.
cwriter = repo.config_writer('global')
cwriter.set_value('core', 'fileMode', 'false')
cwriter.release()
# Add new/changed files to Git's index
try:
repo.git.add('--all')
except git.exc.GitCommandError as git_add_error:
raise DrupdatesUpdateError(20, git_add_error)
# Remove deleted files from Git's index.
deleted = repo.git.ls_files('--deleted')
for filepath in deleted.split():
repo.git.rm(filepath)
# Commit all the changes.
if self.settings.get('useFeatureBranch'):
if self.settings.get('featureBranchName'):
branch_name = self.settings.get('featureBranchName')
else:
ts = time.time()
stamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
branch_name = "drupdates-{0}".format(stamp)
repo.git.checkout(self.working_branch, b=branch_name)
else:
branch_name = self.settings.get('workingBranch')
repo.git.checkout(self.working_branch)
msg = ''
for site, update in updates.items():
msg += "\n{0} \n {1}".format(site, '\n'.join(update))
commit_author = Actor(self.settings.get('commitAuthorName'), self.settings.get('commitAuthorEmail'))
repo.index.commit(message=msg, author=commit_author)
# Save the commit hash for the Drupdates report to use.
heads = repo.heads
branch = heads[branch_name]
self.commit_hash = branch.commit
# Push the changes to the origin repo.
repo.git.push(self._site_name, branch_name)
示例2: make_commit
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import config_writer [as 别名]
def make_commit(repo_path, key=None, user='user', email='[email protected]'):
repo = Repo(repo_path)
#repo.git.config('--global', 'gpg.program', here('../../gpg-with-fingerprint'))
# if not key:
# key = assert_keys()
repo.config_writer().set_value(section='user', option='name', value=user).set_value(
section='user', option='email', value=email).release()
if key:
repo.config_writer().set_value(
section='user', option='signingkey', value=key).release()
for i in range(0, 10000):
repo.git.add('.')
if key:
sign = "-S"
else:
sign = None
try:
repo.git.commit("-a", sign, "-m", str(i))
except GitCommandError as e:
logger.info(e)
return False, {'git': str(e)}
#import IPython; IPython.embed()
sha = repo.head.commit.hexsha
logger.info("sha: %s, %s", sha, i)
errors = validate_commit(repo_path, repo.head.commit)
logger.info('errors %s', repr(errors))
if errors == {}: # no problems!
logger.info('done commiting')
repo.git.checkout('master')
return True, errors
# Try again for proper POW
repo.git.checkout('master')
repo.git.reset('HEAD~')
# Just kidding, somethign else wrong happened, bail out
if list(errors.keys()) != ['pow']:
logger.info('not going to try anymore')
return False, errors
# POW was too difficult
return False, errors
示例3: test_init_repo_object
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import config_writer [as 别名]
def test_init_repo_object(self, rw_dir):
# [1-test_init_repo_object]
from git import Repo
join = os.path.join
# rorepo is a a Repo instance pointing to the git-python repository.
# For all you know, the first argument to Repo is a path to the repository
# you want to work with
repo = Repo(self.rorepo.working_tree_dir)
assert not repo.bare
# ![1-test_init_repo_object]
# [2-test_init_repo_object]
bare_repo = Repo.init(join(rw_dir, 'bare-repo'), bare=True)
assert bare_repo.bare
# ![2-test_init_repo_object]
# [3-test_init_repo_object]
repo.config_reader() # get a config reader for read-only access
cw = repo.config_writer() # get a config writer to change configuration
cw.release() # call release() to be sure changes are written and locks are released
# ![3-test_init_repo_object]
# [4-test_init_repo_object]
assert not bare_repo.is_dirty() # check the dirty state
repo.untracked_files # retrieve a list of untracked files
# ['my_untracked_file']
# ![4-test_init_repo_object]
# [5-test_init_repo_object]
cloned_repo = repo.clone(join(rw_dir, 'to/this/path'))
assert cloned_repo.__class__ is Repo # clone an existing repository
assert Repo.init(join(rw_dir, 'path/for/new/repo')).__class__ is Repo
# ![5-test_init_repo_object]
# [6-test_init_repo_object]
repo.archive(open(join(rw_dir, 'repo.tar'), 'wb'))
# ![6-test_init_repo_object]
# repository paths
# [7-test_init_repo_object]
assert os.path.isdir(cloned_repo.working_tree_dir) # directory with your work files
assert cloned_repo.git_dir.startswith(cloned_repo.working_tree_dir) # directory containing the git repository
assert bare_repo.working_tree_dir is None # bare repositories have no working tree
# ![7-test_init_repo_object]
# heads, tags and references
# heads are branches in git-speak
# [8-test_init_repo_object]
assert repo.head.ref == repo.heads.master # head is a symbolic reference pointing to master
assert repo.tags['0.3.5'] == repo.tag('refs/tags/0.3.5') # you can access tags in various ways too
assert repo.refs.master == repo.heads['master'] # .refs provides access to all refs, i.e. heads ...
assert repo.refs['origin/master'] == repo.remotes.origin.refs.master # ... remotes ...
assert repo.refs['0.3.5'] == repo.tags['0.3.5'] # ... and tags
# ![8-test_init_repo_object]
# create a new head/branch
# [9-test_init_repo_object]
new_branch = cloned_repo.create_head('feature') # create a new branch ...
assert cloned_repo.active_branch != new_branch # which wasn't checked out yet ...
assert new_branch.commit == cloned_repo.active_branch.commit # and which points to the checked-out commit
# It's easy to let a branch point to the previous commit, without affecting anything else
# Each reference provides access to the git object it points to, usually commits
assert new_branch.set_commit('HEAD~1').commit == cloned_repo.active_branch.commit.parents[0]
# ![9-test_init_repo_object]
# create a new tag reference
# [10-test_init_repo_object]
past = cloned_repo.create_tag('past', ref=new_branch,
message="This is a tag-object pointing to %s" % new_branch.name)
assert past.commit == new_branch.commit # the tag points to the specified commit
assert past.tag.message.startswith("This is") # and its object carries the message provided
now = cloned_repo.create_tag('now') # This is a tag-reference. It may not carry meta-data
assert now.tag is None
# ![10-test_init_repo_object]
# Object handling
# [11-test_init_repo_object]
assert now.commit.message != past.commit.message
# You can read objects directly through binary streams, no working tree required
assert (now.commit.tree / 'VERSION').data_stream.read().decode('ascii').startswith('0')
# You can traverse trees as well to handle all contained files of a particular commit
file_count = 0
tree_count = 0
tree = past.commit.tree
for item in tree.traverse():
file_count += item.type == 'blob'
tree_count += item.type == 'tree'
assert file_count and tree_count # we have accumulated all directories and files
assert len(tree.blobs) + len(tree.trees) == len(tree) # a tree is iterable itself to traverse its children
# ![11-test_init_repo_object]
# remotes allow handling push, pull and fetch operations
# [12-test_init_repo_object]
from git import RemoteProgress
class MyProgressPrinter(RemoteProgress):
def update(self, op_code, cur_count, max_count=None, message=''):
#.........这里部分代码省略.........
示例4: Repo
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import config_writer [as 别名]
#! /usr/bin/env python
import os
from git import Repo
join = os.path.join
repo = Repo('/home/colm/git/prototypes/')
repo.config_reader()
cw = repo.config_writer()
cw.release()
print cw
示例5: GitFlow
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import config_writer [as 别名]
#.........这里部分代码省略.........
self.is_set('gitflow.prefix.feature') and
self.is_set('gitflow.prefix.release') and
self.is_set('gitflow.prefix.hotfix') and
self.is_set('gitflow.prefix.support') and
self.is_set('gitflow.prefix.versiontag'))
def _parse_setting(self, setting):
groups = setting.split('.', 2)
if len(groups) == 2:
section, option = groups
elif len(groups) == 3:
section, subsection, option = groups
section = '%s "%s"' % (section, subsection)
else:
raise ValueError('Invalid setting name: %s' % setting)
return (section, option)
@requires_repo
def get(self, setting, default=_NONE):
section, option = self._parse_setting(setting)
try:
return self.repo.config_reader().get_value(section, option)
except (NoSectionError, NoOptionError):
if default is not _NONE:
return default
raise
def get_prefix(self, identifier):
return self._safe_get('gitflow.prefix.%s' % (identifier,))
@requires_repo
def set(self, setting, value):
section, option = self._parse_setting(setting)
writer = self.repo.config_writer()
writer.set_value(section, option, value)
writer.release()
del writer
def is_set(self, setting):
return self.get(setting, None) is not None
@requires_repo
def _safe_get(self, setting_name):
try:
return self.get(setting_name)
except (NoSectionError, NoOptionError):
raise NotInitialized('This repo has not yet been initialized.')
def master_name(self):
return self._safe_get('gitflow.branch.master')
def develop_name(self):
return self._safe_get('gitflow.branch.develop')
def origin_name(self, name=None):
origin = self.get('gitflow.origin', self.defaults['gitflow.origin'])
if name is not None:
return origin + '/' + name
else:
return origin
@requires_repo
def require_remote(self, name):
try:
return self.repo.remotes[name]
except IndexError:
示例6: GitFlow
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import config_writer [as 别名]
#.........这里部分代码省略.........
self.is_set('gitflow.prefix.release') and
self.is_set('gitflow.prefix.hotfix') and
self.is_set('gitflow.prefix.support') and
self.is_set('gitflow.prefix.versiontag') and
self.is_set('gitflow.release.versionmatcher'))
def _parse_setting(self, setting):
groups = setting.split('.', 2)
if len(groups) == 2:
section, option = groups
elif len(groups) == 3:
section, subsection, option = groups
section = '%s "%s"' % (section, subsection)
else:
raise ValueError('Invalid setting name: %s' % setting)
return (section, option)
@requires_repo
def get(self, setting, default=_NONE):
section, option = self._parse_setting(setting)
try:
return self.repo.config_reader().get_value(section, option)
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
if default is not _NONE:
return default
raise
def get_prefix(self, identifier):
return self._safe_get('gitflow.prefix.%s' % (identifier,))
@requires_repo
def set(self, setting, value):
section, option = self._parse_setting(setting)
self.repo.config_writer().set_value(section, option, value)
def is_set(self, setting):
return self.get(setting, None) is not None
@requires_repo
def _safe_get(self, setting_name):
try:
return self.get(setting_name)
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
raise NotInitialized('This repo has not yet been initialized.')
def master_name(self):
return self._safe_get('gitflow.branch.master')
def develop_name(self):
return self._safe_get('gitflow.branch.develop')
def origin_name(self, name=None):
origin = self.get('gitflow.origin', self.defaults['gitflow.origin'])
if name is not None:
return origin + '/' + name
else:
return origin
@requires_repo
def require_remote(self, name):
try:
remote = self.repo.remotes[name]
except IndexError:
raise NoSuchRemoteError("Remote '{0}' was not found.".format(name))
示例7: Post
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import config_writer [as 别名]
class Post(object):
def __init__(self, directory, filename):
self.filename = filename.decode('utf-8')
self.root = directory
self.repo = Repo(self.root)
self.path = path.join(self.root, self.filename)
def __eq__(self, other):
return hash(self) == hash(other)
def __hash__(self):
return int(md5(str(self)).hexdigest(), 16)
def __repr__(self):
return str(self)
def __str__(self):
return self.path.encode('utf-8')
@memoize_for_head
def _get_authors(self):
authors = set(
[c.author for c in self.repo.iter_commits(\
paths=self.filename.encode('utf-8'))]
)
return [{'name': a.name, 'email': a.email} for a in authors]
authors = property(_get_authors)
@memoize_for_head
def _get_content(self):
try:
blob = self.repo.heads.master.commit.tree[self.filename]
return blob.data_stream.read()
except KeyError:
return None
content = property(_get_content)
@memoize_for_head
def _get_commits(self):
commits = list(self.repo.iter_commits(\
paths=self.filename.encode('utf-8')))
return commits
commits = property(_get_commits)
@memoize
def _get_creation_datetime(self):
timestamp = self.commits[-1].authored_date
return datetime.fromtimestamp(timestamp)
creation_datetime = property(_get_creation_datetime)
@memoize_for_head
def _get_update_datetime(self):
timestamp = self.repo.iter_commits(\
paths=self.filename.encode('utf-8')).next().authored_date
return datetime.fromtimestamp(timestamp)
update_datetime = property(_get_update_datetime)
@memoize_for_head
def _exists(self):
return bool(self.commits)
exists = property(_exists)
def get_content(self):
return self.content
@memoize_for_head
def get_title(self):
document = parseFragment(self.content, treebuilder='etree', \
namespaceHTMLElements=False, encoding='utf-8')
try:
text = \
' '.join([w for w in document.find('.//h1').itertext()])
return text.encode('utf-8')
except AttributeError:
return None
title = property(get_title)
def update_content(self, content, author, email, message):
config = self.repo.config_writer()
config.set_value("user", "name", author);
config.set_value("user", "email", email);
istream = IStream("blob", len(content), StringIO(content))
self.repo.odb.store(istream)
blob = Blob(self.repo, istream.binsha, 0100644, self.filename.encode('utf-8'))
self.repo.index.add([IndexEntry.from_blob(blob)])
self.repo.index.commit(message)