├── .coveragerc ├── .gitignore ├── LICENSE.txt ├── README.md ├── bin └── gitconsensus ├── gitconsensus ├── __init__.py ├── config.py ├── gitconsensus.py └── repository.py ├── makefile ├── requirements.txt ├── setup.cfg ├── setup.py └── tests ├── __init__.py └── test_cli.py /.coveragerc: -------------------------------------------------------------------------------- 1 | [report] 2 | 3 | exclude_lines = 4 | if __name__ == .__main__.: -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | 103 | .gitcredentials 104 | 105 | MANIFEST 106 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Robert Hafner 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GitConsensus 2 | 3 | This simple project allows github projects to be automated. It uses "reaction" as a voting mechanism to automatically 4 | merge (or close) pull requests. 5 | 6 | ## Consensus Rules 7 | 8 | The file `.gitconsensus.yaml` needs to be placed in the repository to be managed. Any rule set to `false` or ommitted 9 | will be skipped. 10 | 11 | You can run `gitconsensus init` to start with a template configuration in the current working directory. 12 | 13 | ```yaml 14 | # Which version of the consensus rules to use 15 | version: 3 16 | 17 | # Add extra labels for the vote counts and age when merging 18 | extra_labels: false 19 | 20 | # Don't count any vote from a user who votes for multiple options 21 | prevent_doubles: true 22 | 23 | # The following only applies to pull requests 24 | pull_requests: 25 | 26 | # Minimum number of voters 27 | quorum: 5 28 | 29 | # Required percentage of "yes" votes (ignoring abstentions) 30 | threshold: 0.65 31 | 32 | # Only process votes by contributors 33 | contributors_only: false 34 | 35 | # Only process votes by collaborators 36 | collaborators_only: false 37 | 38 | # When defined only process votes from these github users 39 | whitelist: 40 | - alice 41 | - carol 42 | 43 | # When defined votes from these users will be ignored 44 | blacklist: 45 | - bob 46 | - dan 47 | 48 | # Number of hours after last action (commit or opening the pull request) before issue can be merged 49 | merge_delay: 24 50 | 51 | # Number of votes from contributors at which the mergedelay gets ignored, assuming no negative votes. 52 | delay_override: 10 53 | 54 | # When `delayoverride` is set this value is the minimum hours without changes before the PR will be merged 55 | merge_delay_min: 1 56 | 57 | # Require this amount of time in hours before a PR with a license change will be merged. 58 | licensed_delay: 72 59 | 60 | # Require this amount of time in hours before a PR with a consensus change will be merged. 61 | consensus_delay: 72 62 | 63 | # Do not allow license changes to be merged. 64 | license_lock: true 65 | 66 | # Do not allow consensus changes to be merged. 67 | consensus_lock: true 68 | 69 | # Number of hours after last action (commit or opening the pull request) before issue is autoclosed 70 | timeout: 720 71 | ``` 72 | 73 | ## Voting 74 | 75 | Votes are made by using reactions on the top level comment of the Pull Request. 76 | 77 | | Reaction | Vote | 78 | |----------|---------| 79 | | ![+1](https://github.githubassets.com/images/icons/emoji/unicode/1f44d.png "+1") | Yes | 80 | | ![-1](https://github.githubassets.com/images/icons/emoji/unicode/1f44e.png "-1") | No | 81 | | ![confused](https://github.githubassets.com/images/icons/emoji/unicode/1f615.png "confused") | Abstain | 82 | 83 | 84 | ## Label Overrides 85 | 86 | Any Pull Request with a `WIP` or `DONTMERGE` label (case insensitive) will be skipped over. 87 | 88 | 89 | ## Commands 90 | 91 | ### Authentication 92 | 93 | ```shell 94 | gitconsensus auth 95 | ``` 96 | 97 | You will be asked for your username, password, and 2fa token (if configured). This will be used to get an authentication 98 | token from Github that will be used in place of your username and password (which are never saved). 99 | 100 | ### Initialization 101 | 102 | Initialize the configuration for a specific project. If no template is provided the `recommended` settings will be used. 103 | All settings come from the [gitconsensus_examples](https://github.com/gitconsensus/gitconsensus_examples) project. 104 | 105 | ```shell 106 | gitconsensus init [TEMPLATE] 107 | ``` 108 | 109 | ### Merge 110 | 111 | Merge all pull requests that meet consensus rules. 112 | 113 | ```shell 114 | gitconsensus merge USERNAME REPOSITORY 115 | ``` 116 | 117 | ### Close 118 | 119 | Close all pull requests that have passed the "timeout" date (if it is set). 120 | 121 | ```shell 122 | gitconsensus close USERNAME REPOSITORY 123 | ``` 124 | 125 | ### Info 126 | 127 | Get detailed infromation about a specific pull request and what rules it passes. 128 | 129 | ```shell 130 | gitconsensus info USERNAME REPOSITORY PR_NUMBER 131 | ``` 132 | 133 | ### Force Close 134 | 135 | Close specific pull request, including any labels and comments that normally would be sent. 136 | 137 | ```shell 138 | gitconsensus forceclose USERNAME REPOSITORY PR_NUMBER 139 | ``` 140 | 141 | ### Force Merge 142 | 143 | Merge specific pull request, including any labels and comments that normally would be sent. 144 | 145 | ```shell 146 | gitconsensus forcemerge USERNAME REPOSITORY PR_NUMBER 147 | ``` 148 | -------------------------------------------------------------------------------- /bin/gitconsensus: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Get real directory in case of symlink 4 | if [[ -L "${BASH_SOURCE[0]}" ]] 5 | then 6 | DIR="$( cd "$( dirname $( readlink "${BASH_SOURCE[0]}" ) )" && pwd )" 7 | else 8 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 9 | fi 10 | 11 | ENV="$DIR/../env/bin/activate" 12 | if [ ! -f $ENV ]; then 13 | echo 'Virtual Environment Not Installed- Run `make`' 14 | exit -1 15 | fi 16 | source $ENV 17 | 18 | python -m gitconsensus.gitconsensus "$@" 19 | -------------------------------------------------------------------------------- /gitconsensus/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gitconsensus/GitConsensusCLI/93abd3a3ac97f6ebc90881ce3e0619924a910821/gitconsensus/__init__.py -------------------------------------------------------------------------------- /gitconsensus/config.py: -------------------------------------------------------------------------------- 1 | import os 2 | import yaml 3 | 4 | settings = False 5 | cwd = os.getcwd() 6 | path = "%s/%s" % (os.getcwd(), '/.gitconsensus.yaml') 7 | 8 | 9 | def getSettings(): 10 | global settings 11 | return settings 12 | 13 | 14 | def reloadSettings(): 15 | global settings 16 | if os.path.isfile(path): 17 | with open(path, 'r') as f: 18 | settings = yaml.safe_load(f) 19 | return settings 20 | 21 | 22 | def getGitToken(): 23 | token = id = '' 24 | with open("%s/%s" % (os.getcwd(), '/.gitcredentials'), 'r') as fd: 25 | return { 26 | "id": fd.readline().strip(), 27 | "token": fd.readline().strip() 28 | } 29 | return False 30 | 31 | reloadSettings() 32 | -------------------------------------------------------------------------------- /gitconsensus/gitconsensus.py: -------------------------------------------------------------------------------- 1 | import click 2 | import github3 3 | import os 4 | import random 5 | import requests 6 | from gitconsensus import config 7 | from gitconsensus.repository import Repository 8 | import string 9 | 10 | @click.group() 11 | @click.pass_context 12 | def cli(ctx): 13 | if ctx.parent: 14 | print(ctx.parent.get_help()) 15 | 16 | 17 | @cli.command(short_help="Obtain an authorization token") 18 | def auth(): 19 | username = click.prompt('Username') 20 | password = click.prompt('Password', hide_input=True) 21 | def twofacallback(*args): 22 | return click.prompt('2fa Code') 23 | 24 | hostid = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8)) 25 | note = 'gitconsensus - %s' % (hostid,) 26 | note_url = 'https://github.com/tedivm/GitConsensus' 27 | scopes = ['repo'] 28 | auth = github3.authorize(username, password, scopes, note, note_url, two_factor_callback=twofacallback) 29 | 30 | with open("%s/%s" % (os.getcwd(), '/.gitcredentials'), 'w') as fd: 31 | fd.write(str(auth.id) + '\n') 32 | fd.write(auth.token + '\n') 33 | 34 | 35 | @cli.command(short_help="Create a new gitconsensus configuration") 36 | @click.argument('template', required=False) 37 | def init(template): 38 | if not template: 39 | template = 'recommended' 40 | 41 | if os.path.isfile('.gitconsensus.yaml'): 42 | click.echo('.gitconsensus.yaml already exists.') 43 | exit(-1) 44 | 45 | baseurl = 'https://raw.githubusercontent.com/gitconsensus/gitconsensus_examples/master/examples/%s/.gitconsensus.yaml' 46 | url = baseurl % (template) 47 | response = requests.get(url) 48 | 49 | if not response.ok: 50 | click.echo('Unable to find template "%s"' % (template)) 51 | exit(-1) 52 | 53 | with open('.gitconsensus.yaml', 'wb') as f: 54 | f.write(response.content) 55 | 56 | 57 | @cli.command(short_help="List open pull requests and their status") 58 | @click.argument('username') 59 | @click.argument('repository_name') 60 | def list(username, repository_name): 61 | repo = get_repository(username, repository_name) 62 | requests = repo.getPullRequests() 63 | for request in requests: 64 | click.echo("PR#%s: %s" % (request.number, request.validate())) 65 | 66 | 67 | @cli.command(short_help="Display detailed information about a specific pull request") 68 | @click.argument('username') 69 | @click.argument('repository_name') 70 | @click.argument('pull_request') 71 | def info(username, repository_name, pull_request): 72 | repo = get_repository(username, repository_name) 73 | request = repo.getPullRequest(pull_request) 74 | click.echo("PR#%s: %s" % (request.number, request.pr.title)) 75 | consensus = repo.getConsensus() 76 | click.echo("Mergeable: %s" % (consensus.isMergeable(request),)) 77 | click.echo("Is Blocked: %s" % (request.isBlocked(),)) 78 | click.echo("Is Allowed: %s" % (consensus.isAllowed(request),)) 79 | click.echo("Has Quorum: %s" % (consensus.hasQuorum(request),)) 80 | click.echo("Has Votes: %s" % (consensus.hasVotes(request),)) 81 | click.echo("Has Aged: %s" % (consensus.hasAged(request),)) 82 | click.echo("Should Close: %s" % (request.shouldClose(),)) 83 | click.echo("Last Update: %s" % (request.hoursSinceLastUpdate(),)) 84 | 85 | 86 | @cli.command(short_help="Forced a specific pull request to be merged") 87 | @click.argument('username') 88 | @click.argument('repository_name') 89 | @click.argument('pull_request') 90 | def forcemerge(username, repository_name, pull_request): 91 | repo = get_repository(username, repository_name) 92 | request = repo.getPullRequest(pull_request) 93 | click.echo("PR#%s: %s" % (request.number, request.pr.title)) 94 | request.vote_merge() 95 | 96 | 97 | @cli.command(short_help="Forced a specific pull request to be closed") 98 | @click.argument('username') 99 | @click.argument('repository_name') 100 | @click.argument('pull_request') 101 | def forceclose(username, repository_name, pull_request): 102 | repo = get_repository(username, repository_name) 103 | request = repo.getPullRequest(pull_request) 104 | click.echo("PR#%s: %s" % (request.number, request.pr.title)) 105 | request.close() 106 | 107 | 108 | @cli.command(short_help="Merge open pull requests that validate") 109 | @click.argument('username') 110 | @click.argument('repository_name') 111 | def merge(username, repository_name): 112 | repo = get_repository(username, repository_name) 113 | requests = repo.getPullRequests() 114 | for request in requests: 115 | if request.validate(): 116 | click.echo("Merging PR#%s" % (request.number,)) 117 | request.vote_merge() 118 | else: 119 | request.addInfoLabels() 120 | 121 | 122 | @cli.command(short_help="Close older unmerged opened pull requests") 123 | @click.argument('username') 124 | @click.argument('repository_name') 125 | def close(username, repository_name): 126 | repo = get_repository(username, repository_name) 127 | requests = repo.getPullRequests() 128 | for request in requests: 129 | if request.isBlocked(): 130 | continue 131 | if request.shouldClose(): 132 | click.echo("Closing PR#%s" % (request.number,)) 133 | request.addInfoLabels() 134 | request.close() 135 | 136 | 137 | @cli.command(short_help="Add labels and set colors") 138 | @click.argument('username') 139 | @click.argument('repository_name') 140 | @click.option('--color-negative', default='#ee0701') 141 | @click.option('--color-positive', default='#0052cc') 142 | @click.option('--color-notice', default='#fbf904') 143 | def createlabels(username, repository_name, color_negative, color_positive, color_notice): 144 | repo = get_repository(username, repository_name) 145 | repo.setLabelColor('License Change', color_notice) 146 | repo.setLabelColor('Consensus Change', color_notice) 147 | repo.setLabelColor('Has Quorum', color_positive) 148 | repo.setLabelColor('Needs Votes', color_negative) 149 | repo.setLabelColor('Passing', color_positive) 150 | repo.setLabelColor('Failing', color_negative) 151 | repo.setLabelColor('gc-merged', color_positive) 152 | repo.setLabelColor('gc-closed', color_negative) 153 | 154 | 155 | def get_repository(username, repository_name): 156 | credentials = config.getGitToken() 157 | client = github3.login(token=credentials['token']) 158 | return Repository(username, repository_name, client) 159 | 160 | 161 | if __name__ == '__main__': 162 | cli() 163 | -------------------------------------------------------------------------------- /gitconsensus/repository.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import datetime 3 | import github3 4 | import json 5 | import requests 6 | from semantic_version import Version 7 | import yaml 8 | 9 | # .gitconsensus.yaml files with versions higher than this will be ignored. 10 | max_consensus_version = Version('3.0.0', partial=True) 11 | 12 | message_template = """ 13 | This Pull Request has been %s by [GitConsensus](https://www.gitconsensus.com/). 14 | 15 | ## Vote Totals 16 | 17 | | Yes | No | Abstain | Voters | 18 | | --- | -- | ------- | ------ | 19 | | %s | %s | %s | %s | 20 | 21 | 22 | ## Vote Breakdown 23 | 24 | %s 25 | 26 | 27 | ## Vote Results 28 | 29 | | Criteria | Result | 30 | | ---------- | ------ | 31 | | Has Quorum | %s | 32 | | Has Votes | %s | 33 | 34 | """ 35 | 36 | consensus_url_template = "https://api.github.com/repos/%s/%s/contents/.gitconsensus.yaml" 37 | 38 | 39 | def githubApiRequest(url, client): 40 | headers = {'Accept': 'application/vnd.github.squirrel-girl-preview'} 41 | return client._get(url, headers=headers) 42 | 43 | 44 | class Repository: 45 | 46 | def __init__(self, user, repository, client): 47 | self.user = user 48 | self.name = repository 49 | self.contributors = False 50 | self.collaborators = {} 51 | self.client = client 52 | self.client.set_user_agent('gitconsensus') 53 | self.repository = self.client.repository(self.user, self.name) 54 | consensusurl = consensus_url_template % (self.user, self.name) 55 | res = githubApiRequest(consensusurl, self.client) 56 | self.rules = False 57 | if res.status_code == 200: 58 | ruleresults = res.json() 59 | self.rules = yaml.safe_load(base64.b64decode(ruleresults['content']).decode('utf-8')) 60 | # support older versions by converting from day to hours. 61 | if 'version' not in self.rules or self.rules['version'] < 2: 62 | if 'mergedelay' in self.rules and self.rules['mergedelay']: 63 | self.rules['mergedelay'] = self.rules['mergedelay'] * 24 64 | if 'timeout' in self.rules and self.rules['timeout']: 65 | self.rules['timeout'] = self.rules['timeout'] * 24 66 | self.rules['version'] = 2 67 | 68 | if self.rules['version'] < 3: 69 | self.rules['version'] = 3 70 | self.rules['pull_requests'] = { 71 | "quorum": self.rules.get('quorum', False), 72 | "threshold": self.rules.get('threshold', False), 73 | "contributors_only": self.rules.get('contributorsonly', False), 74 | "collaborators_only": self.rules.get('collaboratorsonly', False), 75 | "whitelist": self.rules.get('whitelist'), 76 | "blacklist": self.rules.get('blacklist'), 77 | "merge_delay": self.rules.get('mergedelay', False), 78 | "delay_override": self.rules.get('delayoverride', False), 79 | "merge_delay_min": self.rules.get('mergedelaymin', False), 80 | "license_delay": self.rules.get('licenseddelay', False), 81 | "license_lock": self.rules.get('locklicense', False), 82 | "consensus_delay": self.rules.get('consensusdelay', False), 83 | "consensus_lock": self.rules.get('lockconsensus', False), 84 | "timeout": self.rules.get('timeout') 85 | } 86 | 87 | if int(self.rules['pull_requests']['threshold']) > 1: 88 | self.rules['pull_requests']['threshold'] /= 100 89 | 90 | # Treat higher version consensus rules are an unconfigured repository. 91 | project_consensus_version = Version(str(self.rules['version']), partial=True) 92 | if max_consensus_version < project_consensus_version: 93 | self.rules = False 94 | 95 | def getPullRequests(self): 96 | prs = self.repository.iter_pulls(state="open") 97 | retpr = [] 98 | for pr in prs: 99 | newpr = PullRequest(self, pr.number) 100 | retpr.append(newpr) 101 | return retpr 102 | 103 | def getPullRequest(self, number): 104 | return PullRequest(self, number) 105 | 106 | def isContributor(self, username): 107 | if not self.contributors: 108 | contributor_list = self.repository.contributors() 109 | self.contributors = [str(contributor) for contributor in contributor_list] 110 | return username in self.contributors 111 | 112 | def isCollaborator(self, username): 113 | if username not in self.collaborators: 114 | self.collaborators[username] = self.repository.is_collaborator(username) 115 | return self.repository.is_collaborator(username) 116 | 117 | def getConsensus(self): 118 | return Consensus(self.rules) 119 | 120 | def setLabelColor(self, name, color): 121 | labels = self.get_labels() 122 | if name not in labels: 123 | self.repository.create_label(name, color) 124 | elif color != labels[name].color: 125 | labels[name].update(name, color) 126 | 127 | def get_labels(self): 128 | labels = {} 129 | for label in self.repository.labels(): 130 | labels[label.name] = label 131 | return labels 132 | 133 | 134 | class PullRequest: 135 | labels = False 136 | 137 | def __init__(self, repository, number): 138 | self.repository = repository 139 | self.consensus = repository.getConsensus() 140 | self.number = number 141 | self.pr = self.repository.client.pull_request(self.repository.user, self.repository.name, number) 142 | 143 | # https://api.github.com/repos/OWNER/REPO/issues/1/reactions 144 | reacturl = "https://api.github.com/repos/%s/%s/issues/%s/reactions" % (self.repository.user, self.repository.name, self.number) 145 | res = githubApiRequest(reacturl, self.repository.client) 146 | reactions = json.loads(res.text) 147 | 148 | self.yes = [] 149 | self.no = [] 150 | self.abstain = [] 151 | 152 | self.contributors_yes = [] 153 | self.contributors_no = [] 154 | self.contributors_abstain = [] 155 | 156 | self.users = [] 157 | self.doubles = [] 158 | for reaction in reactions: 159 | content = reaction['content'] 160 | user = reaction['user'] 161 | username = user['login'] 162 | 163 | if username in self.doubles: 164 | continue 165 | 166 | if 'blacklist' in self.repository.rules and self.repository.rules['blacklist']: 167 | if username in self.repository.blacklist: 168 | continue 169 | 170 | if 'collaborators_only' in self.repository.rules and self.repository.rules['collaborators_only']: 171 | if not self.repository.isCollaborator(username): 172 | continue 173 | 174 | if 'contributors_only' in self.repository.rules and self.repository.rules['contributors_only']: 175 | if not self.repository.isContributor(username): 176 | continue 177 | 178 | if 'whitelist' in self.repository.rules: 179 | if username not in self.repository.rules['whitelist']: 180 | continue 181 | 182 | if 'prevent_doubles' in self.repository.rules and self.repository.rules['prevent_doubles']: 183 | # make sure user hasn't voted twice 184 | if content == '+1' or content == '-1' or content == 'confused': 185 | if username in self.users: 186 | self.doubles.append(username) 187 | self.users.remove(username) 188 | if username in self.yes: 189 | self.yes.remove(username) 190 | if username in self.no: 191 | self.no.remove(username) 192 | if username in self.abstain: 193 | self.abstain.remove(username) 194 | if username in self.contributors_yes: 195 | self.contributors_yes.remove(username) 196 | if username in self.contributors_no: 197 | self.contributors_no.remove(username) 198 | if username in self.contributors_abstain: 199 | self.contributors_abstain.remove(username) 200 | continue 201 | 202 | if content == '+1': 203 | self.users.append(user['login']) 204 | self.yes.append(user['login']) 205 | if self.repository.isContributor(user['login']): 206 | self.contributors_yes.append(user['login']) 207 | elif content == '-1': 208 | self.users.append(user['login']) 209 | self.no.append(user['login']) 210 | if self.repository.isContributor(user['login']): 211 | self.contributors_no.append(user['login']) 212 | elif content == 'confused': 213 | self.users.append(user['login']) 214 | self.abstain.append(user['login']) 215 | if self.repository.isContributor(user['login']): 216 | self.contributors_abstain.append(user['login']) 217 | 218 | files = self.pr.files() 219 | self.changes_consensus = False 220 | self.changes_license = False 221 | for changed_file in files: 222 | if changed_file.filename == '.gitconsensus.yaml': 223 | self.changes_consensus = True 224 | if changed_file.filename.lower().startswith('license'): 225 | self.changes_license = True 226 | 227 | def hoursSinceLastCommit(self): 228 | commits = self.pr.commits() 229 | 230 | for commit in commits: 231 | commit_date_string = commit._json_data['commit']['author']['date'] 232 | 233 | # 2017-08-19T23:29:31Z 234 | commit_date = datetime.datetime.strptime(commit_date_string, '%Y-%m-%dT%H:%M:%SZ') 235 | now = datetime.datetime.utcnow() 236 | delta = now - commit_date 237 | return delta.total_seconds() / 3600 238 | 239 | def hoursSincePullOpened(self): 240 | now = datetime.datetime.utcnow() 241 | delta = now - self.pr.created_at.replace(tzinfo=None) 242 | return delta.total_seconds() / 3600 243 | 244 | def hoursSinceLastUpdate(self): 245 | hoursOpen = self.hoursSincePullOpened() 246 | hoursSinceCommit = self.hoursSinceLastCommit() 247 | if hoursOpen < hoursSinceCommit: 248 | return hoursOpen 249 | return hoursSinceCommit 250 | 251 | def changesConsensus(self): 252 | return self.changes_consensus 253 | 254 | def changesLicense(self): 255 | return self.changes_license 256 | 257 | def getIssue(self): 258 | return self.repository.repository.issue(self.number) 259 | 260 | def validate(self): 261 | if self.repository.rules == False: 262 | return False 263 | return self.consensus.validate(self) 264 | 265 | def shouldClose(self): 266 | if not self.repository.rules: 267 | return False 268 | if 'pull_requests' not in self.repository.rules: 269 | return False 270 | if 'timeout' in self.repository.rules['pull_requests']: 271 | if self.hoursSinceLastUpdate() >= self.repository.rules['pull_requests']['timeout']: 272 | return True 273 | return False 274 | 275 | def close(self): 276 | self.pr.close() 277 | self.addLabels(['gc-closed']) 278 | self.cleanInfoLabels() 279 | self.commentAction('closed') 280 | 281 | def vote_merge(self): 282 | if not self.repository.rules: 283 | return False 284 | self.pr.merge('GitConsensus Merge') 285 | self.addLabels(['gc-merged']) 286 | self.cleanInfoLabels() 287 | 288 | if 'extra_labels' in self.repository.rules and self.repository.rules['extra_labels']: 289 | self.addLabels([ 290 | 'gc-voters %s' % (len(self.users),), 291 | 'gc-yes %s' % (len(self.yes),), 292 | 'gc-no %s' % (len(self.no),), 293 | 'gc-age %s' % (int(self.hoursSinceLastUpdate()),) 294 | ]) 295 | self.commentAction('merged') 296 | 297 | def addInfoLabels(self): 298 | labels = self.getLabelList() 299 | 300 | licenseMessage = 'License Change' 301 | if self.changesLicense(): 302 | self.addLabels([licenseMessage]) 303 | else: 304 | self.removeLabels([licenseMessage]) 305 | 306 | consensusMessage = 'Consensus Change' 307 | if self.changesConsensus(): 308 | self.addLabels([consensusMessage]) 309 | else: 310 | self.removeLabels([consensusMessage]) 311 | 312 | hasQuorumMessage = 'Has Quorum' 313 | needsQuorumMessage = 'Needs Votes' 314 | if self.consensus.hasQuorum(self): 315 | self.addLabels([hasQuorumMessage]) 316 | self.removeLabels([needsQuorumMessage]) 317 | else: 318 | self.removeLabels([hasQuorumMessage]) 319 | self.addLabels([needsQuorumMessage]) 320 | 321 | passingMessage = 'Passing' 322 | failingMessage = 'Failing' 323 | if self.consensus.hasVotes(self): 324 | self.addLabels([passingMessage]) 325 | self.removeLabels([failingMessage]) 326 | else: 327 | self.removeLabels([passingMessage]) 328 | self.addLabels([failingMessage]) 329 | 330 | def cleanInfoLabels(self): 331 | self.removeLabels(['Failing', 'Passing', 'Needs Votes', 'Has Quorum']) 332 | 333 | def commentAction(self, action): 334 | table = self.buildVoteTable() 335 | message = message_template % ( 336 | action, 337 | str(len(self.yes)), 338 | str(len(self.no)), 339 | str(len(self.abstain)), 340 | str(len(self.users)), 341 | table, 342 | self.consensus.hasQuorum(self), 343 | self.consensus.hasVotes(self) 344 | ) 345 | 346 | if len(self.doubles) > 0: 347 | duplist = ["[%s](https://github.com/%s)" % (username, username) for username in self.doubles] 348 | dupuserstring = ', '.join(duplist) 349 | dupstring = '\n\nThe following users voted for multiple options and were exlcuded: \n%s' % (dupuserstring) 350 | message = "%s\n%s" % (message, dupstring) 351 | 352 | self.addComment(message) 353 | 354 | def buildVoteTable(self): 355 | table = '| User | Yes | No | Abstain |\n|--------|-----|----|----|' 356 | for user in self.users: 357 | if user in self.yes: 358 | yes = '✔' 359 | else: 360 | yes = ' ' 361 | if user in self.no: 362 | no = '✔' 363 | else: 364 | no = ' ' 365 | if user in self.abstain: 366 | abstain = '✔' 367 | else: 368 | abstain = ' ' 369 | 370 | user_label = '[%s](https://github.com/%s)' % (user, user) 371 | row = "| %s | %s | %s | %s |" % (user_label, yes, no, abstain) 372 | table = "%s\n%s" % (table, row) 373 | return table 374 | 375 | def addLabels(self, labels): 376 | existing = self.getLabelList() 377 | issue = self.getIssue() 378 | for label in labels: 379 | if label not in existing: 380 | issue.add_labels(label) 381 | 382 | def removeLabels(self, labels): 383 | existing = self.getLabelList() 384 | issue = self.getIssue() 385 | for label in labels: 386 | if label in existing: 387 | issue.remove_label(label) 388 | 389 | def addComment(self, comment_string): 390 | return self.getIssue().create_comment(comment_string) 391 | 392 | def getLabelList(self): 393 | if not self.labels: 394 | issue = self.getIssue() 395 | self.labels = [item.name for item in issue.labels()] 396 | return self.labels 397 | 398 | def isBlocked(self): 399 | labels = [item.lower() for item in self.getLabelList()] 400 | if 'wip' in labels: 401 | return True 402 | if 'dontmerge' in labels: 403 | return True 404 | return False 405 | 406 | 407 | class Consensus: 408 | def __init__(self, rules): 409 | self.rules = rules 410 | 411 | def validate(self, pr): 412 | if not self.rules: 413 | return False 414 | if pr.isBlocked(): 415 | return False 416 | if not self.isAllowed(pr): 417 | return False 418 | if not self.isMergeable(pr): 419 | return False 420 | if not self.hasQuorum(pr): 421 | return False 422 | if not self.hasVotes(pr): 423 | return False 424 | if not self.hasAged(pr): 425 | return False 426 | return True 427 | 428 | def isAllowed(self, pr): 429 | if not self.rules: 430 | return False 431 | if pr.changesLicense(): 432 | if 'license_lock' in self.rules['pull_requests'] and self.rules['pull_requests']['license_lock']: 433 | return False 434 | if pr.changesConsensus(): 435 | if 'consensus_lock' in self.rules['pull_requests'] and self.rules['pull_requests']['consensus_lock']: 436 | return False 437 | return True 438 | 439 | def isMergeable(self, pr): 440 | if not self.rules: 441 | return False 442 | if not pr.pr.mergeable: 443 | return False 444 | return True 445 | 446 | def hasQuorum(self, pr): 447 | if not self.rules: 448 | return False 449 | if 'quorum' in self.rules['pull_requests']: 450 | if len(pr.users) < self.rules['pull_requests']['quorum']: 451 | return False 452 | return True 453 | 454 | def hasVotes(self, pr): 455 | if not self.rules: 456 | return False 457 | if 'threshold' in self.rules['pull_requests']: 458 | total = (len(pr.yes) + len(pr.no)) 459 | if total <= 0: 460 | return False 461 | ratio = len(pr.yes) / total 462 | if ratio < self.rules['pull_requests']['threshold']: 463 | return False 464 | return True 465 | 466 | def hasAged(self, pr): 467 | if not self.rules: 468 | return False 469 | hours = pr.hoursSinceLastUpdate() 470 | if pr.changesLicense(): 471 | if 'license_delay' in self.rules['pull_requests'] and self.rules['pull_requests']['license_delay']: 472 | if hours < self.rules['pull_requests']['license_delay']: 473 | return False 474 | if pr.changesConsensus(): 475 | if 'consensus_delay' in self.rules['pull_requests'] and self.rules['pull_requests']['consensus_delay']: 476 | if hours < self.rules['pull_requests']['consensus_delay']: 477 | return False 478 | if 'merge_delay' not in self.rules['pull_requests'] or not self.rules['pull_requests']['merge_delay']: 479 | return True 480 | if hours >= self.rules['pull_requests']['merge_delay']: 481 | return True 482 | if 'delay_override' in self.rules['pull_requests'] and self.rules['pull_requests']['delay_override']: 483 | if pr.changesConsensus() or pr.changesLicense(): 484 | return False 485 | if 'merge_delay_min' in self.rules['pull_requests'] and self.rules['pull_requests']['merge_delay_min']: 486 | if hours < self.rules['pull_requests']['merge_delay_min']: 487 | return False 488 | if len(pr.no) > 0: 489 | return False 490 | if len(pr.contributors_yes) >= self.rules['pull_requests']['delay_override']: 491 | return True 492 | return False 493 | -------------------------------------------------------------------------------- /makefile: -------------------------------------------------------------------------------- 1 | 2 | SHELL:=/bin/bash 3 | ROOT_DIR:=$(shell dirname $(realpath $(lastword $(MAKEFILE_LIST)))) 4 | 5 | .PHONY: all fresh dependencies clean package 6 | 7 | all: dependencies 8 | 9 | fresh: clean dependencies 10 | 11 | clean: 12 | rm -rf $(ROOT_DIR)/gitconsensus/*.pyc 13 | rm -rf $(ROOT_DIR)/env 14 | rm -rf $(ROOT_DIR)/dist 15 | rm -rf $(ROOT_DIR)/build 16 | rm -rf $(ROOT_DIR)/*.egg-info 17 | 18 | dependencies: 19 | if [ ! -d $(ROOT_DIR)/env ]; then python3 -m venv $(ROOT_DIR)/env; fi 20 | source $(ROOT_DIR)/env/bin/activate; yes w | python -m pip install -e .[dev] 21 | 22 | test: 23 | python setup.py test 24 | 25 | package: 26 | source $(ROOT_DIR)/env/bin/activate; python setup.py bdist_wheel 27 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | certifi==2018.1.18 2 | chardet==3.0.4 3 | click==6.7 4 | github3.py==1.0.2 5 | idna==2.6 6 | pkginfo==1.4.2 7 | pypandoc==1.4 8 | python-dateutil==2.7.2 9 | PyYAML==3.12 10 | requests==2.18.4 11 | requests-toolbelt==0.8.0 12 | semantic-version==2.6.0 13 | six==1.11.0 14 | tqdm==4.21.0 15 | twine==1.11.0 16 | uritemplate==3.0.0 17 | urllib3==1.22 18 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md 3 | 4 | [aliases] 5 | test=pytest 6 | 7 | [tool:pytest] 8 | addopts = --cov=gitconsensus --cov-report term-missing 9 | python_files = tests/*.py -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Always prefer setuptools over distutils 2 | from setuptools import setup, find_packages 3 | # To use a consistent encoding 4 | from codecs import open 5 | 6 | version = '0.8.0' 7 | setup( 8 | 9 | name = 'gitconsensus', 10 | 11 | version = version, 12 | packages=find_packages(), 13 | 14 | description = 'Automate Github Pull Requests using Reactions', 15 | long_description=open('README.md').read(), 16 | long_description_content_type="text/markdown", 17 | python_requires='>=3', 18 | 19 | author = 'Robert Hafner', 20 | author_email = 'tedivm@tedivm.com', 21 | url = 'https://github.com/gitconsensus/gitconsensuscli', 22 | download_url = "https://github.com/gitconsensus/gitconsensuscli/archive/v%s.tar.gz" % (version), 23 | keywords = 'automation github consensus git', 24 | 25 | classifiers = [ 26 | 'Development Status :: 4 - Beta', 27 | 'License :: OSI Approved :: MIT License', 28 | 29 | 'Intended Audience :: Developers', 30 | 'Intended Audience :: System Administrators', 31 | 'Topic :: Software Development :: Version Control', 32 | 33 | 'Programming Language :: Python :: 3', 34 | 'Environment :: Console', 35 | ], 36 | 37 | install_requires=[ 38 | 'click>=6.0,<8.0', 39 | 'github3.py>=1,<2', 40 | 'PyYAML>=3.12,<6', 41 | 'requests>=2.18.0,<3', 42 | 'semantic_version>=2.6.0,<3' 43 | ], 44 | 45 | extras_require={ 46 | 'dev': [ 47 | 'twine', 48 | 'wheel' 49 | ], 50 | }, 51 | 52 | setup_requires=["pytest-runner"], 53 | tests_require=["freezegun", "pytest", "pytest-cov", "pytest-mock"], 54 | 55 | entry_points={ 56 | 'console_scripts': [ 57 | 'gitconsensus=gitconsensus.gitconsensus:cli', 58 | ], 59 | }, 60 | 61 | ) 62 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gitconsensus/GitConsensusCLI/93abd3a3ac97f6ebc90881ce3e0619924a910821/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_cli.py: -------------------------------------------------------------------------------- 1 | from click.testing import CliRunner 2 | from gitconsensus.gitconsensus import cli 3 | 4 | def test_cli_command(): 5 | runner = CliRunner() 6 | result = runner.invoke(cli, ["get-repository"]) 7 | assert result.exit_code == 2 8 | 9 | --------------------------------------------------------------------------------