├── updater.sh ├── README.md ├── new_wikis_handler.sh ├── user_notice_archiver.py ├── cron ├── .gitignore ├── column_mover.py ├── patch_makers.py ├── gerrit.py ├── patchforreview_remover.py ├── lib.py ├── project_grouper.py ├── new_wikis_handler.py └── LICENSE /updater.sh: -------------------------------------------------------------------------------- 1 | cd /data/project/phabbot/phabbot 2 | git pull 3 | cat /data/project/phabbot/phabbot/cron | crontab - -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MOVE: This project has been moved to https://gitlab.wikimedia.org/ladsgroup/Phabricator-maintenance-bot 2 | -------------------------------------------------------------------------------- /new_wikis_handler.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | eval $(ssh-agent) 4 | python3 /data/project/phabbot/phabbot/new_wikis_handler.py /data/project/phabbot/phabbot/creds.json 10000000 5 | pkill -u $USER ssh-agent 6 | -------------------------------------------------------------------------------- /user_notice_archiver.py: -------------------------------------------------------------------------------- 1 | from lib import Client 2 | 3 | 4 | client = Client.newFromCreds() 5 | 6 | user_notice_phid = client.lookupPhid('#user-notice') 7 | columns = client.getColumns(user_notice_phid) 8 | mapping = {} 9 | for column in columns['data']: 10 | mapping[column['fields']['name']] = column['phid'] 11 | gen = client.getInactiveTasksWithProject(user_notice_phid, columns=[mapping['Already announced/Archive']]) 12 | for phid in gen: 13 | client.changeProjectByPhid(phid, user_notice_phid, 'PHID-PROJ-y6egyt5y4lvnzs5mgll6') 14 | -------------------------------------------------------------------------------- /cron: -------------------------------------------------------------------------------- 1 | 15 * * * * jsub -once -N column_mover python3 /data/project/phabbot/phabbot/column_mover.py /data/project/phabbot/phabbot/creds.json 3600 >/dev/null 2>&1 2 | 45 * * * * jsub -once -N project_grouper python3 /data/project/phabbot/phabbot/project_grouper.py /data/project/phabbot/phabbot/creds.json 3600 >/dev/null 2>&1 3 | 10 * * * * jsub -once -N patch_for_review python3 /data/project/phabbot/phabbot/patchforreview_remover.py /data/project/phabbot/phabbot/creds.json 3600 >/dev/null 2>&1 4 | 5 * * * * jlocal bash /data/project/phabbot/phabbot/updater.sh >/dev/null 2>&1 5 | 10 22,4,10,16 * * * jsub -once -N new_wikis_handler bash /data/project/phabbot/phabbot/new_wikis_handler.sh >/dev/null 2>&1 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # My credentials 2 | creds.json 3 | private_key 4 | gerrit-creds.json 5 | 6 | # Byte-compiled / optimized / DLL files 7 | __pycache__/ 8 | *.py[cod] 9 | *$py.class 10 | 11 | # C extensions 12 | *.so 13 | 14 | # Distribution / packaging 15 | .Python 16 | build/ 17 | develop-eggs/ 18 | dist/ 19 | downloads/ 20 | eggs/ 21 | .eggs/ 22 | lib/ 23 | lib64/ 24 | parts/ 25 | sdist/ 26 | var/ 27 | wheels/ 28 | *.egg-info/ 29 | .installed.cfg 30 | *.egg 31 | MANIFEST 32 | 33 | # PyInstaller 34 | # Usually these files are written by a python script from a template 35 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 36 | *.manifest 37 | *.spec 38 | 39 | # Installer logs 40 | pip-log.txt 41 | pip-delete-this-directory.txt 42 | 43 | # Unit test / coverage reports 44 | htmlcov/ 45 | .tox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *.cover 52 | .hypothesis/ 53 | .pytest_cache/ 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # Django stuff: 60 | *.log 61 | local_settings.py 62 | db.sqlite3 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # pyenv 81 | .python-version 82 | 83 | # celery beat schedule file 84 | celerybeat-schedule 85 | 86 | # SageMath parsed files 87 | *.sage.py 88 | 89 | # Environments 90 | .env 91 | .venv 92 | env/ 93 | venv/ 94 | ENV/ 95 | env.bak/ 96 | venv.bak/ 97 | 98 | # Spyder project settings 99 | .spyderproject 100 | .spyproject 101 | 102 | # Rope project settings 103 | .ropeproject 104 | 105 | # mkdocs documentation 106 | /site 107 | 108 | # mypy 109 | .mypy_cache/ 110 | 111 | .idea/ 112 | *.iml 113 | -------------------------------------------------------------------------------- /column_mover.py: -------------------------------------------------------------------------------- 1 | from lib import Client 2 | 3 | 4 | class Checker(): 5 | def __init__(self, work, client): 6 | self.work = work 7 | self.client = client 8 | 9 | def phid_check(self, phid): 10 | if self.work.get('projects'): 11 | return self.phid_check_project( 12 | phid, [ 13 | self.client.lookupPhid( 14 | '#' + i) for i in self.work['projects']]) 15 | if self.work.get('status'): 16 | return self.phid_check_status(phid, self.work['status']) 17 | return False 18 | 19 | def phid_check_project(self, phid, project_phids): 20 | taskDetails = self.client.taskDetails(phid) 21 | for project_phid in project_phids: 22 | if project_phid in taskDetails['projectPHIDs']: 23 | return True 24 | return False 25 | 26 | def phid_check_status(self, phid, statuses): 27 | taskDetails = self.client.taskDetails(phid) 28 | return taskDetails['statusName'] in statuses 29 | 30 | 31 | client = Client.newFromCreds() 32 | 33 | work = [{'from': ['incoming'], 34 | 'project': 'Wikidata', 35 | 'to': 'in progress', 36 | 'projects': ['wikidata-campsite-iteration-∞', 37 | 'Wikibase_Extension_Decoupling_and_Registration', 38 | 'wikidata-bridge-sprint-8']}, 39 | {'from': ['Test (Verification)'], 40 | 'project': 'wikidata-campsite-iteration-∞', 41 | 'to': 'Done', 42 | 'status': ['Resolved']}, 43 | {'from': ['Inbox','Investigate & Discuss','Blocked','Goals','To Prioritize','Triaged Low (0-50)', 'Triaged Medium (50+)','Triaged Big','Active','Subtasks'], 44 | 'project': 'wdwb-tech', 45 | 'to': 'Sorted Team A', 46 | 'projects': ['wmde-team-a-tech']}, 47 | {'from': ['Inbox','Investigate & Discuss','Blocked','Goals','To Prioritize','Triaged Low (0-50)', 'Triaged Medium (50+)','Triaged Big','Active','Subtasks'], 48 | 'project': 'wdwb-tech', 49 | 'to': 'Sorted Team B', 50 | 'projects': ['wmde-team-b-tech']}, 51 | {'from': ['In progress'], 52 | 'project': 'DBA', 53 | 'to': 'Done', 54 | 'status': ['Resolved']}, 55 | {'from': ['Radar', 56 | 'Extensions & Core', 57 | 'Configuration'], 58 | 'project': 'User-RhinosF1', 59 | 'to': 'Done', 60 | 'status': ['Resolved']}, 61 | {'from': ['Backlog', 62 | 'Language conversion', 63 | 'Site configuration'], 64 | 'project': 'Bengali-Sites', 65 | 'to': 'Done', 66 | 'status': ['Resolved']}, 67 | {'from': ['New Tasks', 68 | 'Backlog', 69 | 'Prioritized'], 70 | 'project': 'growthexperiments-mentorship', 71 | 'to': 'In Progress', 72 | 'projects': ['growth-team-current-sprint']}, 73 | {'from': ['Incoming', 74 | 'Radar', 75 | 'Other Projects', 76 | '[DOT] By Project', 77 | '[DOT] Prioritized', 78 | '[DOT] Epics + Stalled' 79 | '[QT] By Project', 80 | '[QT] Prioritized', 81 | '[QT] Epics + Stalled'], 82 | 'project': 'wmde-wikidata-tech', 83 | 'to': 'Ongoing', 84 | 'projects': [ 85 | 'wikidata_dev_team_wikidata.org', 86 | 'wikidata_dev_team_quality_tools', 87 | 'wikidata_dev_team_sprint']} 88 | ] 89 | for case in work: 90 | gen = client.getTasksWithProject(client.lookupPhid('#' + case['project'])) 91 | checker = Checker(case, client) 92 | columns = client.getColumns(client.lookupPhid('#' + case['project'])) 93 | mapping = {} 94 | for column in columns['data']: 95 | mapping[column['fields']['name']] = column['phid'] 96 | for phid in gen: 97 | if checker.phid_check(phid): 98 | project_phid = client.lookupPhid('#' + case['project']) 99 | currentColumnName = client.getTaskColumns( 100 | phid)['boards'][project_phid]['columns'][0]['name'] 101 | if currentColumnName not in case['from']: 102 | continue 103 | try: 104 | print(phid) 105 | client.moveColumns(phid, mapping[case['to']]) 106 | except KeyboardInterrupt: 107 | continue 108 | -------------------------------------------------------------------------------- /patch_makers.py: -------------------------------------------------------------------------------- 1 | import json 2 | from datetime import date 3 | 4 | from gerrit import GerritBot 5 | 6 | 7 | class WikimediaMessagesPatchMaker(GerritBot): 8 | def __init__(self, db_name, english_name, url, lang, bug_id): 9 | self.db_name = db_name 10 | self.english_name = english_name 11 | self.wiki_url = url 12 | self.wiki_lang = lang 13 | super().__init__( 14 | 'mediawiki/extensions/WikimediaMessages', 15 | 'Add messages for {} ({})\n\nBug:{}'.format( 16 | english_name, db_name, bug_id) 17 | ) 18 | 19 | def changes(self): 20 | file_ = 'i18n/wikimediaprojectnames/en.json' 21 | result = self._read_json(file_) 22 | result['project-localized-name-' + self.db_name] = self.english_name 23 | self._write_json(file_, result) 24 | 25 | file_ = 'i18n/wikimediaprojectnames/qqq.json' 26 | result = self._read_json(file_) 27 | result['project-localized-name-' + self.db_name] = '{{ProjectNameDocumentation|url=https://' + \ 28 | self.wiki_url + '|name=' + self.english_name + \ 29 | '|language=' + self.wiki_lang + '}}' 30 | self._write_json(file_, result) 31 | 32 | if not 'wikipedia' in self.wiki_url: 33 | return 34 | 35 | file_ = 'i18n/wikimediainterwikisearchresults/en.json' 36 | result = self._read_json(file_) 37 | result['search-interwiki-results-' + 38 | self.db_name] = 'Showing results from [[:{}:|{}]].'.format(self.wiki_lang, self.english_name) 39 | self._write_json(file_, result) 40 | 41 | file_ = 'i18n/wikimediainterwikisearchresults/qqq.json' 42 | result = self._read_json(file_) 43 | result['search-interwiki-results-' + self.db_name] = 'Search results description for ' + \ 44 | self.english_name + '.\n{{LanguageNameTip|' + self.wiki_lang + '}}' 45 | self._write_json(file_, result) 46 | 47 | def _read_json(self, path): 48 | with open(path, 'r') as f: 49 | result = json.load(f) 50 | return result 51 | 52 | def _write_json(self, path, content): 53 | with open(path, 'w') as f: 54 | f.write(json.dumps(content, ensure_ascii=False, 55 | indent='\t', sort_keys=True) + '\n') 56 | 57 | 58 | class DnsPatchMaker(GerritBot): 59 | def __init__(self, lang, bug_id): 60 | self.wiki_lang = lang 61 | super().__init__( 62 | 'operations/dns', 63 | 'Add {} to langlist helper\n\nBug:{}'.format(lang, bug_id) 64 | ) 65 | 66 | def changes(self): 67 | with open('templates/helpers/langlist.tmpl', 'r') as f: 68 | lines = f.read().split('\n') 69 | header = [] 70 | langs = [] 71 | footer = [] 72 | for line in lines: 73 | if not line.startswith(' '): 74 | if not header: 75 | header.append(line) 76 | else: 77 | footer.append(line) 78 | else: 79 | langs.append(line) 80 | langs.append(" '{}',".format(self.wiki_lang)) 81 | langs.sort() 82 | with open('templates/helpers/langlist.tmpl', 'w') as f: 83 | f.write('\n'.join(header) + '\n' + 84 | '\n'.join(langs) + '\n' + '\n'.join(footer)) 85 | 86 | 87 | class CxPatchMaker(GerritBot): 88 | def __init__(self, lang, bug_id): 89 | self.wiki_lang = lang 90 | super().__init__( 91 | 'mediawiki/services/cxserver', 92 | 'Add {} to languages \n\nBug:{}'.format(lang, bug_id) 93 | ) 94 | 95 | def changes(self): 96 | with open('config/languages.yaml', 'r') as f: 97 | lines = f.read().split('\n')[:-1] 98 | lines.append("- {}".format(self.wiki_lang)) 99 | lines.sort() 100 | with open('config/languages.yaml', 'w') as f: 101 | f.write('\n'.join(lines) + '\n') 102 | 103 | 104 | class AnalyticsPatchMaker(GerritBot): 105 | def __init__(self, project, bug_id): 106 | self.project = project 107 | super().__init__( 108 | 'analytics/refinery', 109 | 'Add {} to pageview allowlist \n\nBug:{}'.format(project, bug_id) 110 | ) 111 | 112 | def changes(self): 113 | with open('static_data/pageview/allowlist/allowlist.tsv', 'r') as f: 114 | lines = f.read().split('\n') 115 | projects = [] 116 | non_projects = [] 117 | for line in lines: 118 | if line.startswith('project'): 119 | projects.append(line) 120 | else: 121 | non_projects.append(line) 122 | today = date.today() 123 | projects.append('project\t{}\t{}'.format( 124 | self.project, 125 | today.strftime("%Y-%m-%d 00:00:00") 126 | )) 127 | projects = list(set(projects)) 128 | projects.sort() 129 | with open('static_data/pageview/allowlist/allowlist.tsv', 'w') as f: 130 | f.write('\n'.join(projects) + '\n' + '\n'.join(non_projects)) 131 | -------------------------------------------------------------------------------- /gerrit.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright (C) 2019 Kunal Mehta 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU Affero General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU Affero General Public License for more details. 13 | You should have received a copy of the GNU Affero General Public License 14 | along with this program. If not, see . 15 | """ 16 | 17 | import json 18 | import os 19 | import subprocess 20 | import tempfile 21 | import urllib 22 | from contextlib import contextmanager 23 | 24 | 25 | dir_path = os.path.dirname(os.path.realpath(__file__)) 26 | with open(os.path.join(dir_path, 'gerrit-creds.json'), 'r') as f: 27 | creds = json.loads(f.read()) 28 | 29 | 30 | @contextmanager 31 | def cd(dirname): 32 | cwd = os.getcwd() 33 | os.chdir(dirname) 34 | try: 35 | yield dirname 36 | finally: 37 | os.chdir(cwd) 38 | 39 | 40 | def gerrit_url(repo: str, user=None, ssh=False, password=None) -> str: 41 | if user is not None: 42 | prefix = user 43 | if password is not None: 44 | prefix += ':' + password 45 | prefix += '@' 46 | else: 47 | prefix = '' 48 | if ssh: 49 | return 'ssh://{}gerrit.wikimedia.org:29418/{}'.format(prefix, repo) 50 | else: 51 | return 'https://{}gerrit.wikimedia.org/r/{}.git'.format(prefix, repo) 52 | 53 | 54 | class ShellMixin: 55 | def check_call(self, args: list, stdin='', env=None, 56 | ignore_returncode=False) -> str: 57 | debug = self.log if hasattr(self, 'log') else print 58 | #debug('$ ' + ' '.join(args) + ' env: ' + str(env)) 59 | env = None 60 | res = subprocess.run( 61 | args, 62 | input=stdin.encode(), 63 | stdout=subprocess.PIPE, 64 | stderr=subprocess.STDOUT, 65 | env=env 66 | ) 67 | debug(res.stdout.decode()) 68 | if not ignore_returncode: 69 | res.check_returncode() 70 | return res.stdout.decode() 71 | 72 | def clone(self, repo): 73 | url = gerrit_url(repo, user=creds['name']) 74 | self.check_call(['git', 'clone', url, 'repo', '--depth=1']) 75 | os.chdir('repo') 76 | self.check_call(['git', 'config', 'user.name', creds['name']]) 77 | self.check_call(['git', 'config', 'user.email', creds['email']]) 78 | self.check_call(['git', 'submodule', 'update', '--init']) 79 | self.check_call(['mkdir', '-p', '.git/hooks']) 80 | self.check_call(['curl', '-Lo', '.git/hooks/commit-msg', 'https://gerrit.wikimedia.org/r/tools/hooks/commit-msg']) 81 | self.check_call(['chmod', '+x', '.git/hooks/commit-msg']) 82 | 83 | def build_push_command(self, options: dict, ticket='') -> list: 84 | per = '%topic=lsc' 85 | if ticket: 86 | per += '-' + ticket 87 | for hashtag in options.get('hashtags', []): 88 | per += ',t=' + hashtag 89 | if options.get('vote'): 90 | per += ',l=' + options['vote'] 91 | # If we're not automerging, vote V+1 to trigger jenkins (T254070) 92 | if options.get('message'): 93 | per += ',m=' + urllib.parse.quote_plus(options['message']) 94 | branch = options.get('branch', 'master') 95 | return ['git', 'push', 96 | gerrit_url(options['repo'], creds['name'], password=creds['password']), 97 | 'HEAD:refs/for/' + branch + per] 98 | 99 | 100 | class GerritBot(ShellMixin): 101 | def __init__(self, name, commit_message): 102 | self.name = name 103 | self.commit_message = commit_message 104 | 105 | def run(self): 106 | with tempfile.TemporaryDirectory() as tmpdirname: 107 | with cd(tmpdirname): 108 | self.clone(self.name) 109 | self.changes() 110 | self.commit() 111 | 112 | def changes(self): 113 | files = [ 114 | 'i18n/wikimediaprojectnames/en.json', 115 | 'i18n/wikimediaprojectnames/qqq.json' 116 | ] 117 | for file_ in files: 118 | with open(file_, 'r') as f: 119 | result = json.load(f) 120 | with open(file_, 'w') as f: 121 | f.write(json.dumps(result, ensure_ascii=False, 122 | indent='\t', sort_keys=True)) 123 | 124 | def commit(self): 125 | self.check_call(['git', 'add', '.']) 126 | with open('.git/COMMIT_EDITMSG', 'w') as f: 127 | f.write(self.commit_message) 128 | self.check_call(['git', 'commit', '-F', '.git/COMMIT_EDITMSG']) 129 | self.check_call( 130 | self.build_push_command({'repo': self.name}) 131 | ) 132 | 133 | 134 | if __name__ == "__main__": 135 | gerritbot = GerritBot( 136 | 'mediawiki/extensions/WikimediaMessages', 137 | "Order entries by alphabetical order\n\nThis would make creating automated patches easier") 138 | gerritbot.run() 139 | -------------------------------------------------------------------------------- /patchforreview_remover.py: -------------------------------------------------------------------------------- 1 | import re 2 | import time 3 | from collections import defaultdict 4 | 5 | from lib import Client 6 | 7 | 8 | class Checker(): 9 | def __init__(self, gerrit_bot_phid, code_review_bot_phid, project_patch_for_review_phid, client): 10 | self.gerrit_bot_phid = gerrit_bot_phid 11 | self.code_review_bot_phid = code_review_bot_phid 12 | self.project_patch_for_review_phid = project_patch_for_review_phid 13 | self.client = client 14 | 15 | def check(self, t_id): 16 | """ 17 | Returns true if the Patch-For-Review project should be removed from the Phabricator 18 | task identified 't_id'. 19 | """ 20 | phid = self.client.lookupPhid(t_id) 21 | return self.phid_check(phid) 22 | 23 | def get_change_url(self, raw_comment): 24 | m = re.search(r'https://gerrit(?:-test|)\.wikimedia\.org/r/\d+', raw_comment) 25 | if m: 26 | return m[0] 27 | m = re.search(r'https://gitlab\.wikimedia\.org/repos/.*/-/merge_requests/\d+', raw_comment) 28 | if m: 29 | return m[0] 30 | return None 31 | 32 | def get_operation_type(self, raw_comment, url): 33 | """ 34 | If the operation type can be determined from raw_comment, return 35 | it. It will be the string "open" (first patchset created or merge 36 | request created) or "close" (merge or abandon) 37 | """ 38 | # Gitlab style 39 | if re.search(r"opened " + re.escape(url), raw_comment): 40 | return "open" 41 | 42 | if re.search(r"(merged|closed) " + re.escape(url), raw_comment): 43 | return "close" 44 | 45 | # Gerrit style 46 | if re.search(r"Change \d+ had a related patch set uploaded", raw_comment): 47 | return "open" 48 | 49 | if re.search(r'Change \d+ \*\*(?:merged|abandoned)\*\* by ', raw_comment): 50 | return "close" 51 | 52 | return None 53 | 54 | def phid_check(self, phid) -> bool: 55 | """ 56 | Returns true if the Patch-For-Review project should be removed from the Phabricator 57 | task identified by 'phid'. 58 | """ 59 | gerrit_bot_actions = [] 60 | 61 | # Note that transactions are returned in reverse chronological order (most recent first). 62 | for transaction in self.client.getTransactions(phid): 63 | if re.findall(re.escape('https://github.com/') + r'.+?/pull', str(transaction)): 64 | return False 65 | if transaction['authorPHID'] in [self.gerrit_bot_phid, self.code_review_bot_phid]: 66 | gerrit_bot_actions.append(transaction) 67 | else: 68 | # If someone other than GerritBot adds the Patch-For-Review project, don't 69 | # auto-remove it. 70 | if transaction['type'] == 'projects': 71 | check = self.project_patch_for_review_phid in str( 72 | transaction['fields']) 73 | add_check = "'add'" in str(transaction['fields']) 74 | if check and add_check: 75 | return False 76 | 77 | gerrit_patch_status = defaultdict(list) 78 | for case in gerrit_bot_actions: 79 | if case['type'] != 'comment': 80 | continue 81 | 82 | if len(case['comments']) != 1: 83 | return False 84 | raw_comment = case['comments'][0]['content']['raw'] 85 | 86 | change_url = self.get_change_url(raw_comment) 87 | if change_url: 88 | op = self.get_operation_type(raw_comment, change_url) 89 | 90 | # Append True or False depending on whether the action was to 91 | # open/reopen a change (True) or merge a change (False) 92 | gerrit_patch_status[change_url].append(op in ["open", "reopen"]) 93 | 94 | for patch in gerrit_patch_status: 95 | # The normal sequence of GerritBot transactions for a Gerrit change is "Change 96 | # \d+ had a related patch set uploaded" (indicated by True in 97 | # gerrit_patch_status) eventually followed by "Change \d+ (merged|abandoned) 98 | # by whoever" (indicated by False in gerrit_patch_status). The transactions 99 | # are returned in reverse order so the opened/merged pattern will appear as 100 | # the reverse of [True, False], which is [False, True]. 101 | # FIXME: This logic can't handle a open/close/reopen/merge situation. 102 | if gerrit_patch_status[patch] != [False, True]: 103 | return False 104 | return True 105 | 106 | if __name__ == "__main__": 107 | client = Client.newFromCreds() 108 | 109 | gerrit_bot_phid = 'PHID-USER-idceizaw6elwiwm5xshb' 110 | code_review_bot_phid = 'PHID-USER-ckazlx2gejbyo75y6lid' 111 | project_patch_for_review_phid = 'PHID-PROJ-onnxucoedheq3jevknyr' 112 | checker = Checker( 113 | gerrit_bot_phid, 114 | code_review_bot_phid, 115 | project_patch_for_review_phid, 116 | client) 117 | gen = client.getTasksWithProject(project_patch_for_review_phid) 118 | for phid in gen: 119 | if checker.phid_check(phid): 120 | print(client.taskDetails(phid)['id']) 121 | try: 122 | client.removeProjectByPhid(project_patch_for_review_phid, phid) 123 | except BaseException: 124 | continue 125 | time.sleep(10) 126 | -------------------------------------------------------------------------------- /lib.py: -------------------------------------------------------------------------------- 1 | import json 2 | import sys 3 | import time 4 | import os 5 | 6 | import requests 7 | 8 | 9 | class Client(object): 10 | """Phabricator client""" 11 | 12 | def __init__(self, url, username, key): 13 | self.url = url 14 | self.username = username # Unused 15 | self.column_cache = {} 16 | self.phid_cache = {} 17 | self.session = { 18 | 'token': key, 19 | } 20 | 21 | @classmethod 22 | def newFromCreds(cls): 23 | dir_path = os.path.dirname(os.path.realpath(__file__)) 24 | with open(os.path.join(dir_path, 'creds.json'), 'r') as f: 25 | creds = json.loads(f.read()) 26 | return cls(*creds) 27 | 28 | def post(self, path, data): 29 | data['__conduit__'] = self.session 30 | r = requests.post('%s/api/%s' % (self.url, path), data={ 31 | 'params': json.dumps(data), 32 | 'output': 'json', 33 | }) 34 | resp = r.json() 35 | if resp['error_code'] is not None: 36 | raise Exception(resp['error_info']) 37 | return resp['result'] 38 | 39 | def lookupPhid(self, label): 40 | """Lookup information on a Phab object by name.""" 41 | if not self.phid_cache.get(label): 42 | r = self.post('phid.lookup', {'names': [label]}) 43 | if label in r and 'phid' in r[label]: 44 | obj = r[label]['phid'] 45 | self.phid_cache[label] = obj 46 | else: 47 | raise Exception('No object found for %s' % label) 48 | return self.phid_cache[label] 49 | 50 | def getSubprojects(self, phid): 51 | """Lookup information on a Phab object by name.""" 52 | r = self.post('project.search', {'constraints': {'isMilestone': True, 'ancestors': [phid]}}) 53 | return [i['phid'] for i in r['data']] 54 | 55 | def getColumns(self, project_phid): 56 | if not self.column_cache.get(project_phid): 57 | self.column_cache[project_phid] = self.post( 58 | 'project.column.search', { 59 | "constraints": { 60 | "projects": [project_phid]}}) 61 | return self.column_cache[project_phid] 62 | 63 | def moveColumns(self, task_phid, to_column): 64 | self.post('maniphest.edit', { 65 | 'objectIdentifier': task_phid, 66 | 'transactions': [{ 67 | 'type': 'column', 68 | 'value': [to_column], 69 | }] 70 | }) 71 | 72 | def setTaskDescription(self, task_phid, new_desc): 73 | self.post('maniphest.edit', { 74 | 'objectIdentifier': task_phid, 75 | 'transactions': [{ 76 | 'type': 'description', 77 | 'value': new_desc, 78 | }] 79 | }) 80 | 81 | def addTaskProject(self, task_phid, project_phid): 82 | self.post('maniphest.edit', { 83 | 'objectIdentifier': task_phid, 84 | 'transactions': [{ 85 | 'type': 'projects.add', 86 | 'value': [project_phid], 87 | }] 88 | }) 89 | 90 | def createSubtask(self, desc, project_phids, parent_phid, title): 91 | self.post('maniphest.edit', { 92 | 'objectIdentifier': '', 93 | 'transactions': [{ 94 | 'type': 'parent', 95 | 'value': parent_phid 96 | }, 97 | { 98 | 'type': 'title', 99 | 'value': title 100 | }, 101 | { 102 | 'type': 'description', 103 | 'value': desc, 104 | }, 105 | { 106 | 'type': 'projects.add', 107 | 'value': project_phids 108 | }] 109 | }) 110 | 111 | def createParentTask(self, desc, project_phids, subtask_phid, title): 112 | return self.post('maniphest.edit', { 113 | 'objectIdentifier': '', 114 | 'transactions': [{ 115 | 'type': 'subtasks.add', 116 | 'value': [subtask_phid] 117 | }, 118 | { 119 | 'type': 'title', 120 | 'value': title 121 | }, 122 | { 123 | 'type': 'description', 124 | 'value': desc, 125 | }, 126 | { 127 | 'type': 'projects.add', 128 | 'value': project_phids 129 | }] 130 | }) 131 | 132 | def taskDetails(self, phid): 133 | """Lookup details of a Maniphest task.""" 134 | r = self.post('maniphest.query', {'phids': [phid]}) 135 | if phid in r: 136 | return r[phid] 137 | raise Exception('No task found for phid %s' % phid) 138 | 139 | def getTransactions(self, phid): 140 | r = self.post('transaction.search', {'objectIdentifier': phid}) 141 | if 'data' in r: 142 | return r['data'] 143 | raise Exception('No transaction found for phid %s' % phid) 144 | 145 | def removeProject(self, project_phid, task): 146 | return self.removeProjectByPhid(project_phid, self.lookupPhid(task)) 147 | 148 | def removeProjectByPhid(self, project_phid, task_phid): 149 | self.post('maniphest.edit', { 150 | 'objectIdentifier': task_phid, 151 | 'transactions': [{ 152 | 'type': 'projects.remove', 153 | 'value': [project_phid], 154 | }] 155 | }) 156 | 157 | def changeProjectByPhid(self, task_phid, old_project_phid, new_project_phid): 158 | return self.post('maniphest.edit', { 159 | 'objectIdentifier': task_phid, 160 | 'transactions': [{ 161 | 'type': 'projects.remove', 162 | 'value': [old_project_phid], 163 | }, 164 | { 165 | 'type': 'projects.add', 166 | 'value': [new_project_phid], 167 | } 168 | ] 169 | 170 | }) 171 | 172 | def getTasksWithProject(self, project_phid, continue_=None, statuses=None): 173 | r = self._getTasksWithProjectContinue( 174 | project_phid, continue_, statuses=statuses) 175 | cursor = r['cursor'] 176 | for case in r['data']: 177 | if case['type'] != 'TASK': 178 | continue 179 | yield case['phid'] 180 | if cursor.get('after'): 181 | for case in self.getTasksWithProject( 182 | project_phid, cursor['after'], statuses=statuses): 183 | yield case 184 | 185 | def getInactiveTasksWithProject(self, project_phid, inactive_for=864000, statuses=['resolved'], columns=[]): 186 | params = { 187 | 'limit': 100, 188 | 'constraints': { 189 | 'projects': [project_phid], 190 | 'statuses': statuses, 191 | "modifiedEnd": int(time.time() - inactive_for), 192 | 'columnPHIDs': columns, 193 | } 194 | } 195 | r = self.post('maniphest.search', params) 196 | for case in r['data']: 197 | if case['type'] != 'TASK': 198 | continue 199 | yield case['phid'] 200 | 201 | def _getTasksWithProjectContinue(self, project_phid, continue_=None, statuses=None): 202 | params = { 203 | 'limit': 100, 204 | 'constraints': { 205 | 'projects': [project_phid], 206 | "modifiedStart": int(time.time() - int(sys.argv[2])) 207 | } 208 | } 209 | if continue_: 210 | params['after'] = continue_ 211 | if statuses: 212 | params['constraints']['statuses'] = statuses 213 | return self.post('maniphest.search', params) 214 | 215 | def getTaskColumns(self, phid): 216 | params = { 217 | "attachments": { 218 | "columns": {"boards": {"columns": True}} 219 | }, 220 | "constraints": { 221 | "phids": [phid] 222 | } 223 | } 224 | return self.post('maniphest.search', params)[ 225 | 'data'][0]['attachments']['columns'] 226 | 227 | def getTaskSubtasks(self, phid): 228 | params = { 229 | "constraints": { 230 | "phids": [phid], 231 | "hasSubtasks": True 232 | } 233 | } 234 | return self.post('maniphest.search', params)[ 235 | 'data'] 236 | 237 | def getTaskName(self, keyword): 238 | params = { 239 | "constraints": { 240 | "query": keyword 241 | } 242 | } 243 | return self.post('maniphest.search', params)[ 244 | 'data'] 245 | 246 | def getTaskParents(self, phid): 247 | params = { 248 | "constraints": { 249 | "phids": [phid], 250 | "hasParents": True 251 | } 252 | } 253 | return self.post('maniphest.search', params)[ 254 | 'data'] 255 | -------------------------------------------------------------------------------- /project_grouper.py: -------------------------------------------------------------------------------- 1 | """ 2 | Adds tasks in configured projects to other configured projects 3 | """ 4 | 5 | from lib import Client 6 | 7 | # To get it on a list run this on herald rule page 8 | # const items = document.getElementsByClassName('herald-list-item')[0].getElementsByClassName('phui-handle') 9 | # for (i in items) {console.log(items[i].text)}; 10 | rules = [ 11 | { 12 | # H175 - see T136921 13 | 'add': 'Design', 14 | 'in': ['WMF-Design', 'WMDE-Design'], 15 | }, 16 | { 17 | # H232 18 | 'add': 'artificial-intelligence', 19 | 'in': ['editquality-modeling', 'draftquality-modeling', 'articlequality-modeling', 'revscoring'], 20 | }, 21 | { 22 | # H193 - see T146701 23 | 'add': 'accessibility', 24 | 'in': ['ios-app-feature-accessibility'], 25 | }, 26 | { 27 | # H174 28 | 'add': 'upstream', 29 | 'in': ['phabricator-upstream'], 30 | }, 31 | { 32 | # H24 - see T86536 33 | 'add': 'universallanguageselector', 34 | 'in': ['uls-compactlinks'], 35 | }, 36 | { 37 | # H15 - note that #producrement tasks are private -> rule can't be disabled 38 | 'add': 'SRE', 39 | 'in': [ 40 | 'ops-eqiad', 41 | 'ops-codfw', 42 | 'ops-esams', 43 | 'ops-ulsfo', 44 | # 'hardware-requests', archived project 45 | 'SRE-Access-Requests', 46 | 'netops', 47 | 'vm-requests', 48 | 'Traffic', 49 | 'ops-eqord', 50 | 'ops-eqdfw', 51 | # 'procurement', always in S4 52 | 'ops-eqsin', 53 | 'DNS', 54 | 'LDAP-Access-Requests', 55 | 'Wikimedia-Mailing-lists', 56 | ], 57 | 'once': True 58 | }, 59 | { 60 | # H14 - see T85596 61 | 'add': 'Social-Tools', 62 | 'in': [ 63 | 'BlogPage', 64 | 'Challenge', 65 | 'Comments', 66 | 'FanBoxes', 67 | 'ImageRating', 68 | 'LinkFilter', 69 | 'MiniInvite', 70 | 'NewSignupPage', 71 | # 'NewUsersList', archived project 72 | 'PictureGame', 73 | 'PollNY', 74 | 'QuizGame', 75 | # 'RandomFeaturedUser', archived project 76 | 'RandomGameUnit', 77 | # 'RandomUsersWithAvatars', archived project 78 | 'SocialProfile', 79 | 'SiteMetrics', 80 | 'SportsTeams', 81 | # 'TopLists', archived project 82 | 'video_non-wmf', 83 | 'VoteNY', 84 | 'WikiForum', 85 | 'WikiTextLoggedInOut', 86 | ], 87 | }, 88 | { 89 | # H10 - see T76954 90 | 'add': 'VisualEditor', 91 | 'in': [ 92 | 'VisualEditor-ContentEditable', 93 | 'VisualEditor-ContentLanguage', 94 | 'VisualEditor-CopyPaste', 95 | 'VisualEditor-DataModel', 96 | 'VisualEditor-EditingTools', 97 | 'VisualEditor-Initialisation', 98 | 'VisualEditor-InterfaceLanguage', 99 | 'VisualEditor-MediaWiki', 100 | 'VisualEditor-MediaWiki-Links', 101 | 'VisualEditor-MediaWiki-Media', 102 | 'VisualEditor-MediaWiki-Mobile', 103 | 'VisualEditor-MediaWiki-References', 104 | 'VisualEditor-MediaWiki-Templates', 105 | 'VisualEditor-Performance', 106 | 'VisualEditor-Tables', 107 | 'TemplateData', 108 | 'VisualEditor-MediaWiki-Plugins', 109 | 'VisualEditor-LanguageTool', 110 | 'VisualEditor-Links', 111 | 'VisualEditor-Media', 112 | 'VisualEditor-MediaWiki-2017WikitextEditor', 113 | 'VisualEditor-VisualDiffs', 114 | ], 115 | }, 116 | { 117 | # H30 118 | 'add': 'wikidata', 119 | 'in': [ 120 | 'Wikibase-Quality-Constraints', 121 | 'DataValues', 122 | 'DataValues-JavaScript', 123 | 'MediaWiki-extensions-WikibaseClient', 124 | 'MediaWiki-extensions-WikibaseView', 125 | 'Wikibase-DataModel', 126 | 'Wikibase-DataModel-JavaScript', 127 | 'Wikibase-DataModel-Serialization', 128 | 'Wikibase-Internal-Serialization', 129 | 'Wikibase-JavaScript-Api', 130 | 'Wikibase-Serialization-JavaScript', 131 | 'Wikidata-Query-Service', 132 | 'Tool-Wikidata-Periodic-Table', 133 | 'Wikidata.org', 134 | 'DataTypes', 135 | 'MediaWiki-extensions-WikibaseRepository', 136 | 'SDC General', 137 | 'ValueView', 138 | 'Wikidata-Gadgets', 139 | 'ArticlePlaceholder', 140 | 'Wikidata Lexicographical data', 141 | 'Automated list generation', 142 | 'Wikidata Query UI', 143 | 'Wikibase-Containers', 144 | 'Soweego', 145 | 'Wikidata Mobile', 146 | 'Wikidata-Campsite', 147 | 'Wikibase-registry', 148 | 'wikiba.se website', 149 | 'Wikibase-Lua', 150 | 'MediaWiki-extensions-PropertySuggester', 151 | 'Wikidata-Campsite (Wikidata-Campsite-Iteration-∞)', 152 | 'RL Module Terminators Trailblazing', 153 | 'Wikidata-Bridge', 154 | 'Shape Expressions', 155 | 'Wikidata Tainted References', 156 | 'Wikidata Design System', 157 | 'Wikidata - Reference Treasure Hunt', 158 | 'Item Quality Scoring Improvement', 159 | 'Wikibase - Automated Configuration Detection (WikibaseManifest)', 160 | 'Wikidata Query Builder', 161 | 'Wikidata - Visualisation of Reliability Metrics', 162 | 'Item Quality Evaluator', 163 | 'wdwb-tech', 164 | 'Cognate', 165 | 'Mismatch Finder', 166 | 'Wikidata analytics', 167 | 'Wikidata-Termbox', 168 | 'Special:NewLexeme revival', 169 | 'Wikidata Dev Team', 170 | 'Wikidata data quality and trust', 171 | 'Wikidata-UX', 172 | 'Wikidata Integration in Wikimedia projects', 173 | ], 174 | 'once': True 175 | }, 176 | { 177 | 'add': 'Wikidata Lexicographical data', 178 | 'in': [ 179 | 'Special:NewLexeme revival', 180 | ], 181 | 'once': True 182 | }, 183 | { 184 | # H337 185 | 'add': 'Research', 186 | 'in': [ 187 | 'address-knowledge-gaps', 188 | 'Research-foundational', 189 | 'Knowledge-Integrity', 190 | ], 191 | 'once': True 192 | }, 193 | { 194 | # H314 195 | 'add': 'Pywikibot', 196 | 'in': [ 197 | 'Pywikibot-archivebot.py', 198 | 'Pywikibot-category.py', 199 | 'Pywikibot-compat', 200 | 'Pywikibot-copyright.py', 201 | 'Pywikibot-delinker.py', 202 | 'Pywikibot-cosmetic-changes.py', 203 | 'Pywikibot-Documentation', 204 | 'Pywikibot-General', 205 | 'Pywikibot-i18n', 206 | 'Pywikibot-interwiki.py', 207 | 'Pywikibot-login.py', 208 | 'Pywikibot-network', 209 | 'Pywikibot-Scripts', 210 | 'Pywikibot-pagegenerators.py', 211 | 'Pywikibot-redirect.py', 212 | 'Pywikibot-replace.py', 213 | 'Pywikibot-solve-disambiguation.py', 214 | 'Pywikibot-tests', 215 | 'Pywikibot-textlib.py', 216 | 'Pywikibot-weblinkchecker.py', 217 | 'Pywikibot-Wikidata', 218 | 'Pywikibot-xmlreader.py', 219 | ], 220 | 'once': True 221 | }, 222 | { 223 | # H285 224 | 'add': 'Product-Analytics', 225 | 'in': [ 226 | 'Discovery-Analysis', 227 | ], 228 | 'once': True 229 | }, 230 | { 231 | # H216 232 | 'add': 'WMDE-FUN-Team', 233 | 'in': [ 234 | 'WMDE-Fundraising-Tech', 235 | ], 236 | 'once': True 237 | }, 238 | { 239 | # H131 240 | 'add': 'Traffic', 241 | 'in': [ 242 | 'HTTPS', 243 | 'DNS', 244 | 'Domains', 245 | ], 246 | 'once': True 247 | }, 248 | { 249 | # H131 250 | 'add': 'Traffic', 251 | 'in': [ 252 | 'HTTPS', 253 | 'DNS', 254 | 'Domains', 255 | ], 256 | 'once': True 257 | }, 258 | { 259 | # H109 260 | 'add': 'Commons', 261 | 'in': [ 262 | 'MediaWiki-File-management', 263 | 'MediaWiki-extensions-GWToolset', 264 | ], 265 | 'once': True 266 | }, 267 | { 268 | # Keep all Abstract Wikipedia work on the team board 269 | 'add': 'abstract_wikipedia', 270 | 'in': [ 271 | 'abstract_wikipedia_ux', 272 | 'wikifunctions', 273 | 'wikilambda', 274 | 'function-evaluator', 275 | 'function-orchestrator', 276 | 'function-schemata', 277 | 'tool-ducttape', 278 | ], 279 | }, 280 | { 281 | # https://phabricator.wikimedia.org/T295397 282 | 'add': 'Data-Engineering', 283 | 'in': [ 284 | 'Event-Platform', 285 | 'Analytics-Wikistats', 286 | ], 287 | 'once': True 288 | }, 289 | { 290 | 'add': 'growthexperiments-mentorship', 291 | 'in': [ 292 | 'growthexperiments-mentordashboard', 293 | 'growthexperiments-personalizedpraise' 294 | ], 295 | }, 296 | ] 297 | 298 | client = Client.newFromCreds() 299 | 300 | for rule in rules: 301 | handled_tasks = [] 302 | 303 | wanted_project_phid = client.lookupPhid('#' + rule['add'].replace(' ', '_')) 304 | subprojects = set(client.getSubprojects(wanted_project_phid) + [wanted_project_phid]) 305 | for project_name in rule['in']: 306 | project_name = project_name.replace(' ', '_') 307 | try: 308 | project_phid = client.lookupPhid('#' + project_name) 309 | except: 310 | continue 311 | for task_phid in client.getTasksWithProject(project_phid): 312 | # if a task is in multiple 'in' projects, still only process it once 313 | if task_phid in handled_tasks: 314 | continue 315 | task = client.taskDetails(task_phid) 316 | if subprojects.intersection(set(task['projectPHIDs'])): 317 | continue 318 | if rule.get('once') == True: 319 | is_already_added = False 320 | transactions = client.getTransactions(task_phid) 321 | for transaction in transactions: 322 | operations = transaction.get( 323 | 'fields', {}).get('operations', []) 324 | for operation in operations: 325 | if operation.get('operation') == 'add' and operation.get('phid') == wanted_project_phid: 326 | is_already_added = True 327 | break 328 | if is_already_added == True: 329 | continue 330 | handled_tasks.append(task_phid) 331 | client.addTaskProject(task_phid, wanted_project_phid) 332 | -------------------------------------------------------------------------------- /new_wikis_handler.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import json 3 | import re 4 | import socket 5 | 6 | import requests 7 | 8 | from lib import Client 9 | from patch_makers import (AnalyticsPatchMaker, CxPatchMaker, DnsPatchMaker, 10 | WikimediaMessagesPatchMaker) 11 | 12 | final_text = '' 13 | gerrit_path = 'https://gerrit.wikimedia.org/g/' 14 | client = Client.newFromCreds() 15 | 16 | 17 | def get_checklist_text(url, text, checked): 18 | if checked: 19 | return ' [x] [[{}|{}]]'.format(url, text) 20 | else: 21 | return ' [] [[{}|{}]]'.format(url, text) 22 | 23 | def get_file_from_gerrit(path): 24 | gerrit_url = 'https://gerrit.wikimedia.org/g/' 25 | url = gerrit_url + '{0}?format=TEXT'.format(path) 26 | r = requests.get(url) 27 | if r.status_code == 200: 28 | return base64.b64decode(r.text).decode('utf-8') 29 | else: 30 | return '' 31 | 32 | 33 | def get_gerrit_path(repo, filename): 34 | return repo + '/+/master/' + filename 35 | 36 | 37 | def get_github_url(repo, filename): 38 | return 'https://raw.githubusercontent.com/wikimedia/{}/master/{}'.format( 39 | repo, filename 40 | ) 41 | 42 | 43 | class PostCreationHandler(object): 44 | def __init__(self, phid, db_name, url, language_code, parts): 45 | self.main_pid = phid 46 | self.db_name = db_name 47 | self.url = url 48 | self.parts = parts 49 | self.language_code = language_code 50 | self.post_ticket_bug_id = '' 51 | self.post_ticket_text = '' 52 | self.checkers = [ 53 | self._check_restbase, 54 | self._check_cx, 55 | self._check_analytics, 56 | self._check_pywikibot, 57 | self._check_wikidata, 58 | ] 59 | self.handlers = [ 60 | self._handle_restbase, 61 | self._handle_cx, 62 | self._handle_analytics, 63 | self._handle_pywikibot, 64 | self._handle_wikidata, 65 | self._handle_wikistats, 66 | ] 67 | self.handlers_needed = {} 68 | 69 | def handle(self): 70 | for checker in self.checkers: 71 | checker() 72 | self.add_text(' [] Import from Incubator') 73 | self.add_text(' [] Clean up old interwiki links') 74 | self.add_text(' [] For content wikis: [[ https://meta.wikimedia.org/wiki/Stewards%27_noticeboard | ask the stewards ]] to add the wiki to the global bot policy wikiset') 75 | self.add_text(' [] Add the wiki to a CVNBot for SWMT monitoring') 76 | 77 | self._create_ticket() 78 | for handler in self.handlers: 79 | handler() 80 | 81 | def add_text(self, a): 82 | self.post_ticket_text += a + '\n' 83 | 84 | def add_checklist(self, url, text, checked): 85 | self.add_text(get_checklist_text(url, text, checked)) 86 | 87 | def _create_ticket(self): 88 | result = client.createParentTask( 89 | self.post_ticket_text, 90 | [ 91 | 'PHID-PROJ-2fuv7mxzjnpjfuojdnfd', # wiki-setup 92 | 'PHID-PROJ-2b7oz62ylk3jk4aus262', # platform-engineering 93 | 'PHID-PROJ-flkea3bsbxquupwv5g2s', # countervandalism-network 94 | ], 95 | self.main_pid, 96 | 'Post-creation work for {}'.format(self.db_name))['object'] 97 | self.post_ticket_phid = result['phid'] 98 | self.post_ticket_bug_id = 'T' + str(result['id']) 99 | 100 | def _check_restbase(self): 101 | path = get_gerrit_path( 102 | 'mediawiki/services/restbase/deploy', 103 | 'scap/vars.yaml' 104 | ) 105 | restbase = get_file_from_gerrit(path) 106 | self.add_checklist(gerrit_path + path, 'RESTbase', self.url in restbase) 107 | self.handlers_needed['restbase'] = self.url not in restbase 108 | 109 | def _handle_restbase(self): 110 | if not self.handlers_needed['restbase']: 111 | return 112 | client.createSubtask( 113 | 'Per https://wikitech.wikimedia.org/wiki/Add_a_wiki once the wiki has been created', 114 | ['PHID-PROJ-mszihytuo3ij3fcxcxgm'], 115 | self.post_ticket_phid, 116 | 'Add {} to RESTBase'.format(self.db_name)) 117 | 118 | def _check_cx(self): 119 | path = get_gerrit_path( 120 | 'mediawiki/services/cxserver', 121 | 'config/languages.yaml' 122 | ) 123 | cxconfig = get_file_from_gerrit(path) 124 | cx = '\n- ' + self.language_code in cxconfig 125 | self.add_checklist(gerrit_path + path, 'CX Config', cx) 126 | self.handlers_needed['cx'] = not cx 127 | 128 | def _handle_cx(self): 129 | if not self.handlers_needed['cx']: 130 | return 131 | r = requests.get( 132 | 'https://gerrit.wikimedia.org/r/changes/' 133 | '?q=bug:{}+project:mediawiki/services/cxserver'.format(self.post_ticket_bug_id)) 134 | b = json.loads('\n'.join(r.text.split('\n')[1:])) 135 | if b: 136 | return 137 | maker = CxPatchMaker(self.language_code, self.post_ticket_bug_id) 138 | maker.run() 139 | 140 | def _check_analytics(self): 141 | path = get_gerrit_path( 142 | 'analytics/refinery', 143 | 'static_data/pageview/allowlist/allowlist.tsv' 144 | ) 145 | url = '.'.join(self.parts[:2]) 146 | refinery_whitelist = get_file_from_gerrit(path) 147 | self.add_checklist(gerrit_path + path, 'Analytics refinery', 148 | url in refinery_whitelist) 149 | self.handlers_needed['analytics'] = url not in refinery_whitelist 150 | 151 | def _handle_analytics(self): 152 | if not self.handlers_needed['analytics']: 153 | return 154 | url = '.'.join(self.parts[:2]) 155 | r = requests.get( 156 | 'https://gerrit.wikimedia.org/r/changes/' 157 | '?q=bug:{}+project:analytics/refinery'.format(self.post_ticket_bug_id)) 158 | b = json.loads('\n'.join(r.text.split('\n')[1:])) 159 | if b: 160 | return 161 | maker = AnalyticsPatchMaker(url, self.post_ticket_bug_id) 162 | maker.run() 163 | 164 | def _check_pywikibot(self): 165 | path = get_gerrit_path( 166 | 'pywikibot/core', 167 | 'pywikibot/families/{}_family.py'.format(self.parts[1]) 168 | ) 169 | pywikibot = get_file_from_gerrit(path) 170 | self.add_checklist(gerrit_path + path, 'Pywikibot', 171 | "'{}'".format(self.language_code) in pywikibot) 172 | self.handlers_needed['pywikibot'] = "'{}'".format(self.language_code) not in pywikibot 173 | 174 | def _handle_pywikibot(self): 175 | if not self.handlers_needed['pywikibot']: 176 | return 177 | client.createSubtask( 178 | 'Per https://wikitech.wikimedia.org/wiki/Add_a_wiki once the wiki has been created', 179 | ['PHID-PROJ-orw42whe2lepxc7gghdq'], 180 | self.post_ticket_phid, 181 | 'Add support for {} to Pywikibot'.format(self.db_name)) 182 | 183 | def _check_wikidata(self): 184 | url = 'https://www.wikidata.org/w/api.php' 185 | wikidata_help_page = requests.get(url, params={ 186 | 'action': 'help', 187 | 'modules': 'wbgetentities' 188 | }).text 189 | self.add_checklist(url, 'Wikidata', self.db_name in wikidata_help_page) 190 | 191 | def _handle_wikidata(self): 192 | client.createSubtask( 193 | 'Per https://wikitech.wikimedia.org/wiki/Add_a_wiki once the wiki has been created', 194 | ['PHID-PROJ-egbmgxclscgwu2rbnotm', 'PHID-PROJ-7ocjej2gottz7cikkdc6'], 195 | self.post_ticket_phid, 196 | 'Add Wikidata support for {}'.format(self.db_name)) 197 | 198 | def _handle_wikistats(self): 199 | client.createSubtask("Please add new wiki `%s` to Wikistats, once it is created. Thanks!" % self.db_name, [ 200 | 'PHID-PROJ-6sht6g4xpdii4c4bga2i' # VPS-project-Wikistats 201 | ], self.post_ticket_phid, 'Add %s to wikistats' % self.db_name) 202 | 203 | 204 | def add_text(a): 205 | global final_text 206 | final_text += a + '\n' 207 | 208 | def add_checklist(url, text, checked): 209 | add_text(get_checklist_text(url, text, checked)) 210 | 211 | 212 | def hostname_resolves(hostname): 213 | try: 214 | socket.gethostbyname(hostname) 215 | except socket.error: 216 | return False 217 | return True 218 | 219 | 220 | def handle_special_wiki_apache(parts): 221 | file_path = 'hieradata/common/mediawiki.yaml' 222 | apache_file = get_file_from_gerrit( 223 | 'operations/puppet/+/production/' + file_path) 224 | url = '.'.join(parts) 225 | return url in apache_file 226 | 227 | 228 | def post_a_comment(comment): 229 | comment = 'Hello, I am helping on creating this wiki. ' + comment + \ 230 | ' ^_^ Sincerely, your Fully Automated Resource Tackler' 231 | pass 232 | 233 | 234 | def handle_subticket_for_cloud(task_details, db_name, wiki_status): 235 | hasSubtasks = client.getTaskSubtasks(task_details['phid']) 236 | if hasSubtasks: 237 | return 238 | 239 | client.createSubtask("The new wiki's visibility will be: **%s**." % wiki_status, [ 240 | 'PHID-PROJ-hwibeuyzizzy4xzunfsk', # DBA 241 | 'PHID-PROJ-bj6y6ks7ampcwcignhce' # Data services 242 | ], task_details['phid'], 'Prepare and check storage layer for ' + db_name) 243 | 244 | def handle_ticket_for_wikistats(task_details, db_name): 245 | client.createParentTask("Please add new wiki `%s` to Wikistats, once it is created. Thanks!" % db_name, [ 246 | 'PHID-PROJ-6sht6g4xpdii4c4bga2i' # VPS-project-Wikistats 247 | ], task_details['phid'], 'Add %s to wikistats' % db_name) 248 | 249 | 250 | def get_dummy_wiki(shard, family): 251 | if family == "wiktionary": 252 | return { 253 | "s3": "aawiki", 254 | "s5": "mhwiktionary", 255 | }.get(shard, "?????") 256 | else: 257 | return { 258 | "s3": "aawiki", 259 | "s5": "muswiki" 260 | }.get(shard, "?????") 261 | 262 | 263 | def create_patch_for_wikimedia_messages( 264 | db_name, english_name, url, lang, bug_id): 265 | if not english_name: 266 | return 267 | r = requests.get( 268 | 'https://gerrit.wikimedia.org/r/changes/?q=' 269 | 'bug:{}+project:mediawiki/extensions/WikimediaMessages'.format(bug_id)) 270 | b = json.loads('\n'.join(r.text.split('\n')[1:])) 271 | if b: 272 | return 273 | maker = WikimediaMessagesPatchMaker( 274 | db_name, english_name, url, lang, bug_id) 275 | maker.run() 276 | 277 | 278 | def handle_dns(special, url, language_code, task_tid): 279 | dns_path = get_gerrit_path( 280 | 'operations/dns', 281 | 'templates/wikimedia.org' if special else 282 | 'templates/helpers/langlist.tmpl') 283 | dns_url = gerrit_path + dns_path 284 | dns = hostname_resolves(url) 285 | print(url) 286 | if not dns: 287 | print('dns not found') 288 | if not special: 289 | print('not special') 290 | create_patch_for_dns(language_code, task_tid) 291 | add_checklist(dns_url, 'DNS', dns) 292 | return dns 293 | 294 | 295 | def handle_apache(special, parts): 296 | if not special: 297 | add_text(' [x] Apache config (Not needed)') 298 | return True 299 | 300 | file_path = 'hieradata/common/mediawiki.yaml' 301 | apache_url = gerrit_path + \ 302 | 'operations/puppet/+/production/' + file_path 303 | if not handle_special_wiki_apache(parts): 304 | apache = False 305 | else: 306 | apache = True 307 | add_checklist(apache_url, 'Apache config', apache) 308 | return apache 309 | 310 | 311 | def handle_langdb(language_code): 312 | langdb_url = get_github_url('language-data', 'data/langdb.yaml') 313 | r = requests.get(langdb_url) 314 | config = 'Language configuration in language data repo' 315 | if re.search(r'\n *?' + language_code + ':', r.text): 316 | langdb = True 317 | else: 318 | langdb = False 319 | add_checklist(langdb_url, config, langdb) 320 | return langdb 321 | 322 | 323 | def handle_wikimedia_messages_one( 324 | db_name, 325 | wiki_spec, 326 | url, 327 | language_code, 328 | task_tid): 329 | path = get_gerrit_path( 330 | 'mediawiki/extensions/WikimediaMessages', 331 | 'i18n/wikimediaprojectnames/en.json' 332 | ) 333 | wikimedia_messages_data = get_file_from_gerrit(path) 334 | wikimedia_messages_data = json.loads(wikimedia_messages_data) 335 | if 'project-localized-name-' + db_name in wikimedia_messages_data: 336 | wikimedia_messages_one = True 337 | else: 338 | wikimedia_messages_one = False 339 | english_name = wiki_spec.get('Project name (English)') 340 | create_patch_for_wikimedia_messages( 341 | db_name, english_name, url, language_code, task_tid) 342 | add_checklist(gerrit_path + path, 343 | 'Wikimedia messages configuration', wikimedia_messages_one) 344 | url = 'https://en.wikipedia.org/wiki/' + \ 345 | 'MediaWiki:Project-localized-name-' + db_name 346 | r = requests.get(url) 347 | if 'Wikipedia does not have a' not in r.text: 348 | wikimedia_messages_one_deployed = True 349 | add_text(' [x] [[{}|deployed]]'.format(url)) 350 | else: 351 | wikimedia_messages_one_deployed = False 352 | add_text(' [] [[{}|deployed]]'.format(url)) 353 | 354 | return wikimedia_messages_one and wikimedia_messages_one_deployed 355 | 356 | 357 | def handle_wikimedia_messages_two(db_name, parts): 358 | config = 'Wikimedia messages (interwiki search result) configuration' 359 | if parts[1] != 'wikipedia': 360 | add_text(' [x] {} (not needed)'.format(config)) 361 | return True 362 | 363 | path = get_gerrit_path( 364 | 'mediawiki/extensions/WikimediaMessages', 365 | 'i18n/wikimediainterwikisearchresults/en.json' 366 | ) 367 | search_messages_data = json.loads(get_file_from_gerrit(path)) 368 | if 'search-interwiki-results-' + db_name in search_messages_data: 369 | wikimedia_messages_two = True 370 | else: 371 | wikimedia_messages_two = False 372 | add_checklist( 373 | gerrit_path + path, 374 | config, 375 | wikimedia_messages_two) 376 | url = 'https://en.wikipedia.org/wiki/' + \ 377 | 'MediaWiki:Search-interwiki-results-' + db_name 378 | r = requests.get(url) 379 | if 'Wikipedia does not have a' not in r.text: 380 | wikimedia_messages_two_deployed = True 381 | add_text(' [x] [[{}|deployed]]'.format(url)) 382 | else: 383 | wikimedia_messages_two_deployed = False 384 | add_text(' [] [[{}|deployed]]'.format(url)) 385 | return wikimedia_messages_two and wikimedia_messages_two_deployed 386 | 387 | 388 | def create_patch_for_dns(lang, bug_id): 389 | r = requests.get( 390 | 'https://gerrit.wikimedia.org/r/changes/' 391 | '?q=bug:{}+project:operations/dns'.format(bug_id)) 392 | b = json.loads('\n'.join(r.text.split('\n')[1:])) 393 | if b: 394 | return 395 | maker = DnsPatchMaker(lang, bug_id) 396 | maker.run() 397 | 398 | 399 | def handle_core_lang(language_code): 400 | core_messages_url = get_github_url( 401 | 'mediawiki', 402 | 'languages/messages/Messages{}.php'.format( 403 | language_code[0].upper() + language_code[1:])) 404 | r = requests.get(core_messages_url) 405 | if r.status_code == 200: 406 | core_lang = True 407 | else: 408 | core_lang = False 409 | add_checklist(core_messages_url, 410 | 'Language configuration in mediawiki core', core_lang) 411 | return core_lang 412 | 413 | 414 | def get_db_name(wiki_spec, parts): 415 | db_name = wiki_spec.get('Database name') 416 | if not db_name: 417 | if parts[1] == 'wikipedia': 418 | db_name = parts[0].replace('-', '_') + 'wiki' 419 | else: 420 | db_name = parts[0].replace('-', '_') + parts[1] 421 | return db_name 422 | 423 | 424 | def add_create_instructions(parts, shard, language_code, db_name, task_tid): 425 | add_text('\n-------') 426 | add_text('**Step by step commands**:') 427 | dummy_wiki = get_dummy_wiki(shard, parts[1]) 428 | add_text('On deployment host:') 429 | add_text('`cd /srv/mediawiki-staging/`') 430 | add_text('`git fetch`') 431 | add_text('`git log -p HEAD..@{u}`') 432 | add_text('`git rebase`') 433 | add_text('On mwmaint1002:') 434 | add_text('`scap pull`') 435 | addwiki_path = 'mwscript extensions/WikimediaMaintenance/addWiki.php' 436 | add_text( 437 | '`{addwiki_path} --wiki={dummy} {lang} {family} {db} {url}`'.format( 438 | addwiki_path=addwiki_path, 439 | dummy=dummy_wiki, 440 | lang=language_code, 441 | family=parts[1], 442 | db=db_name, 443 | url='.'.join(parts))) 444 | 445 | add_text('On deployment host:') 446 | add_text('`scap sync-world "Creating {db_name} ({phab})"`'.format( 447 | db_name=db_name, phab=task_tid)) 448 | 449 | add_text('On mwmaint1002:') 450 | add_text('`{search_path} --wiki={dbname} --cluster=all 2>&1 | tee {log}`'.format( 451 | search_path='mwscript extensions/CirrusSearch/maintenance/UpdateSearchIndexConfig.php', 452 | dbname=db_name, 453 | log='/tmp/{dbname}.UpdateSearchIndexConfig.log'.format(dbname=db_name), 454 | )) 455 | 456 | add_text('On deployment host:') 457 | add_text('`scap update-interwiki-cache`') 458 | 459 | 460 | def update_task_report(task_details): 461 | global final_text 462 | if not final_text: 463 | return 464 | old_report = re.findall( 465 | r'(\n\n------\n\*\*Pre-install automatic checklist:' 466 | r'\*\*.+?\n\*\*End of automatic output\*\*\n)', 467 | task_details['description'], re.DOTALL) 468 | if not old_report: 469 | print('old report not found, appending') 470 | client.setTaskDescription( 471 | task_details['phid'], task_details['description'] + final_text) 472 | else: 473 | if old_report[0] != final_text: 474 | print('Updating old report') 475 | client.setTaskDescription( 476 | task_details['phid'], 477 | task_details['description'].replace( 478 | old_report[0], 479 | final_text)) 480 | 481 | 482 | def hande_task(task_details): 483 | global final_text 484 | final_text = '' 485 | print('Checking T%s' % task_details['id']) 486 | task_tid = 'T' + task_details['id'] 487 | 488 | # Extract wiki config 489 | wiki_spec = {} 490 | for case in re.findall( 491 | r'\n- *?\*\*(.+?):\*\* *?(.+)', 492 | task_details['description']): 493 | wiki_spec[case[0].strip()] = case[1].strip() 494 | language_code = wiki_spec.get('Language code') 495 | if not language_code: 496 | print('lang code not found, skipping') 497 | return 498 | url = wiki_spec.get('Site URL') 499 | if not url: 500 | print('url not found, skipping') 501 | return 502 | parts = url.split('.') 503 | if len(parts) != 3 or parts[2] != 'org': 504 | print('the url looks weird, skipping') 505 | return 506 | db_name = get_db_name(wiki_spec, parts) 507 | shard = wiki_spec.get('Shard', 'TBD') 508 | visibility = wiki_spec.get('Visibility', 'unknown') 509 | shardDecided = shard != "TBD" 510 | special = parts[1] == 'wikimedia' 511 | 512 | add_text('\n\n------\n**Pre-install automatic checklist:**') 513 | if shardDecided: 514 | add_text(' [X] #DBA decided about the shard') 515 | else: 516 | add_text(' [] #DBA decided about the shard') 517 | dns = handle_dns(special, url, language_code, task_tid) 518 | if not special and wiki_spec.get('Special', '').lower() != 'yes': 519 | handle_subticket_for_cloud(task_details, db_name, visibility) 520 | apache = handle_apache(special, parts) 521 | langdb = handle_langdb(language_code) 522 | core_lang = handle_core_lang(language_code) 523 | wm_message_one = handle_wikimedia_messages_one( 524 | db_name, wiki_spec, url, language_code, task_tid 525 | ) 526 | wm_message_two = handle_wikimedia_messages_two(db_name, parts) 527 | 528 | if dns and apache and langdb and core_lang and wm_message_one and \ 529 | wm_message_two and shardDecided: 530 | add_text('**The Wiki is ready to be created.**') 531 | else: 532 | add_text('**The creation is blocked until these part are all done.**') 533 | 534 | if visibility.lower() != 'private' and not client.getTaskParents(task_details['phid']): 535 | handler = PostCreationHandler(task_details['phid'], db_name, url, language_code, parts) 536 | handler.handle() 537 | 538 | add_create_instructions(parts, shard, language_code, db_name, task_tid) 539 | add_text('\n**End of automatic output**') 540 | 541 | 542 | def main(): 543 | open_create_wikis_phid = 'PHID-PROJ-kmpu7gznmc2edea3qn2x' 544 | for phid in client.getTasksWithProject( 545 | open_create_wikis_phid, statuses=['open']): 546 | task_details = client.taskDetails(phid) 547 | hande_task(task_details) 548 | update_task_report(task_details) 549 | 550 | 551 | if __name__ == "__main__": 552 | main() 553 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------