Debian Codegraph @

tools/gen_emoji.py

raw
1 """Generate gemoji index."""
2 import os
3 import requests
4 import json
5 import argparse
6 import shutil
7 import zipfile
8 import gen_emoji1
9 import gen_gemoji
10 import gen_twemoji
11 import gen_joypixels
12
13 current_dir = os.path.dirname(os.path.abspath(__file__))
14
15 GITHUB_API_HEADER = 'application/vnd.github.v3+json'
16 GITHUB_API = 'https://api.github.com'
17 GEMOJI = 'github/gemoji'
18 EMOJIONE = 'joypixels/emojione'
19 JOYPIXELS = 'joypixels/emoji-toolkit'
20 TWEMOJI = 'jdecked/twemoji'
21
22
23 def url_join(*args):
24 """Join URL parts."""
25 return '/'.join(args)
26
27
28 def get_github_emoji():
29 """Get GitHub's usable emoji."""
30 try:
31 resp = requests.get(
32 url_join(GITHUB_API, 'emojis'),
33 headers={'Accept': GITHUB_API_HEADER},
34 timeout=30
35 )
36 except Exception:
37 return None
38
39 return json.loads(resp.text)
40
41
42 def extract_tag(repo, file_location):
43 """Extract tag from zip."""
44 with zipfile.ZipFile(file_location, "r") as z:
45 z.extractall(os.path.dirname(file_location))
46 repo_dir = None
47 base = os.path.dirname(file_location)
48 for x in os.listdir(base):
49 fullname = os.path.join(base, x)
50 if os.path.isdir(fullname) and x.startswith(repo.replace('/', '-')):
51 repo_dir = fullname
52 break
53 if repo_dir:
54 os.rename(repo_dir, os.path.join(base, repo.replace('/', '-')))
55
56
57 def download_tag(repo, tag, url):
58 """Download tag."""
59 destination = os.path.join(current_dir, 'tags', repo.replace('/', '-'))
60 if not os.path.exists(destination):
61 os.makedirs(destination)
62 else:
63 print('Removing old tag...')
64 shutil.rmtree(destination)
65 os.makedirs(destination)
66 file_location = os.path.join(destination, os.path.basename(url) + '.zip')
67 print('Downloading: {} --> {}'.format(url, file_location))
68 resp = requests.get(
69 url,
70 headers={'Accept': GITHUB_API_HEADER},
71 stream=True
72 )
73 with open(file_location, 'wb') as f:
74 for chunk in resp.iter_content(chunk_size=1024):
75 if chunk:
76 f.write(chunk)
77
78 extract_tag(repo, file_location)
79
80
81 def select_tag(repo, no_download):
82 """Get GitHub's usable emoji."""
83 resp = requests.get(
84 url_join(GITHUB_API, 'repos', repo, 'releases'),
85 headers={'Accept': GITHUB_API_HEADER},
86 timeout=50
87 )
88
89 assert resp.status_code == 200, "API call failed to get tag list!"
90 tags = json.loads(resp.text)
91
92 print('Select %s tag to use:' % repo)
93 num_tags = len(tags)
94 text = []
95 for index in range(num_tags):
96 text.append(' [%d] %s' % (index, tags[index]['tag_name']))
97 if (index + 1) % 4 == 0:
98 text.append('\n')
99 if len(text) == 0 or text[-1] != '\n':
100 text.append('\n')
101 print(''.join(text))
102 user_input = None
103 while user_input is None:
104 try:
105 user_input = int(input('Select Tag > '))
106 except Exception:
107 user_input = None
108 if user_input is not None and (user_input < 0 or user_input >= num_tags):
109 user_input = None
110
111 if not no_download:
112 download_tag(repo, tags[user_input]['tag_name'], tags[user_input]['zipball_url'])
113 return tags[user_input]['tag_name']
114
115
116 if __name__ == "__main__":
117 parser = argparse.ArgumentParser(prog='gen_emoji', description='Generate emoji db files.')
118 # Flag arguments
119 parser.add_argument('--tag', default=None, help="Tag to use.")
120 parser.add_argument('--joypixels-tag', default=None, help="Joypixels tag to use for Twemoji.")
121 parser.add_argument('--joypixels-no-download', action='store_true', default=False, help="Skip Joypixels download.")
122 parser.add_argument('--gemoji', action='store_true', default=False, help="Get Gemoji.")
123 parser.add_argument('--emojione', action='store_true', default=False, help="Get Emojione.")
124 parser.add_argument('--twemoji', action='store_true', default=False, help="Get Twemoji.")
125 parser.add_argument('--no-download', action='store_true', default=False, help="Skip download and use local.")
126 args = parser.parse_args()
127 os.chdir(current_dir)
128 if args.gemoji:
129 if args.tag is None:
130 tag = select_tag(GEMOJI, args.no_download)
131 else:
132 tag = args.tag
133 gen_gemoji.parse(GEMOJI.replace('/', '-'), tag)
134 if args.emojione:
135 if args.tag is None:
136 tag = select_tag(EMOJIONE, args.no_download)
137 else:
138 tag = args.tag
139 gen_emoji1.parse(EMOJIONE.replace('/', '-'), tag)
140 if args.twemoji:
141 if args.joypixels_tag is None:
142 jtag = select_tag(JOYPIXELS, args.joypixels_no_download)
143 else:
144 jtag = args.joypixels_tag
145 db, aliases = gen_joypixels.parse(JOYPIXELS.replace('/', '-'), jtag)
146 if args.tag is None:
147 tag = select_tag(TWEMOJI, args.no_download)
148 else:
149 tag = args.tag
150 gen_twemoji.parse(TWEMOJI.replace('/', '-'), tag, jtag, db, aliases)