本文整理汇总了Python中git.Repo.commit方法的典型用法代码示例。如果您正苦于以下问题:Python Repo.commit方法的具体用法?Python Repo.commit怎么用?Python Repo.commit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类git.Repo
的用法示例。
在下文中一共展示了Repo.commit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: GitUpdater
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import commit [as 别名]
class GitUpdater(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.fallbacks = imp.internal_config['updater']['fallbacks']
self.repo = imp.internal_config['updater']['repo']
self.update_interval = imp.internal_config['updater']['update_interval']
self.local = os.path.dirname(os.path.realpath(__file__))
self.local_repo = Repo(self.local)
def run(self):
no_updates = True
imp.internal_version = "Git Build #{short_sha}".format(short_sha=self.local_repo.commit().hexsha[:7])
print(imp.internal_version)
while no_updates:
for remote in self.local_repo.remotes:
local_commit = self.local_repo.commit()
info = remote.fetch()
remote_commit = info[0].commit
remote_name = info[0].name
if remote_name != self.repo: # Pick repo from settings.
continue
if remote_commit == local_commit : # If an update.
continue
if self.fallbacks:
self.local_repo.git.execute("git checkout -B fallback")
self.local_repo.git.execute("git checkout master")
data = self.local_repo.git.execute("git pull {} {}".format(*self.repo.split('/')))
print(data)
print("We have updated to #{}".format(self.local_repo.commit().hexsha[:7]))
print("Will undergo a cold reload now.")
init.restart(1)
no_updates = False
time.sleep(self.update_interval)
示例2: Git
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import commit [as 别名]
class Git(BaseBackend):
"""
GIT Backend for asset versions.
"""
def __init__(self):
"""
Git backend constructor.
"""
repo_dir = settings.BASE_DIR
if hasattr(settings, 'ASSET_REPO_DIR'):
repo_dir = settings.REPO_DIR
self.repo = Repo(repo_dir)
def version_long(self):
"""
Returns the full hash of the latest commit found.
:return: Latest commit hash (full)
:rtype: str
"""
return self.repo.commit().hexsha
def version_short(self):
"""
Returns the short hash of the latest commit found.
:return: Latest commit hash (short)
:rtype: str
"""
return self.repo.commit().hexsha[:6]
示例3: clone
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import commit [as 别名]
def clone(self, branch=None, to_path=None, commit='HEAD'):
"""
Shallow clone a repository, if branch name is specified it will clone
only that branch
:param branch: string: branch name
:param to_path: string: destination dir
:param commit: string: desired commit sha
:return:
"""
self.ensure_one()
try:
if not branch:
# Create bare repo
_logger.info('Cloning bare repo in: %s.' % self.get_dir())
repo = Repo.clone_from(
self.name, self.get_dir(), bare=True)
git = repo.git
_logger.info('Fetching %s.' % self.name)
git.fetch()
else:
# Get sources from bare repo
repo = Repo(self.get_dir())
git = repo.git
_logger.info('Fetching %s.' % self.name)
git.fetch('origin', '%s:%s' % (branch, branch))
if to_path:
_logger.info('Cloning repo: %s to: %s.' % (
self.name, to_path))
repo = Repo.clone_from(
self.get_dir(), to_path=to_path, branch=branch)
if commit:
repo.commit(commit)
for submodule in repo.submodules:
submodule.update(init=True)
heads = []
tags = []
for ref in repo.references:
if isinstance(ref, (RemoteReference, Head)):
heads.append((ref.name,
ref.path.replace('refs/remotes/origin/',
'refs/heads/')))
elif isinstance(ref, TagReference):
tags.append(ref.name)
self.update_branches(heads=heads)
self.update_tags(tags=tags)
except Exception as e:
_logger.error(e)
raise Warning(
_('An error happened while executing \'git clone\' on '
'this repository. Please check that you have the '
'rights to access it and that it does not already '
'exists in static/repo/ directory.'))
示例4: _get_source_target
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import commit [as 别名]
def _get_source_target(self):
repo = Repo('.')
source = None
target = repo.head.commit
last_build_metrics = self._context.get(
'last_metrics', {}).get('build', None)
if last_build_metrics:
if last_build_metrics['sha'] == target.hexsha and \
'sha_start' in last_build_metrics:
# rerun metrics case
source = repo.commit(last_build_metrics['sha_start'])
else:
# found new commit(s) - get sha from last run and use it as source
source = repo.commit(last_build_metrics['sha'])
return repo, source, target
示例5: Plugin
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import commit [as 别名]
class Plugin(dork_compose.plugin.Plugin):
def __init__(self, env, name):
dork_compose.plugin.Plugin.__init__(self, env, name)
self.__repo = Repo(self.basedir)
def __commit(self, hash):
try:
return self.__repo.commit(hash)
except BadName:
return None
def snapshot_autosave(self):
return self.__repo.head.commit.hexsha
def snapshot_autoload(self, snapshots=()):
name = None
head = self.__repo.head.commit
distance = -1
for commit in filter(lambda x: x, map(self.__commit, snapshots)):
if self.__repo.is_ancestor(commit.hexsha, head.hexsha):
diff = len(commit.diff(head))
if diff < distance or distance == -1:
name = commit.hexsha
distance = diff
return name
def snapshot_autoclean(self, snapshots=()):
snapshots = filter(lambda x: x, map(self.__commit, snapshots))
names = []
for current in snapshots:
for test in snapshots:
if self.__repo.is_ancestor(test, current) and test != current and test.hexsha not in names:
names.append(test.hexsha)
return names
示例6: validate_commit
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import commit [as 别名]
def validate_commit(repo_path, commit):
repo = Repo(repo_path)
# print(repo.git.show(commit.hexsha))
#repo.git.config('--global', 'gpg.program', here('../../gpg-with-fingerprint'))
if isinstance(commit, str):
commit = repo.commit(commit)
cached_validation = cache.get(commit.hexsha)
logger.info('cached_validation: %s', cached_validation)
if cached_validation is not None: # Could be an empty dict, should clean that up
return cached_validation
# Load keys from repo
refresh_gpg_keys(repo_path)
# is it a valid signiture
try:
repo.git.verify_commit(commit.hexsha)
logger.debug('Valid signiture! {}'.format(commit.hexsha))
except Exception as e:
logger.warn(
'Oh noes! Invalid gpg signiture {} Error: {}'.format(commit.hexsha, e))
for p in commit.parents:
logger.info(p.hexsha)
repo.git.checkout(p.hexsha)
validate_input = repo.git.show(
commit.hexsha, c=True, show_signature=True, no_abbrev=True, format='raw')
logger.info(validate_input)
process = subprocess.Popen(['pypy-sandbox',
'--tmp',
repo.working_tree_dir,
'tsampi', 'validate'],
universal_newlines=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
raw_out, raw_err = process.communicate(input=validate_input)
logger.info('=' * 10)
logger.info(validate_input)
logger.info('=' * 10)
logger.info('out: %s', raw_out)
logger.info('err: %s', raw_err)
logger.info('=' * 10)
out = json.loads(raw_out)
# no news is good news
if out:
logger.info('Invalid Commit: %s\t parent: %s', commit, p)
logger.info(out)
return out
logger.info('Valid Commit!, %s', commit)
return_value = {} # TODO: make this somethign useful
cache.set(commit.hexsha, return_value)
return return_value
示例7: install_experiments
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import commit [as 别名]
def install_experiments(experiment_tags=None, repo_type="experiments"):
# We will return list of experiments that did not install successfully
errored_experiments = []
tmpdir = custom_battery_download(repos=[repo_type, "battery"])
# The git commit is saved with the experiment as the "version"
repo = Repo("%s/%s" % (tmpdir, repo_type))
commit = repo.commit("master").__str__()
experiments = get_experiments("%s/%s" % (tmpdir, repo_type), load=True, warning=False)
if experiment_tags != None:
experiments = [e for e in experiments if e[0]["exp_id"] in experiment_tags]
for experiment in experiments:
try:
performance_variable = None
rejection_variable = None
if "experiment_variables" in experiment[0]:
if isinstance(experiment[0]["experiment_variables"], list):
for var in experiment[0]["experiment_variables"]:
if var["type"].lower().strip() == "bonus":
performance_variable = parse_experiment_variable(var)
elif var["type"].lower().strip() == "credit":
rejection_variable = parse_experiment_variable(var)
else:
parse_experiment_variable(var) # adds to database
if isinstance(experiment[0]["reference"], list):
reference = experiment[0]["reference"][0]
else:
reference = experiment[0]["reference"]
cognitive_atlas_task = get_cognitiveatlas_task(experiment[0]["cognitive_atlas_task_id"])
new_experiment, _ = ExperimentTemplate.objects.update_or_create(
exp_id=experiment[0]["exp_id"],
defaults={
"name": experiment[0]["name"],
"cognitive_atlas_task": cognitive_atlas_task,
"publish": bool(experiment[0]["publish"]),
"time": experiment[0]["time"],
"reference": reference,
"version": commit,
"template": experiment[0]["template"],
"performance_variable": performance_variable,
"rejection_variable": rejection_variable,
},
)
new_experiment.save()
experiment_folder = "%s/%s/%s" % (tmpdir, repo_type, experiment[0]["exp_id"])
output_folder = "%s/%s/%s" % (media_dir, repo_type, experiment[0]["exp_id"])
if os.path.exists(output_folder):
shutil.rmtree(output_folder)
copy_directory(experiment_folder, output_folder)
except:
errored_experiments.append(experiment[0]["exp_id"])
shutil.rmtree(tmpdir)
return errored_experiments
示例8: initialize_repo
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import commit [as 别名]
def initialize_repo():
if os.path.exists(registry_path):
repo = Repo(registry_path)
else:
repo = Repo.clone_from(index_url, registry_path)
conn.cursor().execute("insert into update_history values (?, ?)", (str(repo.commit()), datetime.now()))
conn.commit()
return repo
示例9: __init__
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import commit [as 别名]
def __init__(self, datetime=timezone.now()):
git_repo_path = settings.GIT_REPO_PATH
repo = Repo(git_repo_path)
git_main_branch = settings.GIT_MAIN_BRANCH
git_files = []
git_dirs = []
for root, dirs, files in os.walk(git_repo_path):
for git_dir in [d for d in dirs if not d[0] == '.']:
git_dirs.append(os.path.join(root, git_dir))
for git_file in [f for f in files if not f[0] == '.']:
git_files.append(os.path.join(root, git_file))
nb_lines = 0
for git_file in git_files:
with open(git_file) as f:
nb_lines += sum(1 for _ in f)
models.Git.objects.create(
nb_lines=nb_lines,
nb_files=len(git_files),
nb_dirs=len(git_dirs),
nb_commits=repo.commit(git_main_branch).count(),
datetime=datetime
)
for app_name in app_settings.FOLLOWED_APPS:
app_dir_pth = os.path.join(git_repo_path, app_name)
app_directories = [dir_pth for dir_pth in git_dirs
if dir_pth.startswith(app_dir_pth)]
app_files = [file_pth for file_pth in git_files
if file_pth.startswith(app_dir_pth)]
app_nb_lines = 0
for file in app_files:
with open(file) as f:
app_nb_lines += sum(1 for _ in f)
models.Git.objects.create(
nb_lines=app_nb_lines,
nb_files=len(app_files),
nb_dirs=len(app_directories),
nb_commits=repo.commit(git_main_branch).count(app_name),
app_name=app_name,
datetime=datetime)
示例10: find_repo_contains_specified_commit
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import commit [as 别名]
def find_repo_contains_specified_commit(self, url, ref):
for rel_repodir, abs_repodir in self.get_fetched_refs_for_remote(url):
r = Repo(abs_repodir)
try:
return r.commit(ref)
except:
pass
else:
return None
示例11: fetch
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import commit [as 别名]
def fetch(self, url, ref):
d = os.path.join(self.basedir, self.build_path_from_repo_url(url, ref))
if not os.path.exists(d):
c = self.find_repo_contains_specified_commit(url, ref)
if c is not None:
orig_repo = c.repo
for remote_ref in orig_repo.remotes[self.origin_remote_name].refs:
orig_repo.create_head(remote_ref.name[len(self.origin_remote_name) + 1:], remote_ref, force=True)
r = orig_repo.clone(d)
o = r.create_remote(self.origin_remote_name, url=url, force=True)
else:
r = Repo.init(d)
o = r.create_remote(self.origin_remote_name, url=url)
o.fetch(depth=1)
new = True
else:
r = Repo(d)
o = r.remotes[self.origin_remote_name]
new = False
try:
try:
remote_ref = 'remotes/' + self.origin_remote_name + '/' + ref
hexsha = r.commit(remote_ref).hexsha
except gitdb.exc.BadName:
remote_ref = ref
hexsha = r.commit(ref).hexsha
if hexsha != ref:
# symbolic ref
if not new:
o.fetch(depth=1)
hexsha = r.commit(remote_ref).hexsha
raise Symbolic(hexsha)
# d = os.path.join(self.basedir, self.build_path_from_repo_url(url, hexsha))
# if os.path.exists(d):
# r = Repo(d)
# new = False
if new:
r.head.reference = hexsha
r.head.reset(index=True, working_tree=True)
except Exception as e:
if new:
shutil.rmtree(r.working_dir)
raise
return r
示例12: checkoutGitSources
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import commit [as 别名]
def checkoutGitSources(repoUrl, revision):
repoDir = os.path.join(tempfile.gettempdir(), revision)
if os.path.isdir(repoDir):
logger.warn("Found existing git checkout directory: " + str(repoDir))
gitRepo = Repo(repoDir)
else:
gitRepo = Repo.clone_from(repoUrl, repoDir)
gitRepo.head.reference = gitRepo.commit(revision)
gitRepo.head.reset(index=True, working_tree=True)
return gitRepo
示例13: _GitWrapperCommon
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import commit [as 别名]
class _GitWrapperCommon(object):
"""
Wrap git module to provide a more stable interface across versions
"""
def __init__(self, repo_path):
self.git = Git()
self.repo = Repo(os.path.abspath("."))
def is_file_managed_by_git(self, path):
"""
:param path: Path to check
:returns: True if path is managed by git
"""
status, _stdout, _stderr = self.git.execute(
["git", "ls-files", path, "--error-unmatch"], with_extended_output=True, with_exceptions=False
)
return status == 0
def is_file_modified(self, path):
"""
Does a file have local changes not yet committed
:returns: True if file has local changes
"""
status, _stdout, _stderr = self.git.execute(
["git", "diff", "--quiet", "HEAD", path], with_extended_output=True, with_exceptions=False
)
return status != 0
def get_commits_following(self, path):
"""
Get all commits including path following the file through
renames
:param path: Path which we will find commits for
:returns: Sequence of commit objects. Newest to oldest
"""
commit_shas = self.git.log("--pretty=%H", "--follow", "--", path).splitlines()
return [self.repo.commit(shas) for shas in commit_shas]
def get_commits(self, path, follow=False):
"""
Get all commits including path
:param path: Path which we will find commits for
:param bool follow: If True we will follow path through renames
:returns: Sequence of commit objects. Newest to oldest
"""
if follow:
return self.get_commits_following(path)
else:
return self._get_commits(path)
示例14: setUp
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import commit [as 别名]
def setUp(self):
path = settings.BASE_DIR
repo = Repo(path, odbt=GitDB)
self.tag = str(repo.git.describe(tags=True))
try:
self.branch = str(repo.active_branch)
self.commit = str(repo.active_branch.commit)
except TypeError:
self.branch = "detached"
self.commit = str(repo.commit())
self.revision = f"{self.tag}:{self.branch}:{self.commit}"[0:75]
示例15: Checker
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import commit [as 别名]
class Checker(BaseChecker):
'''Git checker.'''
def __init__(self, path, unexpected, ignores=None, checks=None):
super(Checker, self).__init__(ignores, checks)
self.repo = Repo(path)
def pattern(pattern, index):
return Pattern(re.compile(force_text(pattern.pattern)),
force_text(pattern.name or 'P%03d' % (index)),
force_text(pattern.description))
self.unexpected_patterns = [pattern(p, i) for i, p in enumerate(unexpected)]
def check_diffs(self, diffs):
'''Check diffs and print unexpected lines and matched patterns.'''
self.clear_matched_patterns()
for diff in diffs:
if diff.b_blob and self.need_check(diff.b_blob.path):
self.verbose_output('Checking ' + diff.b_blob.path)
self.check_diff(diff.b_blob.path, force_text(diff.diff).split('\n')[2:], DiffLineCounter())
self.print_matched_patterns()
return 1 if self.matched_patterns else 0
def check(self, check_type=CheckTypes.CHECK_TYPE_GIT_DIFF, revisions=None):
'''Check with type and revisions.'''
head = revisions[0] if revisions else None
commit = self.repo.commit(head) if head else self.repo.head.commit
compare_base = commit
against = None
if check_type == CheckTypes.CHECK_TYPE_GIT_DIFF:
# If diff, base is first revision or Index, against is None.
compare_base = commit if head else self.repo.index
elif check_type == CheckTypes.CHECK_TYPE_GIT_STAGED:
# If staged, base is first revision or HEAD, against is Index (staged).
against = Diffable.Index
elif check_type == CheckTypes.CHECK_TYPE_GIT_TREE:
# If tree, base is first revision, against is second revision or None.
against = self.repo.commit(revisions[1]) if len(revisions) > 1 else None
else:
print('Unknown check type: %s' % (check_type))
return 2
diffs = compare_base.diff(against, create_patch=True)
return self.check_diffs(diffs)