2016-05-11 13:19:06 +00:00
|
|
|
#
|
|
|
|
# Copyright (C) 2016 Intel Corporation
|
|
|
|
#
|
|
|
|
# Released under the MIT license (see COPYING.MIT)
|
|
|
|
#
|
|
|
|
"""Git repository interactions"""
|
2016-08-15 10:56:58 +00:00
|
|
|
import os
|
|
|
|
|
2016-05-11 13:19:06 +00:00
|
|
|
from oeqa.utils.commands import runCmd
|
|
|
|
|
|
|
|
|
|
|
|
class GitError(Exception):
|
|
|
|
"""Git error handling"""
|
|
|
|
pass
|
|
|
|
|
|
|
|
class GitRepo(object):
|
|
|
|
"""Class representing a Git repository clone"""
|
2016-08-15 10:56:58 +00:00
|
|
|
def __init__(self, path, is_topdir=False):
|
2016-05-11 13:19:06 +00:00
|
|
|
self.top_dir = self._run_git_cmd_at(['rev-parse', '--show-toplevel'],
|
2016-08-15 10:56:58 +00:00
|
|
|
path)
|
|
|
|
realpath = os.path.realpath(path)
|
|
|
|
if is_topdir and realpath != self.top_dir:
|
|
|
|
raise GitError("{} is not a Git top directory".format(realpath))
|
2016-05-11 13:19:06 +00:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _run_git_cmd_at(git_args, cwd, **kwargs):
|
|
|
|
"""Run git command at a specified directory"""
|
|
|
|
git_cmd = 'git ' if isinstance(git_args, str) else ['git']
|
|
|
|
git_cmd += git_args
|
|
|
|
ret = runCmd(git_cmd, ignore_status=True, cwd=cwd, **kwargs)
|
|
|
|
if ret.status:
|
|
|
|
cmd_str = git_cmd if isinstance(git_cmd, str) \
|
|
|
|
else ' '.join(git_cmd)
|
|
|
|
raise GitError("'{}' failed with exit code {}: {}".format(
|
|
|
|
cmd_str, ret.status, ret.output))
|
|
|
|
return ret.output.strip()
|
|
|
|
|
2016-05-13 13:34:04 +00:00
|
|
|
def run_cmd(self, git_args, env_update=None):
|
2016-05-11 13:19:06 +00:00
|
|
|
"""Run Git command"""
|
2016-05-13 13:34:04 +00:00
|
|
|
env = None
|
|
|
|
if env_update:
|
|
|
|
env = os.environ.copy()
|
|
|
|
env.update(env_update)
|
|
|
|
return self._run_git_cmd_at(git_args, self.top_dir, env=env)
|
2016-05-11 13:19:06 +00:00
|
|
|
|
2016-05-16 11:23:43 +00:00
|
|
|
def rev_parse(self, revision):
|
|
|
|
"""Do git rev-parse"""
|
|
|
|
try:
|
|
|
|
return self.run_cmd(['rev-parse', revision])
|
|
|
|
except GitError:
|
|
|
|
# Revision does not exist
|
|
|
|
return None
|
2016-05-11 13:19:06 +00:00
|
|
|
|
2016-05-16 11:36:27 +00:00
|
|
|
def get_current_branch(self):
|
|
|
|
"""Get current branch"""
|
|
|
|
try:
|
|
|
|
# Strip 11 chars, i.e. 'refs/heads' from the beginning
|
|
|
|
return self.run_cmd(['symbolic-ref', 'HEAD'])[11:]
|
|
|
|
except GitError:
|
|
|
|
return None
|
|
|
|
|
2016-05-11 13:19:06 +00:00
|
|
|
|