mirror of https://github.com/ansible/ansible.git
Update ansible-test support for CI providers.
Refactored CI provider code to simplify multiple provider support and addition of new providers.pull/69525/head
parent
ca6da5ad63
commit
d8e0aadc0d
@ -0,0 +1,2 @@
|
||||
minor_changes:
|
||||
- ansible-test - Refactored CI related logic into a basic provider abstraction.
|
@ -1,177 +0,0 @@
|
||||
"""Detect changes in Ansible code."""
|
||||
from __future__ import (absolute_import, division, print_function)
|
||||
__metaclass__ = type
|
||||
|
||||
import re
|
||||
import os
|
||||
|
||||
from .util import (
|
||||
ApplicationError,
|
||||
SubprocessError,
|
||||
MissingEnvironmentVariable,
|
||||
display,
|
||||
)
|
||||
|
||||
from .util_common import (
|
||||
CommonConfig,
|
||||
)
|
||||
|
||||
from .http import (
|
||||
HttpClient,
|
||||
urlencode,
|
||||
)
|
||||
|
||||
from .git import (
|
||||
Git,
|
||||
)
|
||||
|
||||
|
||||
class InvalidBranch(ApplicationError):
|
||||
"""Exception for invalid branch specification."""
|
||||
def __init__(self, branch, reason):
|
||||
"""
|
||||
:type branch: str
|
||||
:type reason: str
|
||||
"""
|
||||
message = 'Invalid branch: %s\n%s' % (branch, reason)
|
||||
|
||||
super(InvalidBranch, self).__init__(message)
|
||||
|
||||
self.branch = branch
|
||||
|
||||
|
||||
class ChangeDetectionNotSupported(ApplicationError):
|
||||
"""Exception for cases where change detection is not supported."""
|
||||
|
||||
|
||||
class ShippableChanges:
|
||||
"""Change information for Shippable build."""
|
||||
def __init__(self, args, git):
|
||||
"""
|
||||
:type args: CommonConfig
|
||||
:type git: Git
|
||||
"""
|
||||
self.args = args
|
||||
|
||||
try:
|
||||
self.branch = os.environ['BRANCH']
|
||||
self.is_pr = os.environ['IS_PULL_REQUEST'] == 'true'
|
||||
self.is_tag = os.environ['IS_GIT_TAG'] == 'true'
|
||||
self.commit = os.environ['COMMIT']
|
||||
self.project_id = os.environ['PROJECT_ID']
|
||||
self.commit_range = os.environ['SHIPPABLE_COMMIT_RANGE']
|
||||
except KeyError as ex:
|
||||
raise MissingEnvironmentVariable(name=ex.args[0])
|
||||
|
||||
if self.is_tag:
|
||||
raise ChangeDetectionNotSupported('Change detection is not supported for tags.')
|
||||
|
||||
if self.is_pr:
|
||||
self.paths = sorted(git.get_diff_names([self.commit_range]))
|
||||
self.diff = git.get_diff([self.commit_range])
|
||||
else:
|
||||
merge_runs = self.get_merge_runs(self.project_id, self.branch)
|
||||
last_successful_commit = self.get_last_successful_commit(git, merge_runs)
|
||||
|
||||
if last_successful_commit:
|
||||
self.paths = sorted(git.get_diff_names([last_successful_commit, self.commit]))
|
||||
self.diff = git.get_diff([last_successful_commit, self.commit])
|
||||
else:
|
||||
# first run for branch
|
||||
self.paths = None # act as though change detection not enabled, do not filter targets
|
||||
self.diff = []
|
||||
|
||||
def get_merge_runs(self, project_id, branch):
|
||||
"""
|
||||
:type project_id: str
|
||||
:type branch: str
|
||||
:rtype: list[dict]
|
||||
"""
|
||||
params = dict(
|
||||
isPullRequest='false',
|
||||
projectIds=project_id,
|
||||
branch=branch,
|
||||
)
|
||||
|
||||
client = HttpClient(self.args, always=True)
|
||||
response = client.get('https://api.shippable.com/runs?%s' % urlencode(params))
|
||||
return response.json()
|
||||
|
||||
@staticmethod
|
||||
def get_last_successful_commit(git, merge_runs):
|
||||
"""
|
||||
:type git: Git
|
||||
:type merge_runs: dict | list[dict]
|
||||
:rtype: str
|
||||
"""
|
||||
if 'id' in merge_runs and merge_runs['id'] == 4004:
|
||||
display.warning('Unable to find project. Cannot determine changes. All tests will be executed.')
|
||||
return None
|
||||
|
||||
successful_commits = set(run['commitSha'] for run in merge_runs if run['statusCode'] == 30)
|
||||
commit_history = git.get_rev_list(max_count=100)
|
||||
ordered_successful_commits = [commit for commit in commit_history if commit in successful_commits]
|
||||
last_successful_commit = ordered_successful_commits[0] if ordered_successful_commits else None
|
||||
|
||||
if last_successful_commit is None:
|
||||
display.warning('No successful commit found. All tests will be executed.')
|
||||
|
||||
return last_successful_commit
|
||||
|
||||
|
||||
class LocalChanges:
|
||||
"""Change information for local work."""
|
||||
def __init__(self, args, git):
|
||||
"""
|
||||
:type args: CommonConfig
|
||||
:type git: Git
|
||||
"""
|
||||
self.args = args
|
||||
self.current_branch = git.get_branch()
|
||||
|
||||
if self.is_official_branch(self.current_branch):
|
||||
raise InvalidBranch(branch=self.current_branch,
|
||||
reason='Current branch is not a feature branch.')
|
||||
|
||||
self.fork_branch = None
|
||||
self.fork_point = None
|
||||
|
||||
self.local_branches = sorted(git.get_branches())
|
||||
self.official_branches = sorted([b for b in self.local_branches if self.is_official_branch(b)])
|
||||
|
||||
for self.fork_branch in self.official_branches:
|
||||
try:
|
||||
self.fork_point = git.get_branch_fork_point(self.fork_branch)
|
||||
break
|
||||
except SubprocessError:
|
||||
pass
|
||||
|
||||
if self.fork_point is None:
|
||||
raise ApplicationError('Unable to auto-detect fork branch and fork point.')
|
||||
|
||||
# tracked files (including unchanged)
|
||||
self.tracked = sorted(git.get_file_names(['--cached']))
|
||||
# untracked files (except ignored)
|
||||
self.untracked = sorted(git.get_file_names(['--others', '--exclude-standard']))
|
||||
# tracked changes (including deletions) committed since the branch was forked
|
||||
self.committed = sorted(git.get_diff_names([self.fork_point, 'HEAD']))
|
||||
# tracked changes (including deletions) which are staged
|
||||
self.staged = sorted(git.get_diff_names(['--cached']))
|
||||
# tracked changes (including deletions) which are not staged
|
||||
self.unstaged = sorted(git.get_diff_names([]))
|
||||
# diff of all tracked files from fork point to working copy
|
||||
self.diff = git.get_diff([self.fork_point])
|
||||
|
||||
@staticmethod
|
||||
def is_official_branch(name):
|
||||
"""
|
||||
:type name: str
|
||||
:rtype: bool
|
||||
"""
|
||||
if name == 'devel':
|
||||
return True
|
||||
|
||||
if re.match(r'^stable-[0-9]+\.[0-9]+$', name):
|
||||
return True
|
||||
|
||||
return False
|
@ -0,0 +1,101 @@
|
||||
"""Support code for CI environments."""
|
||||
from __future__ import (absolute_import, division, print_function)
|
||||
__metaclass__ = type
|
||||
|
||||
import abc
|
||||
|
||||
|
||||
from .. import types as t
|
||||
|
||||
from ..config import (
|
||||
CommonConfig,
|
||||
TestConfig,
|
||||
)
|
||||
|
||||
from ..util import (
|
||||
ABC,
|
||||
ApplicationError,
|
||||
display,
|
||||
get_subclasses,
|
||||
import_plugins,
|
||||
)
|
||||
|
||||
|
||||
class ChangeDetectionNotSupported(ApplicationError):
|
||||
"""Exception for cases where change detection is not supported."""
|
||||
|
||||
|
||||
class AuthContext:
|
||||
"""Context information required for Ansible Core CI authentication."""
|
||||
def __init__(self): # type: () -> None
|
||||
self.region = None # type: t.Optional[str]
|
||||
|
||||
|
||||
class CIProvider(ABC):
|
||||
"""Base class for CI provider plugins."""
|
||||
priority = 500
|
||||
|
||||
@staticmethod
|
||||
@abc.abstractmethod
|
||||
def is_supported(): # type: () -> bool
|
||||
"""Return True if this provider is supported in the current running environment."""
|
||||
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def code(self): # type: () -> str
|
||||
"""Return a unique code representing this provider."""
|
||||
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def name(self): # type: () -> str
|
||||
"""Return descriptive name for this provider."""
|
||||
|
||||
@abc.abstractmethod
|
||||
def generate_resource_prefix(self): # type: () -> str
|
||||
"""Return a resource prefix specific to this CI provider."""
|
||||
|
||||
@abc.abstractmethod
|
||||
def get_base_branch(self): # type: () -> str
|
||||
"""Return the base branch or an empty string."""
|
||||
|
||||
@abc.abstractmethod
|
||||
def detect_changes(self, args): # type: (TestConfig) -> t.Optional[t.List[str]]
|
||||
"""Initialize change detection."""
|
||||
|
||||
@abc.abstractmethod
|
||||
def supports_core_ci_auth(self, context): # type: (AuthContext) -> bool
|
||||
"""Return True if Ansible Core CI is supported."""
|
||||
|
||||
@abc.abstractmethod
|
||||
def prepare_core_ci_auth(self, context): # type: (AuthContext) -> t.Dict[str, t.Any]
|
||||
"""Return authentication details for Ansible Core CI."""
|
||||
|
||||
@abc.abstractmethod
|
||||
def get_git_details(self, args): # type: (CommonConfig) -> t.Optional[t.Dict[str, t.Any]]
|
||||
"""Return details about git in the current environment."""
|
||||
|
||||
|
||||
def get_ci_provider(): # type: () -> CIProvider
|
||||
"""Return a CI provider instance for the current environment."""
|
||||
try:
|
||||
return get_ci_provider.provider
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
provider = None
|
||||
|
||||
import_plugins('ci')
|
||||
|
||||
candidates = sorted(get_subclasses(CIProvider), key=lambda c: (c.priority, c.__name__))
|
||||
|
||||
for candidate in candidates:
|
||||
if candidate.is_supported():
|
||||
provider = candidate()
|
||||
break
|
||||
|
||||
if provider.code:
|
||||
display.info('Detected CI provider: %s' % provider.name)
|
||||
|
||||
get_ci_provider.provider = provider
|
||||
|
||||
return provider
|
@ -0,0 +1,215 @@
|
||||
"""Support code for working without a supported CI provider."""
|
||||
from __future__ import (absolute_import, division, print_function)
|
||||
__metaclass__ = type
|
||||
|
||||
import os
|
||||
import platform
|
||||
import random
|
||||
import re
|
||||
|
||||
from .. import types as t
|
||||
|
||||
from ..config import (
|
||||
CommonConfig,
|
||||
TestConfig,
|
||||
)
|
||||
|
||||
from ..io import (
|
||||
read_text_file,
|
||||
)
|
||||
|
||||
from ..git import (
|
||||
Git,
|
||||
)
|
||||
|
||||
from ..util import (
|
||||
ApplicationError,
|
||||
display,
|
||||
is_binary_file,
|
||||
SubprocessError,
|
||||
)
|
||||
|
||||
from . import (
|
||||
AuthContext,
|
||||
CIProvider,
|
||||
)
|
||||
|
||||
CODE = '' # not really a CI provider, so use an empty string for the code
|
||||
|
||||
|
||||
class Local(CIProvider):
|
||||
"""CI provider implementation when not using CI."""
|
||||
priority = 1000
|
||||
|
||||
@staticmethod
|
||||
def is_supported(): # type: () -> bool
|
||||
"""Return True if this provider is supported in the current running environment."""
|
||||
return True
|
||||
|
||||
@property
|
||||
def code(self): # type: () -> str
|
||||
"""Return a unique code representing this provider."""
|
||||
return CODE
|
||||
|
||||
@property
|
||||
def name(self): # type: () -> str
|
||||
"""Return descriptive name for this provider."""
|
||||
return 'Local'
|
||||
|
||||
def generate_resource_prefix(self): # type: () -> str
|
||||
"""Return a resource prefix specific to this CI provider."""
|
||||
node = re.sub(r'[^a-zA-Z0-9]+', '-', platform.node().split('.')[0]).lower()
|
||||
|
||||
prefix = 'ansible-test-%s-%d' % (node, random.randint(10000000, 99999999))
|
||||
|
||||
return prefix
|
||||
|
||||
def get_base_branch(self): # type: () -> str
|
||||
"""Return the base branch or an empty string."""
|
||||
return ''
|
||||
|
||||
def detect_changes(self, args): # type: (TestConfig) -> t.Optional[t.List[str]]
|
||||
"""Initialize change detection."""
|
||||
result = LocalChanges(args)
|
||||
|
||||
display.info('Detected branch %s forked from %s at commit %s' % (
|
||||
result.current_branch, result.fork_branch, result.fork_point))
|
||||
|
||||
if result.untracked and not args.untracked:
|
||||
display.warning('Ignored %s untracked file(s). Use --untracked to include them.' %
|
||||
len(result.untracked))
|
||||
|
||||
if result.committed and not args.committed:
|
||||
display.warning('Ignored %s committed change(s). Omit --ignore-committed to include them.' %
|
||||
len(result.committed))
|
||||
|
||||
if result.staged and not args.staged:
|
||||
display.warning('Ignored %s staged change(s). Omit --ignore-staged to include them.' %
|
||||
len(result.staged))
|
||||
|
||||
if result.unstaged and not args.unstaged:
|
||||
display.warning('Ignored %s unstaged change(s). Omit --ignore-unstaged to include them.' %
|
||||
len(result.unstaged))
|
||||
|
||||
names = set()
|
||||
|
||||
if args.tracked:
|
||||
names |= set(result.tracked)
|
||||
if args.untracked:
|
||||
names |= set(result.untracked)
|
||||
if args.committed:
|
||||
names |= set(result.committed)
|
||||
if args.staged:
|
||||
names |= set(result.staged)
|
||||
if args.unstaged:
|
||||
names |= set(result.unstaged)
|
||||
|
||||
if not args.metadata.changes:
|
||||
args.metadata.populate_changes(result.diff)
|
||||
|
||||
for path in result.untracked:
|
||||
if is_binary_file(path):
|
||||
args.metadata.changes[path] = ((0, 0),)
|
||||
continue
|
||||
|
||||
line_count = len(read_text_file(path).splitlines())
|
||||
|
||||
args.metadata.changes[path] = ((1, line_count),)
|
||||
|
||||
return sorted(names)
|
||||
|
||||
def supports_core_ci_auth(self, context): # type: (AuthContext) -> bool
|
||||
"""Return True if Ansible Core CI is supported."""
|
||||
path = self._get_aci_key_path(context)
|
||||
return os.path.exists(path)
|
||||
|
||||
def prepare_core_ci_auth(self, context): # type: (AuthContext) -> t.Dict[str, t.Any]
|
||||
"""Return authentication details for Ansible Core CI."""
|
||||
path = self._get_aci_key_path(context)
|
||||
auth_key = read_text_file(path).strip()
|
||||
|
||||
request = dict(
|
||||
key=auth_key,
|
||||
nonce=None,
|
||||
)
|
||||
|
||||
auth = dict(
|
||||
remote=request,
|
||||
)
|
||||
|
||||
return auth
|
||||
|
||||
def get_git_details(self, args): # type: (CommonConfig) -> t.Optional[t.Dict[str, t.Any]]
|
||||
"""Return details about git in the current environment."""
|
||||
return None # not yet implemented for local
|
||||
|
||||
def _get_aci_key_path(self, context): # type: (AuthContext) -> str
|
||||
path = os.path.expanduser('~/.ansible-core-ci.key')
|
||||
|
||||
if context.region:
|
||||
path += '.%s' % context.region
|
||||
|
||||
return path
|
||||
|
||||
|
||||
class InvalidBranch(ApplicationError):
|
||||
"""Exception for invalid branch specification."""
|
||||
def __init__(self, branch, reason): # type: (str, str) -> None
|
||||
message = 'Invalid branch: %s\n%s' % (branch, reason)
|
||||
|
||||
super(InvalidBranch, self).__init__(message)
|
||||
|
||||
self.branch = branch
|
||||
|
||||
|
||||
class LocalChanges:
|
||||
"""Change information for local work."""
|
||||
def __init__(self, args): # type: (CommonConfig) -> None
|
||||
self.args = args
|
||||
self.git = Git()
|
||||
|
||||
self.current_branch = self.git.get_branch()
|
||||
|
||||
if self.is_official_branch(self.current_branch):
|
||||
raise InvalidBranch(branch=self.current_branch,
|
||||
reason='Current branch is not a feature branch.')
|
||||
|
||||
self.fork_branch = None
|
||||
self.fork_point = None
|
||||
|
||||
self.local_branches = sorted(self.git.get_branches())
|
||||
self.official_branches = sorted([b for b in self.local_branches if self.is_official_branch(b)])
|
||||
|
||||
for self.fork_branch in self.official_branches:
|
||||
try:
|
||||
self.fork_point = self.git.get_branch_fork_point(self.fork_branch)
|
||||
break
|
||||
except SubprocessError:
|
||||
pass
|
||||
|
||||
if self.fork_point is None:
|
||||
raise ApplicationError('Unable to auto-detect fork branch and fork point.')
|
||||
|
||||
# tracked files (including unchanged)
|
||||
self.tracked = sorted(self.git.get_file_names(['--cached']))
|
||||
# untracked files (except ignored)
|
||||
self.untracked = sorted(self.git.get_file_names(['--others', '--exclude-standard']))
|
||||
# tracked changes (including deletions) committed since the branch was forked
|
||||
self.committed = sorted(self.git.get_diff_names([self.fork_point, 'HEAD']))
|
||||
# tracked changes (including deletions) which are staged
|
||||
self.staged = sorted(self.git.get_diff_names(['--cached']))
|
||||
# tracked changes (including deletions) which are not staged
|
||||
self.unstaged = sorted(self.git.get_diff_names([]))
|
||||
# diff of all tracked files from fork point to working copy
|
||||
self.diff = self.git.get_diff([self.fork_point])
|
||||
|
||||
@staticmethod
|
||||
def is_official_branch(name): # type: (str) -> bool
|
||||
"""Return True if the given branch name an official branch for development or releases."""
|
||||
if name == 'devel':
|
||||
return True
|
||||
|
||||
if re.match(r'^stable-[0-9]+\.[0-9]+$', name):
|
||||
return True
|
||||
|
||||
return False
|
@ -0,0 +1,249 @@
|
||||
"""Support code for working with Shippable."""
|
||||
from __future__ import (absolute_import, division, print_function)
|
||||
__metaclass__ = type
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
from .. import types as t
|
||||
|
||||
from ..config import (
|
||||
CommonConfig,
|
||||
TestConfig,
|
||||
)
|
||||
|
||||
from ..git import (
|
||||
Git,
|
||||
)
|
||||
|
||||
from ..http import (
|
||||
HttpClient,
|
||||
urlencode,
|
||||
)
|
||||
|
||||
from ..util import (
|
||||
ApplicationError,
|
||||
display,
|
||||
MissingEnvironmentVariable,
|
||||
SubprocessError,
|
||||
)
|
||||
|
||||
from . import (
|
||||
AuthContext,
|
||||
ChangeDetectionNotSupported,
|
||||
CIProvider,
|
||||
)
|
||||
|
||||
|
||||
CODE = 'shippable'
|
||||
|
||||
|
||||
class Shippable(CIProvider):
|
||||
"""CI provider implementation for Shippable."""
|
||||
@staticmethod
|
||||
def is_supported(): # type: () -> bool
|
||||
"""Return True if this provider is supported in the current running environment."""
|
||||
return os.environ.get('SHIPPABLE') == 'true'
|
||||
|
||||
@property
|
||||
def code(self): # type: () -> str
|
||||
"""Return a unique code representing this provider."""
|
||||
return CODE
|
||||
|
||||
@property
|
||||
def name(self): # type: () -> str
|
||||
"""Return descriptive name for this provider."""
|
||||
return 'Shippable'
|
||||
|
||||
def generate_resource_prefix(self): # type: () -> str
|
||||
"""Return a resource prefix specific to this CI provider."""
|
||||
try:
|
||||
prefix = 'shippable-%s-%s' % (
|
||||
os.environ['SHIPPABLE_BUILD_NUMBER'],
|
||||
os.environ['SHIPPABLE_JOB_NUMBER'],
|
||||
)
|
||||
except KeyError as ex:
|
||||
raise MissingEnvironmentVariable(name=ex.args[0])
|
||||
|
||||
return prefix
|
||||
|
||||
def get_base_branch(self): # type: () -> str
|
||||
"""Return the base branch or an empty string."""
|
||||
base_branch = os.environ.get('BASE_BRANCH')
|
||||
|
||||
if base_branch:
|
||||
base_branch = 'origin/%s' % base_branch
|
||||
|
||||
return base_branch or ''
|
||||
|
||||
def detect_changes(self, args): # type: (TestConfig) -> t.Optional[t.List[str]]
|
||||
"""Initialize change detection."""
|
||||
result = ShippableChanges(args)
|
||||
|
||||
if result.is_pr:
|
||||
job_type = 'pull request'
|
||||
elif result.is_tag:
|
||||
job_type = 'tag'
|
||||
else:
|
||||
job_type = 'merge commit'
|
||||
|
||||
display.info('Processing %s for branch %s commit %s' % (job_type, result.branch, result.commit))
|
||||
|
||||
if not args.metadata.changes:
|
||||
args.metadata.populate_changes(result.diff)
|
||||
|
||||
if result.paths is None:
|
||||
# There are several likely causes of this:
|
||||
# - First run on a new branch.
|
||||
# - Too many pull requests passed since the last merge run passed.
|
||||
display.warning('No successful commit found. All tests will be executed.')
|
||||
|
||||
return result.paths
|
||||
|
||||
def supports_core_ci_auth(self, context): # type: (AuthContext) -> bool
|
||||
"""Return True if Ansible Core CI is supported."""
|
||||
return True
|
||||
|
||||
def prepare_core_ci_auth(self, context): # type: (AuthContext) -> t.Dict[str, t.Any]
|
||||
"""Return authentication details for Ansible Core CI."""
|
||||
try:
|
||||
request = dict(
|
||||
run_id=os.environ['SHIPPABLE_BUILD_ID'],
|
||||
job_number=int(os.environ['SHIPPABLE_JOB_NUMBER']),
|
||||
)
|
||||
except KeyError as ex:
|
||||
raise MissingEnvironmentVariable(name=ex.args[0])
|
||||
|
||||
auth = dict(
|
||||
shippable=request,
|
||||
)
|
||||
|
||||
return auth
|
||||
|
||||
def get_git_details(self, args): # type: (CommonConfig) -> t.Optional[t.Dict[str, t.Any]]
|
||||
"""Return details about git in the current environment."""
|
||||
commit = os.environ.get('COMMIT')
|
||||
base_commit = os.environ.get('BASE_COMMIT')
|
||||
|
||||
details = dict(
|
||||
base_commit=base_commit,
|
||||
commit=commit,
|
||||
merged_commit=self._get_merged_commit(args, commit),
|
||||
)
|
||||
|
||||
return details
|
||||
|
||||
# noinspection PyUnusedLocal
|
||||
def _get_merged_commit(self, args, commit): # type: (CommonConfig, str) -> t.Optional[str] # pylint: disable=unused-argument
|
||||
"""Find the merged commit that should be present."""
|
||||
if not commit:
|
||||
return None
|
||||
|
||||
git = Git()
|
||||
|
||||
try:
|
||||
show_commit = git.run_git(['show', '--no-patch', '--no-abbrev', commit])
|
||||
except SubprocessError as ex:
|
||||
# This should only fail for pull requests where the commit does not exist.
|
||||
# Merge runs would fail much earlier when attempting to checkout the commit.
|
||||
raise ApplicationError('Commit %s was not found:\n\n%s\n\n'
|
||||
'GitHub may not have fully replicated the commit across their infrastructure.\n'
|
||||
'It is also possible the commit was removed by a force push between job creation and execution.\n'
|
||||
'Find the latest run for the pull request and restart failed jobs as needed.'
|
||||
% (commit, ex.stderr.strip()))
|
||||
|
||||
head_commit = git.run_git(['show', '--no-patch', '--no-abbrev', 'HEAD'])
|
||||
|
||||
if show_commit == head_commit:
|
||||
# Commit is HEAD, so this is not a pull request or the base branch for the pull request is up-to-date.
|
||||
return None
|
||||
|
||||
match_merge = re.search(r'^Merge: (?P<parents>[0-9a-f]{40} [0-9a-f]{40})$', head_commit, flags=re.MULTILINE)
|
||||
|
||||
if not match_merge:
|
||||
# The most likely scenarios resulting in a failure here are:
|
||||
# A new run should or does supersede this job, but it wasn't cancelled in time.
|
||||
# A job was superseded and then later restarted.
|
||||
raise ApplicationError('HEAD is not commit %s or a merge commit:\n\n%s\n\n'
|
||||
'This job has likely been superseded by another run due to additional commits being pushed.\n'
|
||||
'Find the latest run for the pull request and restart failed jobs as needed.'
|
||||
% (commit, head_commit.strip()))
|
||||
|
||||
parents = set(match_merge.group('parents').split(' '))
|
||||
|
||||
if len(parents) != 2:
|
||||
raise ApplicationError('HEAD is a %d-way octopus merge.' % len(parents))
|
||||
|
||||
if commit not in parents:
|
||||
raise ApplicationError('Commit %s is not a parent of HEAD.' % commit)
|
||||
|
||||
parents.remove(commit)
|
||||
|
||||
last_commit = parents.pop()
|
||||
|
||||
return last_commit
|
||||
|
||||
|
||||
class ShippableChanges:
|
||||
"""Change information for Shippable build."""
|
||||
def __init__(self, args): # type: (CommonConfig) -> None
|
||||
self.args = args
|
||||
self.git = Git()
|
||||
|
||||
try:
|
||||
self.branch = os.environ['BRANCH']
|
||||
self.is_pr = os.environ['IS_PULL_REQUEST'] == 'true'
|
||||
self.is_tag = os.environ['IS_GIT_TAG'] == 'true'
|
||||
self.commit = os.environ['COMMIT']
|
||||
self.project_id = os.environ['PROJECT_ID']
|
||||
self.commit_range = os.environ['SHIPPABLE_COMMIT_RANGE']
|
||||
except KeyError as ex:
|
||||
raise MissingEnvironmentVariable(name=ex.args[0])
|
||||
|
||||
if self.is_tag:
|
||||
raise ChangeDetectionNotSupported('Change detection is not supported for tags.')
|
||||
|
||||
if self.is_pr:
|
||||
self.paths = sorted(self.git.get_diff_names([self.commit_range]))
|
||||
self.diff = self.git.get_diff([self.commit_range])
|
||||
else:
|
||||
commits = self.get_successful_merge_run_commits(self.project_id, self.branch)
|
||||
last_successful_commit = self.get_last_successful_commit(commits)
|
||||
|
||||
if last_successful_commit:
|
||||
self.paths = sorted(self.git.get_diff_names([last_successful_commit, self.commit]))
|
||||
self.diff = self.git.get_diff([last_successful_commit, self.commit])
|
||||
else:
|
||||
# first run for branch
|
||||
self.paths = None # act as though change detection not enabled, do not filter targets
|
||||
self.diff = []
|
||||
|
||||
def get_successful_merge_run_commits(self, project_id, branch): # type: (str, str) -> t.Set[str]
|
||||
"""Return a set of recent successsful merge commits from Shippable for the given project and branch."""
|
||||
parameters = dict(
|
||||
isPullRequest='false',
|
||||
projectIds=project_id,
|
||||
branch=branch,
|
||||
)
|
||||
|
||||
url = 'https://api.shippable.com/runs?%s' % urlencode(parameters)
|
||||
|
||||
http = HttpClient(self.args, always=True)
|
||||
response = http.get(url)
|
||||
result = response.json()
|
||||
|
||||
if 'id' in result and result['id'] == 4004:
|
||||
# most likely due to a private project, which returns an HTTP 200 response with JSON
|
||||
display.warning('Unable to find project. Cannot determine changes. All tests will be executed.')
|
||||
return set()
|
||||
|
||||
commits = set(run['commitSha'] for run in result if run['statusCode'] == 30)
|
||||
|
||||
return commits
|
||||
|
||||
def get_last_successful_commit(self, successful_commits): # type: (t.Set[str]) -> t.Optional[str]
|
||||
"""Return the last successful commit from git history that is found in the given commit list, or None."""
|
||||
commit_history = self.git.get_rev_list(max_count=100)
|
||||
ordered_successful_commits = [commit for commit in commit_history if commit in successful_commits]
|
||||
last_successful_commit = ordered_successful_commits[0] if ordered_successful_commits else None
|
||||
return last_successful_commit
|
Loading…
Reference in New Issue