Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(184)

Side by Side Diff: build/util/version.py

Issue 336513002: version.py: Use argparse instead of getopt. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Created 6 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « no previous file | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 #!/usr/bin/env python 1 #!/usr/bin/env python
2 # Copyright 2014 The Chromium Authors. All rights reserved. 2 # Copyright 2014 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be 3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file. 4 # found in the LICENSE file.
5 5
6 """ 6 """
7 version.py -- Chromium version string substitution utility. 7 version.py -- Chromium version string substitution utility.
8 """ 8 """
9 9
10 import getopt 10 import argparse
Mark Mentovai 2014/06/12 13:49:43 The CL description still mentions optparse.
11 import os 11 import os
12 import sys 12 import sys
13 13
14 14
15 class Usage(Exception):
16 def __init__(self, msg):
17 self.msg = msg
18
19
20 def fetch_values_from_file(values_dict, file_name): 15 def fetch_values_from_file(values_dict, file_name):
21 """ 16 """
22 Fetches KEYWORD=VALUE settings from the specified file. 17 Fetches KEYWORD=VALUE settings from the specified file.
23 18
24 Everything to the left of the first '=' is the keyword, 19 Everything to the left of the first '=' is the keyword,
25 everything to the right is the value. No stripping of 20 everything to the right is the value. No stripping of
26 white space, so beware. 21 white space, so beware.
27 22
28 The file must exist, otherwise you get the Python exception from open(). 23 The file must exist, otherwise you get the Python exception from open().
29 """ 24 """
(...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after
72 for key, val in values.iteritems(): 67 for key, val in values.iteritems():
73 try: 68 try:
74 contents = contents.replace('@' + key + '@', val) 69 contents = contents.replace('@' + key + '@', val)
75 except TypeError: 70 except TypeError:
76 print repr(key), repr(val) 71 print repr(key), repr(val)
77 return contents 72 return contents
78 73
79 74
80 def subst_file(file_name, values): 75 def subst_file(file_name, values):
81 """ 76 """
82 Returns the contents of the specified file_name with substited 77 Returns the contents of the specified file_name with substituted
83 values from the specified dictionary. 78 values from the specified dictionary.
84 79
85 This is like subst_template, except it operates on a file. 80 This is like subst_template, except it operates on a file.
86 """ 81 """
87 template = open(file_name, 'r').read() 82 template = open(file_name, 'r').read()
88 return subst_template(template, values); 83 return subst_template(template, values);
89 84
90 85
91 def write_if_changed(file_name, contents): 86 def write_if_changed(file_name, contents):
92 """ 87 """
93 Writes the specified contents to the specified file_name 88 Writes the specified contents to the specified file_name
94 iff the contents are different than the current contents. 89 iff the contents are different than the current contents.
95 """ 90 """
96 try: 91 try:
97 old_contents = open(file_name, 'r').read() 92 old_contents = open(file_name, 'r').read()
98 except EnvironmentError: 93 except EnvironmentError:
99 pass 94 pass
100 else: 95 else:
101 if contents == old_contents: 96 if contents == old_contents:
102 return 97 return
103 os.unlink(file_name) 98 os.unlink(file_name)
104 open(file_name, 'w').write(contents) 99 open(file_name, 'w').write(contents)
105 100
106 101
107 def main(argv=None): 102 def main():
108 if argv is None: 103 parser = argparse.ArgumentParser()
109 argv = sys.argv 104 parser.add_argument('-f', '--file', action='append', default=[],
Mark Mentovai 2014/06/12 13:49:43 [] is already the default when action is “append”,
110 105 help='Read variables from FILE.')
111 short_options = 'e:f:i:o:t:h' 106 parser.add_argument('-i', '--input', default=None,
112 long_options = ['eval=', 'file=', 'help'] 107 help='Read strings to substitute from FILE.')
113 108 parser.add_argument('-o', '--output', default=None,
114 helpstr = """\ 109 help='Write substituted strings to FILE.')
115 Usage: version.py [-h] [-f FILE] ([[-i] FILE] | -t TEMPLATE) [[-o] FILE] 110 parser.add_argument('-t', '--template', default=None,
116 111 help='Use TEMPLATE as the strings to substitute.')
117 -f FILE, --file=FILE Read variables from FILE. 112 parser.add_argument('-e', '--eval', default=None,
Mark Mentovai 2014/06/12 13:49:43 The script used to accept multiple -e arguments, b
118 -i FILE, --input=FILE Read strings to substitute from FILE. 113 help='Evaluate VAL after reading variables. Can be used '
119 -o FILE, --output=FILE Write substituted strings to FILE. 114 'to synthesize variables. e.g. -e \'PATCH_HI=int('
120 -t TEMPLATE, --template=TEMPLATE Use TEMPLATE as the strings to substitute. 115 'PATCH)/256.')
121 -e VAR=VAL, --eval=VAR=VAL Evaluate VAL after reading variables. Can 116 parser.add_argument('args', nargs=argparse.REMAINDER,
122 be used to synthesize variables. e.g. 117 help='For compatibility: INPUT and OUTPUT can be '
123 -e 'PATCH_HI=int(PATCH)/256'. 118 'passed as positional arguments.')
124 -h, --help Print this help and exit. 119 options = parser.parse_args()
125 """
126 120
127 evals = {} 121 evals = {}
128 variable_files = [] 122 if options.eval is not None:
Mark Mentovai 2014/06/12 13:49:44 …this condition is no longer ever false. It should
129 in_file = None 123 try:
130 out_file = None 124 evals.update(dict([options.eval.split('=', 1)]))
131 template = None 125 except ValueError:
126 parser.error('-e requires VAR=VAL')
132 127
133 try: 128 # Compatibility with old versions that considered the first two positional
134 try: 129 # arguments shorthands for --input and --output.
135 opts, args = getopt.getopt(argv[1:], short_options, long_options) 130 while len(options.args) and (options.input is None or \
136 except getopt.error, err: 131 options.output is None):
137 raise Usage(err.msg) 132 if options.input is None:
138 for o, a in opts: 133 options.input = options.args.pop(0)
139 if o in ('-e', '--eval'): 134 elif options.output is None:
140 try: 135 options.output = options.args.pop(0)
141 evals.update(dict([a.split('=',1)])) 136 if options.args:
142 except ValueError: 137 parser.error('Unexpected arguments: %r' % options.args)
143 raise Usage("-e requires VAR=VAL")
144 elif o in ('-f', '--file'):
145 variable_files.append(a)
146 elif o in ('-i', '--input'):
147 in_file = a
148 elif o in ('-o', '--output'):
149 out_file = a
150 elif o in ('-t', '--template'):
151 template = a
152 elif o in ('-h', '--help'):
153 print helpstr
154 return 0
155 while len(args) and (in_file is None or out_file is None or
156 template is None):
157 if in_file is None:
158 in_file = args.pop(0)
159 elif out_file is None:
160 out_file = args.pop(0)
161 if args:
162 msg = 'Unexpected arguments: %r' % args
163 raise Usage(msg)
164 except Usage, err:
165 sys.stderr.write(err.msg)
166 sys.stderr.write('; Use -h to get help.\n')
167 return 2
168 138
169 values = fetch_values(variable_files) 139 values = fetch_values(options.file)
170 for key, val in evals.iteritems(): 140 for key, val in evals.iteritems():
171 values[key] = str(eval(val, globals(), values)) 141 values[key] = str(eval(val, globals(), values))
172 142
173 if template is not None: 143 if options.template is not None:
174 contents = subst_template(template, values) 144 contents = subst_template(options.template, values)
175 elif in_file: 145 elif options.input:
176 contents = subst_file(in_file, values) 146 contents = subst_file(options.input, values)
177 else: 147 else:
178 # Generate a default set of version information. 148 # Generate a default set of version information.
179 contents = """MAJOR=%(MAJOR)s 149 contents = """MAJOR=%(MAJOR)s
180 MINOR=%(MINOR)s 150 MINOR=%(MINOR)s
181 BUILD=%(BUILD)s 151 BUILD=%(BUILD)s
182 PATCH=%(PATCH)s 152 PATCH=%(PATCH)s
183 LASTCHANGE=%(LASTCHANGE)s 153 LASTCHANGE=%(LASTCHANGE)s
184 OFFICIAL_BUILD=%(OFFICIAL_BUILD)s 154 OFFICIAL_BUILD=%(OFFICIAL_BUILD)s
185 """ % values 155 """ % values
186 156
187 157 if options.output is not None:
188 if out_file: 158 write_if_changed(options.output, contents)
189 write_if_changed(out_file, contents)
190 else: 159 else:
191 print contents 160 print contents
192 161
193 return 0 162 return 0
194 163
195 164
196 if __name__ == '__main__': 165 if __name__ == '__main__':
197 sys.exit(main()) 166 sys.exit(main())
OLDNEW
« no previous file with comments | « no previous file | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698