Skip to content

Instantly share code, notes, and snippets.

@mithro
Last active February 25, 2018 19:16
Show Gist options
  • Save mithro/d1bb8433abd9c8cda963777f1aeef409 to your computer and use it in GitHub Desktop.
Save mithro/d1bb8433abd9c8cda963777f1aeef409 to your computer and use it in GitHub Desktop.
#!/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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment