Debian Codegraph @

gen_version.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 #
3 # Copyright 2015 Google Inc. All rights reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 """Generate version string for NotoColorEmoji.
18
19 This parses the color emoji template file and updates the lines
20 containing version string info, writing a new file.
21
22 The nameID 5 field in the emoji font should reflect the commit/date
23 of the repo it was built from. This will build a string of the following
24 format:
25 Version 1.39;GOOG;noto-emoji:20170220:a8a215d2e889'
26
27 This is intended to indicate that it was built by Google from noto-emoji
28 at commit a8a215d2e889 and date 20170220 (since dates are a bit easier
29 to locate in time than commit hashes).
30
31 For building with external data we don't include the commit id as we
32 might be using different resources. Instead the version string is:
33 Version 1.39;GOOG;noto-emoji:20170518;BETA <msg>
34
35 Here the date is the current date, and the message after 'BETA ' is
36 provided using the '-b' flag. There's no commit hash. This also
37 bypasses some checks about the state of the repo.
38
39 The release number should have 2 or 3 minor digits. Right now we've been
40 using 2 but at the next major release we probably want to use 3. This
41 supports both. It will bump the version number if none is provided,
42 maintaining the minor digit length.
43 """
44
45 import argparse
46 import datetime
47 import re
48
49 from nototools import tool_utils
50
51 # These are not very lenient, we expect to be applied to the noto color
52 # emoji template ttx file which matches these. Why then require the
53 # input argument, you ask? Um... testing?
54 _nameid_re = re.compile(r'\s*<namerecord nameID="5"')
55 _version_re = re.compile(r'\s*Version\s(\d+.\d{2,3})')
56 _headrev_re = re.compile(r'\s*<fontRevision value="(\d+.\d{2,3})"/>')
57
58 def _get_existing_version(lines):
59 """Scan lines for all existing version numbers, and ensure they match.
60 Return the matched version number string."""
61
62 version = None
63 def check_version(new_version):
64 if version is not None and new_version != version:
65 raise Exception(
66 'version %s and namerecord version %s do not match' % (
67 version, new_version))
68 return new_version
69
70 saw_nameid = False
71 for line in lines:
72 if saw_nameid:
73 saw_nameid = False
74 m = _version_re.match(line)
75 if not m:
76 raise Exception('could not match line "%s" in namerecord' % line)
77 version = check_version(m.group(1))
78 elif _nameid_re.match(line):
79 saw_nameid = True
80 else:
81 m = _headrev_re.match(line)
82 if m:
83 version = check_version(m.group(1))
84 return version
85
86
87 def _version_to_mm(version):
88 majs, mins = version.split('.')
89 minor_len = len(mins)
90 return int(majs), int(mins), minor_len
91
92
93 def _mm_to_version(major, minor, minor_len):
94 fmt = '%%d.%%0%dd' % minor_len
95 return fmt % (major, minor)
96
97
98 def _version_compare(lhs, rhs):
99 lmaj, lmin, llen = _version_to_mm(lhs)
100 rmaj, rmin, rlen = _version_to_mm(rhs)
101 # if major versions differ, we don't care about the minor length, else
102 # they should be the same
103 if lmaj != rmaj:
104 return lmaj - rmaj
105 if llen != rlen:
106 raise Exception('minor version lengths differ: "%s" and "%s"' % (lhs, rhs))
107 return lmin - rmin
108
109
110 def _version_bump(version):
111 major, minor, minor_len = _version_to_mm(version)
112 minor = (minor + 1) % (10 ** minor_len)
113 if minor == 0:
114 raise Exception('cannot bump version "%s", requires new major' % version)
115 return _mm_to_version(major, minor, minor_len)
116
117
118 def _get_repo_version_str(beta):
119 """See above for description of this string."""
120 if beta is not None:
121 date_str = datetime.date.today().strftime('%Y%m%d')
122 return 'GOOG;noto-emoji:%s;BETA %s' % (date_str, beta)
123
124 p = tool_utils.resolve_path('[emoji]')
125 commit, date, _ = tool_utils.git_head_commit(p)
126 if not tool_utils.git_check_remote_commit(p, commit):
127 raise Exception('emoji not on upstream master branch')
128 date_re = re.compile(r'(\d{4})-(\d{2})-(\d{2})')
129 m = date_re.match(date)
130 if not m:
131 raise Exception('could not match "%s" with "%s"' % (date, date_re.pattern))
132 ymd = ''.join(m.groups())
133 return 'GOOG;noto-emoji:%s:%s' % (ymd, commit[:12])
134
135
136 def _replace_existing_version(lines, version, version_str):
137 """Update lines with new version strings in appropriate places."""
138 saw_nameid = False
139 for i in range(len(lines)):
140 line = lines[i]
141 if saw_nameid:
142 saw_nameid = False
143 # preserve indentation
144 lead_ws = len(line) - len(line.lstrip())
145 lines[i] = line[:lead_ws] + version_str + '\n'
146 elif _nameid_re.match(line):
147 saw_nameid = True
148 elif _headrev_re.match(line):
149 lead_ws = len(line) - len(line.lstrip())
150 lines[i] = line[:lead_ws] + '<fontRevision value="%s"/>\n' % version
151
152
153 def update_version(srcfile, dstfile, version, beta):
154 """Update version in srcfile and write to dstfile. If version is None,
155 bumps the current version, else version must be greater than the
156 current version."""
157
158 with open(srcfile, 'r') as f:
159 lines = f.readlines()
160 current_version = _get_existing_version(lines)
161 if not version:
162 version = _version_bump(current_version)
163 elif version and _version_compare(version, current_version) <= 0:
164 raise Exception('new version %s is <= current version %s' % (
165 version, current_version))
166 version_str = 'Version %s;%s' % (version, _get_repo_version_str(beta))
167 _replace_existing_version(lines, version, version_str)
168 with open(dstfile, 'w') as f:
169 for line in lines:
170 f.write(line)
171
172
173 def main():
174 parser = argparse.ArgumentParser()
175 parser.add_argument(
176 '-v', '--version', help='version number, default bumps the current '
177 'version', metavar='ver')
178 parser.add_argument(
179 '-s', '--src', help='ttx file with name and head tables',
180 metavar='file', required=True)
181 parser.add_argument(
182 '-d', '--dst', help='name of edited ttx file to write',
183 metavar='file', required=True)
184 parser.add_argument(
185 '-b', '--beta', help='beta tag if font is built using external resources')
186 args = parser.parse_args()
187
188 update_version(args.src, args.dst, args.version, args.beta)
189
190
191 if __name__ == '__main__':
192 main()