| 1 |
#!/usr/bin/env python |
| 2 |
# License: GPLv3 Copyright: 2008, Kovid Goyal <kovid at kovidgoyal.net> |
| 3 |
|
| 4 |
|
| 5 |
import json |
| 6 |
import os |
| 7 |
import re |
| 8 |
import socket |
| 9 |
import subprocess |
| 10 |
import sys |
| 11 |
import urllib.request |
| 12 |
|
| 13 |
from lxml import html |
| 14 |
|
| 15 |
''' |
| 16 |
Hook to make the commit command automatically close bugs when the commit |
| 17 |
message contains `Fix #number` or `Implement #number`. Also updates the commit |
| 18 |
message with the summary of the closed bug. |
| 19 |
|
| 20 |
''' |
| 21 |
|
| 22 |
|
| 23 |
LAUNCHPAD = os.path.expanduser('~/work/env/launchpad.py') |
| 24 |
LAUNCHPAD_BUG = 'https://bugs.launchpad.net/calibre/+bug/{}' |
| 25 |
GITHUB_BUG = 'https://api.github.com/repos/kovidgoyal/calibre/issues/{}' |
| 26 |
BUG_PAT = r'(Fix|Implement|Fixes|Fixed|Implemented|See)\s+#(\d+)' |
| 27 |
|
| 28 |
socket.setdefaulttimeout(90) |
| 29 |
|
| 30 |
|
| 31 |
class Bug: |
| 32 |
def __init__(self): |
| 33 |
self.seen = set() |
| 34 |
|
| 35 |
def __call__(self, match): |
| 36 |
action, bug = match.group(1), match.group(2) |
| 37 |
summary = '' |
| 38 |
if bug in self.seen: |
| 39 |
return match.group() |
| 40 |
self.seen.add(bug) |
| 41 |
|
| 42 |
if int(bug) > 100000: # Launchpad bug |
| 43 |
try: |
| 44 |
raw = urllib.request.urlopen(LAUNCHPAD_BUG.format(bug)).read() |
| 45 |
h1 = html.fromstring(raw).xpath('//h1[@id="edit-title"]')[0] |
| 46 |
summary = html.tostring(h1, method='text', encoding=str).strip() |
| 47 |
except Exception: |
| 48 |
summary = 'Private bug' |
| 49 |
else: |
| 50 |
summary = json.loads(urllib.request.urlopen(GITHUB_BUG.format(bug)).read())['title'] |
| 51 |
if summary: |
| 52 |
print('Working on bug:', summary) |
| 53 |
if int(bug) > 100000 and action != 'See': |
| 54 |
self.close_bug(bug, action) |
| 55 |
return match.group() + f' [{summary}]({LAUNCHPAD_BUG.format(bug)})' |
| 56 |
return match.group() + f' ({summary})' |
| 57 |
return match.group() |
| 58 |
|
| 59 |
def close_bug(self, bug, action): |
| 60 |
print(f'Closing bug #{bug}') |
| 61 |
suffix = 'The fix will be in the next release. calibre is usually released every alternate Friday.' |
| 62 |
action += 'ed' |
| 63 |
msg = '{} in branch {}. {}'.format(action, 'master', suffix) |
| 64 |
msg = msg.replace('Fixesed', 'Fixed') |
| 65 |
env = dict(os.environ) |
| 66 |
env['LAUNCHPAD_FIX_BUG'] = msg |
| 67 |
subprocess.run([sys.executable, LAUNCHPAD], env=env, input=f'Subject: [Bug {bug}]', text=True, check=True) |
| 68 |
|
| 69 |
|
| 70 |
def main(): |
| 71 |
with open(sys.argv[-1], 'r+b') as f: |
| 72 |
raw = f.read().decode('utf-8') |
| 73 |
bug = Bug() |
| 74 |
msg = re.sub(BUG_PAT, bug, raw) |
| 75 |
if msg != raw: |
| 76 |
f.seek(0) |
| 77 |
f.truncate() |
| 78 |
f.write(msg.encode('utf-8')) |
| 79 |
|
| 80 |
|
| 81 |
if __name__ == '__main__': |
| 82 |
main() |