Esempio n. 1
0
def make_github_webhook(app, database):
    import github_webhook
    webhook = github_webhook.Webhook(app, endpoint='/github-webhook/')

    @webhook.hook()
    def on_push(data):
        logger.debug('recieved push event\n %s', data)
        if data.get('ref'):
            if data.get('ref_type', '') == 'tag':
                return
            with database.get_session() as session:

                repo_name = data['repository']['full_name']
                username = data['sender']['login']

                try:
                    user = session.query(User).filter_by(username=username).one()
                except NoResultFound:
                    logger.debug('adding new user: %s', username)
                    user = User(username=username)
                    session.add(user)

                try:
                    repo = session.query(Repo).filter_by(name=repo_name).one()
                except NoResultFound:
                    logger.debug('adding new repo: %s', username)
                    repo = Repo(name=repo_name,
                                username=user.username,
                                scm='github')
                    session.add(repo)

                build = Build(ref=data['ref'],
                              repo_name=repo.name,
                              commit=data['after'],
                              json=data,
                              status=Status.created)

                repo.builds.append(build)

                session.commit()

                github = Github(TokenAuth(user.token))
                github.update_status(build, GithubStatus.pending)
Esempio n. 2
0
CLIENT_ID = os.environ.get('github_client_id')
CLIENT_SECRET = os.environ.get('github_client_secret')

APP_ID = os.environ.get('github_app_id')
APP_PRIVATE_KEY = os.environ.get('github_private_key').encode('ascii')


@LocalProxy
def ghapp():
    return GithubApp(APP_ID, APP_PRIVATE_KEY)


app = Flask(__name__)
webhook = github_webhook.Webhook(
    app,
    endpoint='/postreceive',
    secret=os.environ.get('github_secret'),
)


class OutputManager:
    """
    Handles the output buffer and sending things to GitHub
    """
    def __init__(self, repo_id, sha):
        self.repo_id = repo_id
        self.git_sha = sha
        self.annotations = []
        self.output = ""
        self.total_annotations = 0
        self.run_id = None
Esempio n. 3
0
import logging
import multiprocessing
import os
from urllib import parse

import flask
import github_webhook
import yaml

from asv_github import manage_git
from asv_github import run_asv

LOG = logging.getLogger(__name__)

APP = flask.Flask(__name__)
WEBHOOK = github_webhook.Webhook(APP)
ASV_MACHINE = False

REPOS = {}
CONFIG = None

ASV_QUEUE = multiprocessing.Queue()


def load_config():
    """Load config from file, else set defaults."""
    global CONFIG
    if os.path.isfile('/etc/asv-github-api.conf'):
        CONFIG = yaml.load('/etc/asv-github-api.conf')
        if 'git-dir' not in CONFIG['api']:
            LOG.warning(
Esempio n. 4
0
# vim:fenc=utf-8
#
# Copyright © 2018 Till Hofmann <*****@*****.**>
#
# Distributed under terms of the MIT license.
"""
Send detailed commit information on GitHub push events.
"""

import github_webhook
import flask
import os
import subprocess

app = flask.Flask(__name__)
webhook = github_webhook.Webhook(app, secret=os.environ.get('GITHUB_SECRET'))


@app.route('/')
def hello_world():
    return 'Hello, world!'


@webhook.hook()
def on_push(data):
    script_env = os.environ.copy()
    full_name = data['repository']['full_name']
    repos_dir = os.environ.get('REPOS_DIR',
                               os.path.join(os.environ.get('PWD'), 'git'))
    script_env['REPO_DIR'] = os.path.join(repos_dir, full_name)
    cmd = [
Esempio n. 5
0
import github_webhook
import flask
import github

ACCESS_TOKEN = os.environ.get("GH_ACCESS_TOKEN")
REPO = "zidarsk8/zengrc"
COMMENT_TEMPLATE = """
The force push was created with the same base commit and the
following changes have been made

[{before}..{after} diff](https://github.com/{repo}/compare/{before}..{after})

""".strip()

app = flask.Flask(__name__)  # Standard Flask app
webhook = github_webhook.Webhook(app)  # Defines '/postreceive' endpoint


@app.route("/")  # Standard Flask endpoint
def hello_world():
    return "Hello, World!"


@webhook.hook()
def on_push(data):
    branch_name = data["ref"].split("/")[-1]
    if not data["forced"]:
        return
    g = github.Github(ACCESS_TOKEN)
    repo = g.get_repo(REPO)
    pulls = repo.get_pulls(head="test-commit")
Esempio n. 6
0
def git_review_handler(event, _context):
    logging.debug(event)
    webhook = github_webhook.Webhook(
        event['body'], event['headers'],
        get_environment_var('GITHUB_SECRET', True))
    if not webhook.is_valid_request():
        return response(404, 'not found')
    j = webhook.event

    am = GitAutoMerger(get_environment_var('GITHUB_TOKEN', True))
    if 'ping' == webhook.event_name:
        return response(200, 'grass tastes bad')
    elif 'status' == webhook.event_name:
        repo = j['name']
        sha = j['sha']
        if not (j['state'] == 'success'):
            logging.info("Got state %s", j['state'])
            return response(200, 'Bad state ' + j['state'])
        if not (j['context'] == required_context()):
            logging.info("Got context %s", j['context'])
            return response(200, 'Bad context ' + j['context'])
        if not (len(j['branches']) == 1):
            logging.info("Got branches %s", j['branches'])
            return response(200, 'More than one branch')
        branches = j['branches']
        branch_name = branches[0]['name']
        logging.info("Starting for %s (%s), branch %s", repo, sha, branch_name)

        am.repo = repo
        am.sha = sha
        am.branch = branch_name
    elif 'check_suite' == webhook.event_name:
        repo = j['repository']['full_name']
        check_suite = j['check_suite']
        sha = check_suite['head_sha']
        if j['action'] != 'completed':
            logging.info("Got state %s", j['action'])
            return response(200, 'Not completed. status: ' + j['action'])
        if check_suite['conclusion'] != 'success':
            logging.info("Got conclusion %s", check_suite['conclusion'])
            return response(200, 'Bad conclusion ' + check_suite['conclusion'])
        branch_name = check_suite['head_branch']
        logging.info("Starting for %s (%s), branch %s", repo, sha, branch_name)

        am.repo = repo
        am.sha = sha
        am.branch = branch_name
    elif 'pull_request_review' == webhook.event_name:
        if not (j['action'] == 'submitted'):
            logging.info("Got action %s", j['action'])
            return response(200, 'Bad action ' + j['action'])
        if not (j['review']['state'] == 'approved'):
            logging.info("Got state %s", j['review']['state'])
            return response(200, 'Bad state ' + j['review']['state'])
        pr = j['pull_request']
        am.repo = pr['head']['repo']['full_name']
        am.sha = pr['head']['sha']
        am.pr_id = pr['number']
        am.pr = pr
        am.branch = pr['head']['ref']
    else:
        return response(403, 'unsupported event ' + event)

    try:
        am.auto_merge()
        return response(200, 'merged yey')
    except ValueError as e:
        return response(200, e.message)