Skip to content

Commit f24e7d8

Browse files
committed
Split generator into separate python module
1 parent d833c0f commit f24e7d8

File tree

3 files changed

+90
-66
lines changed

3 files changed

+90
-66
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/__pycache__/

commit.py

Lines changed: 13 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -1,84 +1,29 @@
11
import os
2-
import sys
3-
import random
4-
import re
52
import json
63
import signal
7-
from typing import Dict, List
8-
9-
from hashlib import md5
104

115
import tornado.httpserver
126
import tornado.ioloop
137
import tornado.web
148
from tornado.escape import xhtml_unescape
159
from tornado.options import define, options
1610

17-
define("port", default=5000, help="run on the given port", type=int)
18-
19-
humans_file = os.path.join(os.path.dirname(__file__), 'static', 'humans.txt')
20-
messages_file = os.path.join(os.path.dirname(__file__), 'commit_messages.txt')
21-
messages: Dict[str, str] = {}
22-
23-
# Create a hash table of all commit messages
24-
with open(messages_file, 'r', encoding='utf-8') as messages_input:
25-
for line in messages_input.readlines():
26-
messages[md5(line.encode('utf-8')).hexdigest()] = line
27-
28-
names: List[str] = []
29-
30-
with open(humans_file, 'r', encoding='utf-8') as humans_input:
31-
humans_content = humans_input.read()
32-
for line in humans_content.split("\n"):
33-
if "Name:" in line:
34-
data = line[6:].rstrip()
35-
if data.find("github:") == 0:
36-
names.append(data[7:])
37-
else:
38-
names.append(data.split(" ")[0])
39-
40-
num_re = re.compile(r"XNUM([0-9,]*)X")
41-
42-
def fill_line(message):
43-
message = message.replace('XNAMEX', random.choice(names))
44-
message = message.replace('XUPPERNAMEX', random.choice(names).upper())
45-
message = message.replace('XLOWERNAMEX', random.choice(names).lower())
46-
47-
nums = num_re.findall(message)
48-
49-
while nums:
50-
start = 1
51-
end = 999
52-
value = nums.pop(0) or str(end)
53-
if "," in value:
54-
position = value.index(",")
55-
if position == 0: # XNUM,5X
56-
end = int(value[1:])
57-
elif position == len(value) - 1: # XNUM5,X
58-
start = int(value[:position])
59-
else: # XNUM1,5X
60-
start = int(value[:position])
61-
end = int(value[position+1:])
62-
else:
63-
end = int(value)
64-
if start > end:
65-
end = start * 2
66-
67-
randint = random.randint(start, end)
68-
message = num_re.sub(str(randint), message, count=1)
11+
import messages
6912

70-
return message
13+
define("port", default=5000, help="run on the given port", type=int)
7114

7215
class MainHandler(tornado.web.RequestHandler):
7316
def get(self, message_hash=None):
74-
if not message_hash:
75-
message_hash = random.choice(list(messages.keys()))
76-
elif message_hash not in messages:
77-
raise tornado.web.HTTPError(404)
17+
found_message = messages.find_by_md5(message_hash)
7818

79-
message = fill_line(messages[message_hash])
19+
if message_hash and not found_message:
20+
raise tornado.web.HTTPError(404)
8021

81-
self.output_message(message, message_hash)
22+
if found_message:
23+
self.output_message(found_message, message_hash)
24+
else:
25+
message, generated_message_hash = messages.generate()
26+
self.output_message(message, generated_message_hash)
8227

8328
def output_message(self, message, message_hash):
8429
self.set_header('X-Message-Hash', message_hash)
@@ -129,6 +74,8 @@ def try_exit(self):
12974
tornado.options.parse_command_line()
13075
signal.signal(signal.SIGINT, application.signal_handler)
13176
http_server = tornado.httpserver.HTTPServer(application)
132-
http_server.listen(os.environ.get("PORT", 5000))
77+
port = os.environ.get("PORT", 5000)
78+
print("ready for requests (on port %s)" % (port))
79+
http_server.listen(port)
13380
tornado.ioloop.PeriodicCallback(application.try_exit, 100).start()
13481
tornado.ioloop.IOLoop.instance().start()

messages.py

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import os
2+
import random
3+
import re
4+
from typing import Dict, List
5+
from hashlib import md5
6+
7+
def generate():
8+
digest = _pick_random_key(templates)
9+
msg = templates[digest]
10+
return (msg, digest)
11+
12+
def find_by_md5(md5):
13+
if md5 not in templates:
14+
return None
15+
else:
16+
t = templates[md5]
17+
return _fill_template(t)
18+
19+
this_file = os.path.dirname(__file__)
20+
humans_file = os.path.join(this_file, 'static', 'humans.txt')
21+
all_messages_file = os.path.join(this_file, 'commit_messages.txt')
22+
tmp = os.path.join(this_file, 'tmp')
23+
os.makedirs(tmp, exist_ok=True)
24+
25+
templates: Dict[str, str] = {}
26+
names: List[str] = []
27+
28+
# Create a hash table of all commit message templates
29+
print("hashing messages...")
30+
with open(all_messages_file, 'r', encoding='utf-8') as f:
31+
for line in f:
32+
templates[md5(line.encode('utf-8')).hexdigest()] = line
33+
34+
with open(humans_file, 'r', encoding='utf-8') as f:
35+
for line in f:
36+
if "Name:" in line:
37+
data = line[6:].rstrip()
38+
if data.find("github:") == 0:
39+
names.append(data[7:])
40+
else:
41+
names.append(data.split(" ")[0])
42+
43+
def _pick_random_key(templates):
44+
return random.choice(list(templates.keys()))
45+
46+
num_re = re.compile(r"XNUM([0-9,]*)X")
47+
48+
def _fill_template(txt):
49+
txt = txt.replace('XNAMEX', random.choice(names))
50+
txt = txt.replace('XUPPERNAMEX', random.choice(names).upper())
51+
txt = txt.replace('XLOWERNAMEX', random.choice(names).lower())
52+
53+
nums = num_re.findall(txt)
54+
55+
while nums:
56+
start = 1
57+
end = 999
58+
value = nums.pop(0) or str(end)
59+
if "," in value:
60+
position = value.index(",")
61+
if position == 0: # XNUM,5X
62+
end = int(value[1:])
63+
elif position == len(value) - 1: # XNUM5,X
64+
start = int(value[:position])
65+
else: # XNUM1,5X
66+
start = int(value[:position])
67+
end = int(value[position+1:])
68+
else:
69+
end = int(value)
70+
if start > end:
71+
end = start * 2
72+
73+
randint = random.randint(start, end)
74+
txt = num_re.sub(str(randint), txt, count=1)
75+
76+
return txt

0 commit comments

Comments
 (0)