Script for running as part of "preflight" checks on a CI system.
It should allow you to cancel build if it is only documentation, etc.
Script for running as part of "preflight" checks on a CI system.
It should allow you to cancel build if it is only documentation, etc.
| #!/usr/bin/env python3 | |
| import os | |
| import sys | |
| def ci_property(name): | |
| exec(""" | |
| @property | |
| def p(self): | |
| value = self.env.get(self._{name}, None) | |
| assert value is not None | |
| return value | |
| """.format(name=name)) | |
| return locals()['p'] | |
| class CI: | |
| """ | |
| >>> env1 = {'CI': 'True', 'CIRCLECI': 'True', 'CIRCLE_SHA1': 'circle'} | |
| >>> c1 = CI.create(env1) | |
| >>> isinstance(c1, CircleCI) | |
| True | |
| >>> isinstance(c1, CI) | |
| True | |
| >>> c1.commit | |
| 'circle' | |
| >>> env2 = {'CI': 'true', 'TRAVIS': 'True', 'TRAVIS_COMMIT': 'travis'} | |
| >>> c2 = CI.create(env2) | |
| >>> isinstance(c2, Travis) | |
| True | |
| >>> isinstance(c2, CI) | |
| True | |
| >>> c2.commit | |
| 'travis' | |
| """ | |
| @staticmethod | |
| def create(env): | |
| ci_env = env.get('CI', 'False').lower() | |
| if ci_env not in ('1', 't', 'true'): | |
| raise SystemError("Not running on CI system! {}".format(ci_env)) | |
| cls = None | |
| for subclass in CI.__subclasses__(): | |
| if not subclass.using(env): | |
| continue | |
| cls = subclass | |
| break | |
| if not cls: | |
| raise SystemError("Unknown CI environment!") | |
| return cls(env) | |
| def __init__(self, env): | |
| self.env = env | |
| @classmethod | |
| def using(cls, env): | |
| env_name = cls.__name__.upper() | |
| env_value = env.get(env_name, None) | |
| return bool(env_value) | |
| commit = ci_property("commit") | |
| slug = ci_property("slug") | |
| hosting = ci_property("hosting") | |
| buildid = ci_property("buildid") | |
| logurl = ci_property("logurl") | |
| @property | |
| def user(self): | |
| return self.slug.split('/', 1)[0] | |
| @property | |
| def repo(self): | |
| return self.slug.split('/', 1)[-1] | |
| class CircleCI(CI): | |
| _commit = 'CIRCLE_SHA1' | |
| _slug = '' | |
| _hosting = '' | |
| _buildid = '' | |
| class Travis(CI): | |
| _commit = 'TRAVIS_COMMIT' | |
| _slug = 'TRAVIS_REPO_SLUG' | |
| _buildid = 'TRAVIS_JOB_ID' | |
| hosting = 'github' | |
| class AppVeyor(CI): | |
| _commit = 'APPVEYOR_REPO_COMMIT' | |
| _slug = 'APPVEYOR_PROJECT_SLUG' | |
| _hosting = 'APPVEYOR_REPO_PROVIDER' | |
| _buildid = 'APPVEYOR_BUILD_ID' | |
| def main(argv): | |
| pass | |
| if __name__ == "__main__": | |
| import doctest | |
| doctest.testmod() | |
| sys.exit(main(sys.argv)) |