本文整理汇总了Python中git.Repo方法的典型用法代码示例。如果您正苦于以下问题:Python git.Repo方法的具体用法?Python git.Repo怎么用?Python git.Repo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类git
的用法示例。
在下文中一共展示了git.Repo方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_last_release_versions
# 需要导入模块: import git [as 别名]
# 或者: from git import Repo [as 别名]
def get_last_release_versions(repo: Repo) -> Tuple[Version, Version]:
print("get latest release version")
commit_to_tag = {tag.commit.hexsha: tag for tag in repo.tags}
_, release_tag = sorted(
[(tag.commit.committed_datetime, tag) for tag in repo.tags], reverse=True,
)[0]
for commit in release_tag.commit.iter_parents():
if commit.hexsha in commit_to_tag:
prev_release_tag = commit_to_tag[commit.hexsha]
prev_version = Version(prev_release_tag.name)
if not any(
(
prev_version.is_devrelease,
prev_version.is_prerelease,
prev_version.is_postrelease,
),
):
break
else:
raise RuntimeError("no previous release")
release_version = Version(release_tag.name)
print(f"\trelease {release_version} with previous {prev_version}")
return prev_version, release_version
示例2: iter_sources_and_tests
# 需要导入模块: import git [as 别名]
# 或者: from git import Repo [as 别名]
def iter_sources_and_tests(repository_path, configuration_file_path=None):
if configuration_file_path is None:
configuration_file_path = os.path.join(repository_path, 'git-hammer-config.json')
configuration = Configuration(configuration_file_path)
repository = git.Repo(repository_path)
for git_object in repository.tree().traverse(visit_once=True):
if git_object.type != 'blob':
continue
if configuration.is_source_file(git_object.path):
if configuration.is_test_file(git_object.path):
yield 'test-file', git_object.path
lines = [line.decode('utf-8', 'ignore') for line in
io.BytesIO(git_object.data_stream.read()).readlines()]
for line in configuration.iter_test_lines(git_object.path, lines):
yield 'test-line', line.rstrip()
else:
yield 'source-file', git_object.path
示例3: all_versions
# 需要导入模块: import git [as 别名]
# 或者: from git import Repo [as 别名]
def all_versions(filename):
"""
Find, open and parse all tagged versions of a json file, including the current version
:param filename: The filename to find
:return: a dictionary of all the versions, in the form
{
'current': {...},
'1.0': {...},
'1.1': {...}
}
"""
repo = git.Repo()
versions = {
'current': get_json(filename)
}
for tag in repo.tags:
version_dict = repo.git.show('%s:%s' % (tag.name, filename))
versions[tag.name.strip('v')] = json.loads(version_dict)
return versions
示例4: _dependency
# 需要导入模块: import git [as 别名]
# 或者: from git import Repo [as 别名]
def _dependency(module):
path = os.path.dirname(module.__file__)
parent = os.path.dirname(path)
try:
fp = open(os.path.join(path, 'VERSION'))
except:
try:
fp = open(os.path.join(parent, 'VERSION'))
except:
fp = None
version = fp.read().strip() if fp else NONE
try:
import git
repo = git.Repo(os.path.dirname(path))
except:
commit_id = tag = NONE
else:
commit_id = repo.commit('HEAD').hexsha[:7]
tag = repo.tags[-1].name if repo.tags else '(none)'
return (' %s: version %s, git commit: %s, git tag %s' %
(module.__name__, version, commit_id, tag))
示例5: main
# 需要导入模块: import git [as 别名]
# 或者: from git import Repo [as 别名]
def main():
"""Entry point."""
commit_hash = os.environ["GITHUB_SHA"]
tweet_trigger_str = os.environ["INPUT_TRIGGER_KEYWORD"]
print("Commit: {}\nTrigger: {}".format(commit_hash, tweet_trigger_str))
repo = Repo(os.getcwd())
commit = repo.commit(commit_hash)
if tweet_trigger_str not in commit.message:
print("Tweet trigger keyword not found, exiting...")
sys.exit(0)
print("Tweet trigger detected, let's tweet!")
entries = get_commit_list_entries(commit)
readme = get_commit_readme(commit)
for i, entry in enumerate(entries):
section = get_entry_section(readme, entry["entry"])
msg = format_tweet_msg(
section, entry["title"], entry["url"], entry["description"]
)
print('Tweet msg #{}:\n\t"{}"'.format(i, msg.replace("\n", "\n\t")))
tweet_msg(msg)
print("Tweeted #{}!".format(i))
示例6: get_commits
# 需要导入模块: import git [as 别名]
# 或者: from git import Repo [as 别名]
def get_commits(self, path_to_repo, branch='master'):
'''get the list of commits from a repo
Args:
path_to_repo (str): path to the git repo
branch (str): the brnch name, e.g. 'master'
Returns:
repo (Repo): git Repo
commits (list): list of commits in going forward in time (oldest -> newest)
'''
repo = git.Repo(path_to_repo)
commits = list(repo.iter_commits(branch))
#reverse as we want oldest first so that gif goes forward in time
commits.reverse()
return repo, commits
示例7: test_get_commits
# 需要导入模块: import git [as 别名]
# 或者: from git import Repo [as 别名]
def test_get_commits():
config = {
"infile_globs": [
"test/grapher/*.lkml"
],
"options": {
"node_size": 400,
"label_font_size": 10,
"text_angle": 30,
"image_width": 12,
"image_height" : 8
}
}
animator = GraphAnimator(config)
repo, commits = animator.get_commits("./", branch='master')
assert isinstance(repo, git.Repo)
assert len(commits) > 1
assert isinstance(commits[0], git.Commit)
示例8: repo_info
# 需要导入模块: import git [as 别名]
# 或者: from git import Repo [as 别名]
def repo_info():
"""Collect important repo info and store as facts."""
changed_files = list()
entries = list()
repo_remotes = list()
repo_path = os.getcwd()
repo = git.Repo(repo_path)
for (path, _stage), _entry in repo.index.entries.items():
entries.append(path)
for item in repo.index.diff(None):
changed_files.append(item.a_path)
for item in repo.remotes:
remote_info = dict()
remote_info[item.name] = dict(url=item.url)
repo_remotes.append(remote_info)
repo_facts = dict(
changed_files=changed_files,
entries=entries,
remotes=repo_remotes,
untracked_files=repo.untracked_files,
working_tree_dir=repo.working_tree_dir
)
return repo, repo_facts
示例9: init_submodules
# 需要导入模块: import git [as 别名]
# 或者: from git import Repo [as 别名]
def init_submodules(main, repo_path):
try:
import git
repo = git.Repo(repo_path)
logger.info("tags: %s", repo.tags)
logger.info("tags: %s", sorted(repo.tags, key=lambda t: t.commit.committed_date))
logger.info("initializing submodules for repo %s", repo_path)
# register timeout handler
with utils.time_limit(main.REPO_SUBMODULE_TIMEOUT):
for submodule in repo.submodules:
submodule.update(init=True, recursive=True)
return True
# timed out
except utils.TimeoutException as te:
logger.error("submodules %s", str(te))
return True # skip submodules
except Exception as e:
logger.error("failed to initialize submodules for repo %s: %s. ignoring!", repo_path, str(e))
return True
示例10: install_from_git
# 需要导入模块: import git [as 别名]
# 或者: from git import Repo [as 别名]
def install_from_git(self):
success, error = True, None
if not self.git.get('repo'):
success = False
error = 'Not repo get'
return success, error
print("Install playbook from: {}".format(self.git.get('repo')))
try:
if os.path.isdir(os.path.join(self.role_dir, '.git')):
repo = git.Repo(self.role_dir)
remote = repo.remote()
remote.pull()
else:
git.Repo.clone_from(
self.git['repo'], self.role_dir,
branch=self.git.get('branch'), depth=1,
)
except Exception as e:
success = False
error = e
return success, error
示例11: install_from_git
# 需要导入模块: import git [as 别名]
# 或者: from git import Repo [as 别名]
def install_from_git(self):
success, error = True, None
if not self.git.get('repo'):
success, error = False, 'Not repo get'
return success, error
try:
if os.path.isdir(os.path.join(self.playbook_dir(), '.git')):
if self.update_policy == self.UPDATE_POLICY_ALWAYS:
print("Update playbook from: {}".format(self.git.get('repo')))
repo = git.Repo(self.playbook_dir())
remote = repo.remote()
remote.pull()
else:
print("Install playbook from: {}".format(self.git.get('repo')))
git.Repo.clone_from(
self.git['repo'], self.playbook_dir(),
branch=self.git.get('branch'), depth=1,
)
except Exception as e:
success, error = False, e
return success, error
示例12: __init__
# 需要导入模块: import git [as 别名]
# 或者: from git import Repo [as 别名]
def __init__(self, folder: str=".",
dry_run=False,
home='bioconda/bioconda-recipes',
fork=None,
allow_dirty=True,
depth=1) -> None:
if os.path.exists(folder):
repo = git.Repo(folder, search_parent_directories=True)
else:
try:
os.mkdir(folder)
logger.error("cloning %s into %s", home, folder)
repo = git.Repo.clone_from(home, folder, depth=depth)
except git.GitCommandError:
os.rmdir(folder)
raise
super().__init__(repo, dry_run, home, fork, allow_dirty)
#: Branch to restore after running
self.prev_active_branch = self.repo.active_branch
示例13: __init__
# 需要导入模块: import git [as 别名]
# 或者: from git import Repo [as 别名]
def __init__(self, config):
"""
Instantiate a new Git Archiver.
:param config: The wily configuration
:type config: :class:`wily.config.WilyConfig`
"""
try:
self.repo = Repo(config.path)
except git.exc.InvalidGitRepositoryError as e:
raise InvalidGitRepositoryError from e
self.config = config
if self.repo.head.is_detached:
self.current_branch = self.repo.head.object.hexsha
else:
self.current_branch = self.repo.active_branch
assert not self.repo.bare, "Not a Git repository"
示例14: test_rank_directory_default_unindexed_revision
# 需要导入模块: import git [as 别名]
# 或者: from git import Repo [as 别名]
def test_rank_directory_default_unindexed_revision(builddir):
""" Test the rank feature with an unindexed revision. """
repo = Repo(builddir)
with open(builddir / "test.py", "w") as test_txt:
test_txt.write("import abc")
index = repo.index
index.add([str(builddir / "test.py")])
author = Actor("An author", "author@example.com")
committer = Actor("A committer", "committer@example.com")
commit = index.commit(
"unindexed commit",
author=author,
committer=committer,
author_date="Thu, 28 Apr 2019 22:13:13 +0200",
commit_date="Thu, 28 Apr 2019 22:13:13 +0200",
)
runner = CliRunner()
result = runner.invoke(main.cli, ["--path", builddir, "rank", "-r", commit.hexsha])
assert result.exit_code == 1, result.stdout
示例15: _find_git_info
# 需要导入模块: import git [as 别名]
# 或者: from git import Repo [as 别名]
def _find_git_info(self):
"""
Return information about the state of the Git repository tox is being
run from.
:return: dict with keys 'dirty' (bool), 'sha' (str), 'tag' (str or None)
:rtype: dict
"""
res = {}
logger.debug('Checking git status...')
repo = Repo(path=self._gitdir, search_parent_directories=False)
res['sha'] = repo.head.commit.hexsha
res['dirty'] = repo.is_dirty(untracked_files=True)
res['tag'] = None
for tag in repo.tags:
# each is a git.Tag object
if tag.commit.hexsha == res['sha']:
res['tag'] = tag.name
logger.debug('Git info: %s', res)
return res