Kiln » TortoiseHg » TortoiseHg
Clone URL:  
Pushed to one repository · View In Graph Contained in 2.0, 2.0.1, and 2.0.2

stable i18n: add python-gettext to i18n folder, use to build translations

The most recent version of gettext available for Windows is 1.14.4, which
does not support msgctxt. This removes one external requirement.

Changeset 6472f3d3c083

Parent 91132aba5fc0

by Steve Borho

Changes to 3 files · Browse files at 6472f3d3c083 Showing diff from parent 91132aba5fc0 Diff from another changeset...

Show Entire File i18n/​__init__.py Stacked
(No changes)
Change 1 of 1 Show Entire File i18n/​msgfmt.py Stacked
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
@@ -0,0 +1,200 @@
+#! /usr/bin/env python +# -*- coding: iso-8859-1 -*- +# Written by Martin v. Loewis <loewis@informatik.hu-berlin.de> +# +# Changed by Christian 'Tiran' Heimes <tiran@cheimes.de> for the placeless +# translation service (PTS) of Zope +# +# Fixed some bugs and updated to support msgctxt +# by Hanno Schlichting <hanno@hannosch.info> + +"""Generate binary message catalog from textual translation description. + +This program converts a textual Uniforum-style message catalog (.po file) into +a binary GNU catalog (.mo file). This is essentially the same function as the +GNU msgfmt program, however, it is a simpler implementation. + +This file was taken from Python-2.3.2/Tools/i18n and altered in several ways. +Now you can simply use it from another python module: + + from msgfmt import Msgfmt + mo = Msgfmt(po).get() + +where po is path to a po file as string, an opened po file ready for reading or +a list of strings (readlines of a po file) and mo is the compiled mo file as +binary string. + +Exceptions: + + * IOError if the file couldn't be read + + * msgfmt.PoSyntaxError if the po file has syntax errors + +""" +import struct +import array +from cStringIO import StringIO + +__version__ = "1.1-pythongettext" + +class PoSyntaxError(Exception): + """ Syntax error in a po file """ + def __init__(self, msg): + self.msg = msg + + def __str__(self): + return 'Po file syntax error: %s' % self.msg + +class Msgfmt: + """ """ + def __init__(self, po, name='unknown'): + self.po = po + self.name = name + self.messages = {} + self.openfile = False + + def readPoData(self): + """ read po data from self.po and return an iterator """ + output = [] + if isinstance(self.po, str): + output = open(self.po, 'rb') + elif isinstance(self.po, file): + self.po.seek(0) + self.openfile = True + output = self.po + elif isinstance(self.po, list): + output = self.po + if not output: + raise ValueError, "self.po is invalid! %s" % type(self.po) + return output + + def add(self, context, id, str, fuzzy): + "Add a non-empty and non-fuzzy translation to the dictionary." + if str and not fuzzy: + # The context is put before the id and separated by a EOT char. + if context: + id = context + '\x04' + id + self.messages[id] = str + + def generate(self): + "Return the generated output." + keys = self.messages.keys() + # the keys are sorted in the .mo file + keys.sort() + offsets = [] + ids = strs = '' + for id in keys: + # For each string, we need size and file offset. Each string is + # NUL terminated; the NUL does not count into the size. + offsets.append((len(ids), len(id), len(strs), + len(self.messages[id]))) + ids += id + '\0' + strs += self.messages[id] + '\0' + output = '' + # The header is 7 32-bit unsigned integers. We don't use hash tables, + # so the keys start right after the index tables. + keystart = 7*4+16*len(keys) + # and the values start after the keys + valuestart = keystart + len(ids) + koffsets = [] + voffsets = [] + # The string table first has the list of keys, then the list of values. + # Each entry has first the size of the string, then the file offset. + for o1, l1, o2, l2 in offsets: + koffsets += [l1, o1+keystart] + voffsets += [l2, o2+valuestart] + offsets = koffsets + voffsets + # Even though we don't use a hashtable, we still set its offset to be + # binary compatible with the gnu gettext format produced by: + # msgfmt file.po --no-hash + output = struct.pack("Iiiiiii", + 0x950412deL, # Magic + 0, # Version + len(keys), # # of entries + 7*4, # start of key index + 7*4+len(keys)*8, # start of value index + 0, keystart) # size and offset of hash table + output += array.array("i", offsets).tostring() + output += ids + output += strs + return output + + def get(self): + """ """ + self.read() + # Compute output + return self.generate() + + def read(self, header_only=False): + """ """ + ID = 1 + STR = 2 + CTXT = 3 + + section = None + fuzzy = 0 + msgid = msgstr = msgctxt = '' + + # Parse the catalog + lno = 0 + for l in self.readPoData(): + lno += 1 + # If we get a comment line after a msgstr or a line starting with + # msgid or msgctxt, this is a new entry + if section == STR and (l[0] == '#' or (l[0] == 'm' and + (l.startswith('msgctxt') or l.startswith('msgid')))): + + self.add(msgctxt, msgid, msgstr, fuzzy) + section = None + fuzzy = 0 + # If we only want the header we stop after the first message + if header_only: + break + # Record a fuzzy mark + if l[:2] == '#,' and 'fuzzy' in l: + fuzzy = 1 + # Skip comments + if l[0] == '#': + continue + # Now we are in a msgctxt section + elif l[0] == 'm': + if l.startswith('msgctxt'): + section = CTXT + l = l[7:] + msgctxt = '' + # Now we are in a msgid section, output previous section + elif l.startswith('msgid'): + section = ID + l = l[5:] + msgid = msgstr = '' + # Now we are in a msgstr section + elif l.startswith('msgstr'): + section = STR + l = l[6:] + # Skip empty lines + l = l.strip() + if not l: + continue + # XXX: Does this always follow Python escape semantics? + try: + l = eval(l) + except Exception, msg: + raise PoSyntaxError('%s (line %d of po file %s): \n%s' % (msg, lno, self.name, l)) + if section == CTXT: + msgctxt += l + elif section == ID: + msgid += l + elif section == STR: + msgstr += l + else: + raise PoSyntaxError('error in line %d of po file %s' % (lno, self.name)) + + # Add last entry + if section == STR: + self.add(msgctxt, msgid, msgstr, fuzzy) + + if self.openfile: + self.po.close() + + def getAsFile(self): + return StringIO(self.get())
Change 1 of 3 Show Changes Only setup.py Stacked
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
 
61
62
 
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 
 
 
 
 
41
42
43
44
45
46
47
48
49
50
51
52
 
 
 
 
53
54
 
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
 # setup.py  # A distutils setup script to install TortoiseHg in Windows and Posix  # environments.  #  # On Windows, this script is mostly used to build a stand-alone  # TortoiseHg package. See installer\build.txt for details. The other  # use is to report the current version of the TortoiseHg source.      import time  import sys  import os  import shutil  import subprocess  import cgi  from fnmatch import fnmatch  from distutils import log  from distutils.core import setup, Command  from distutils.command.build import build as _build_orig  from distutils.command.clean import clean as _clean_orig  from distutils.dep_util import newer, newer_group  from distutils.spawn import spawn, find_executable  from os.path import isdir, exists, join, walk, splitext +from i18n.msgfmt import Msgfmt    thgcopyright = 'Copyright (C) 2010 Steve Borho and others'  hgcopyright = 'Copyright (C) 2005-2010 Matt Mackall and others'    class build_mo(Command):     description = "build translations (.mo files)"   user_options = []     def initialize_options(self):   pass     def finalize_options(self):   pass     def run(self): - if not find_executable('msgfmt'): - self.warn("could not find msgfmt executable, no translations " - "will be built") - return -   podir = 'i18n/tortoisehg'   if not os.path.isdir(podir):   self.warn("could not find %s/ directory" % podir)   return     join = os.path.join   for po in os.listdir(podir):   if not po.endswith('.po'):   continue   pofile = join(podir, po)   modir = join('locale', po[:-3], 'LC_MESSAGES')   mofile = join(modir, 'tortoisehg.mo') - cmd = ['msgfmt', '-v', '-o', mofile, pofile] - if sys.platform != 'sunos5': - # msgfmt on Solaris does not know about -c - cmd.append('-c') + modata = Msgfmt(pofile).get()   self.mkpath(modir) - self.make_file([pofile], mofile, spawn, (cmd,)) + open(mofile, "wb").write(modata)    class update_pot(Command):     description = "extract translatable strings to tortoisehg.pot"   user_options = []     def initialize_options(self):   pass     def finalize_options(self):   pass     def run(self):   if not find_executable('xgettext'):   self.warn("could not find xgettext executable, tortoisehg.pot"   "won't be built")   return     dirlist = [   '.',   'contrib',   'contrib/win32',   'tortoisehg',   'tortoisehg/hgqt',   'tortoisehg/hgtk',   'tortoisehg/hgtk/logview',   'tortoisehg/util',   'tortoisehg/thgutil/iniparse',   ]     filelist = []   for pathname in dirlist:   if not os.path.exists(pathname):   continue   for filename in os.listdir(pathname):   if filename.endswith('.py'):   filelist.append(os.path.join(pathname, filename))     potfile = 'tortoisehg.pot'     cmd = [   'xgettext',   '--package-name', 'TortoiseHg',   '--msgid-bugs-address', '<thg-devel@googlegroups.com>',   '--copyright-holder', thgcopyright,   '--from-code', 'ISO-8859-1',   '--keyword=_:1,2c,2t',   '--add-comments=i18n:',   '-d', '.',   '-o', potfile,   ]   cmd += filelist   self.make_file(filelist, potfile, spawn, (cmd,))    class build_qt(Command):   description = "build PyQt GUIs (.ui) and resources (.qrc)"   user_options = [('force', 'f', 'forcibly compile everything'   ' (ignore file timestamps)')]   boolean_options = ('force',)     def initialize_options(self):   self.force = None     def finalize_options(self):   self.set_undefined_options('build', ('force', 'force'))     def compile_ui(self, ui_file, py_file=None):   # Search for pyuic4 in python bin dir, then in the $Path.   if py_file is None:   py_file = splitext(ui_file)[0] + "_ui.py"   if not(self.force or newer(ui_file, py_file)):   return   try:   from PyQt4 import uic   fp = open(py_file, 'w')   uic.compileUi(ui_file, fp)   fp.close()   log.info('compiled %s into %s' % (ui_file, py_file))   except Exception, e:   self.warn('Unable to compile user interface %s: %s' % (py_file, e))   if not exists(py_file) or not file(py_file).read():   raise SystemExit(1)   return     def compile_rc(self, qrc_file, py_file=None):   # Search for pyuic4 in python bin dir, then in the $Path.   if py_file is None:   py_file = splitext(qrc_file)[0] + "_rc.py"   if not(self.force or newer(qrc_file, py_file)):   return   if os.system('pyrcc4 "%s" -o "%s"' % (qrc_file, py_file)) > 0:   self.warn("Unable to generate python module %s for resource file %s"   % (py_file, qrc_file))   if not exists(py_file) or not file(py_file).read():   raise SystemExit(1)   else:   log.info('compiled %s into %s' % (qrc_file, py_file))     def _generate_qrc(self, qrc_file, srcfiles, prefix):   basedir = os.path.dirname(qrc_file)   f = open(qrc_file, 'w')   try:   f.write('<!DOCTYPE RCC><RCC version="1.0">\n')   f.write(' <qresource prefix="%s">\n' % cgi.escape(prefix))   for e in srcfiles:   relpath = e[len(basedir) + 1:]   f.write(' <file>%s</file>\n'   % cgi.escape(relpath.replace(os.path.sep, '/')))   f.write(' </qresource>\n')   f.write('</RCC>\n')   finally:   f.close()     def build_rc(self, py_file, basedir, prefix='/'):   """Generate compiled resource including any files under basedir"""   # For details, see http://doc.qt.nokia.com/latest/resources.html   qrc_file = os.path.join(basedir, '%s.qrc' % os.path.basename(basedir))   srcfiles = [os.path.join(root, e)   for root, _dirs, files in os.walk(basedir) for e in files]   # NOTE: Here we cannot detect deleted files. In such case, we need   # to remove .qrc manually.   if not (self.force or newer_group(srcfiles, py_file)):   return   try:   self._generate_qrc(qrc_file, srcfiles, prefix)   self.compile_rc(qrc_file, py_file)   finally:   os.unlink(qrc_file)     def run(self):   self._wrapuic()   basepath = join(os.path.dirname(__file__), 'tortoisehg', 'hgqt')   self.build_rc(os.path.join(basepath, 'icons_rc.py'),   os.path.join(os.path.dirname(__file__), 'icons'),   '/icons')   for dirpath, _, filenames in os.walk(basepath):   for filename in filenames:   if filename.endswith('.ui'):   self.compile_ui(join(dirpath, filename))   elif filename.endswith('.qrc'):   self.compile_rc(join(dirpath, filename))     _wrappeduic = False   @classmethod   def _wrapuic(cls):   """wrap uic to use gettext's _() in place of tr()"""   if cls._wrappeduic:   return     from PyQt4.uic.Compiler import compiler, qtproxies, indenter     class _UICompiler(compiler.UICompiler):   def createToplevelWidget(self, classname, widgetname):   o = indenter.getIndenter()   o.level = 0   o.write('from tortoisehg.hgqt.i18n import _')   return super(_UICompiler, self).createToplevelWidget(classname, widgetname)   compiler.UICompiler = _UICompiler     class _i18n_string(qtproxies.i18n_string):   def __str__(self):   return "_('%s')" % self.string.encode('string-escape')   qtproxies.i18n_string = _i18n_string     cls._wrappeduic = True    class clean_local(Command):   pats = ['*.py[co]', '*_ui.py', '*_rc.py', '*.orig', '*.rej']   excludedirs = ['.hg', 'build', 'dist']   description = 'clean up generated files (%s)' % ', '.join(pats)   user_options = []     def initialize_options(self):   pass     def finalize_options(self):   pass     def run(self):   for e in self._walkpaths('.'):   log.info("removing '%s'" % e)   os.remove(e)     def _walkpaths(self, path):   for root, _dirs, files in os.walk(path):   if any(root == join(path, e) or root.startswith(join(path, e, ''))   for e in self.excludedirs):   continue   for e in files:   fpath = join(root, e)   if any(fnmatch(fpath, p) for p in self.pats):   yield fpath    class build(_build_orig):   sub_commands = [   ('build_qt', None),   ('build_mo', None),   ] + _build_orig.sub_commands    class clean(_clean_orig):   sub_commands = [   ('clean_local', None),   ] + _clean_orig.sub_commands     def run(self):   _clean_orig.run(self)   for e in self.get_sub_commands():   self.run_command(e)    cmdclass = {   'build': build,   'build_qt': build_qt ,   'build_mo': build_mo ,   'clean': clean,   'clean_local': clean_local,   'update_pot': update_pot ,   }    def setup_windows(version):   # Specific definitios for Windows NT-alike installations   _scripts = []   _data_files = []   _packages = ['tortoisehg.hgqt', 'tortoisehg.util', 'tortoisehg']   extra = {}   hgextmods = []     # py2exe needs to be installed to work   try:   import py2exe     # Help py2exe to find win32com.shell   try:   import modulefinder   import win32com   for p in win32com.__path__[1:]: # Take the path to win32comext   modulefinder.AddPackagePath("win32com", p)   pn = "win32com.shell"   __import__(pn)   m = sys.modules[pn]   for p in m.__path__[1:]:   modulefinder.AddPackagePath(pn, p)   except ImportError:   pass     except ImportError:   if '--version' not in sys.argv:   raise     if 'py2exe' in sys.argv:   import hgext   hgextdir = os.path.dirname(hgext.__file__)   hgextmods = set(["hgext." + os.path.splitext(f)[0]   for f in os.listdir(hgextdir)])   _data_files = [(root, [os.path.join(root, file_) for file_ in files])   for root, dirs, files in os.walk('icons')]     # for PyQt, see http://www.py2exe.org/index.cgi/Py2exeAndPyQt   includes = ['sip']     # Qt4 plugins, see http://stackoverflow.com/questions/2206406/   def qt4_plugins(subdir, *dlls):   import PyQt4   pluginsdir = join(os.path.dirname(PyQt4.__file__), 'plugins')   return (subdir, [join(pluginsdir, subdir, e) for e in dlls])   _data_files.append(qt4_plugins('imageformats', 'qico4.dll', 'qsvg4.dll'))     # Manually include other modules py2exe can't find by itself.   if 'hgext.highlight' in hgextmods:   includes += ['pygments.*', 'pygments.lexers.*', 'pygments.formatters.*',   'pygments.filters.*', 'pygments.styles.*']   if 'hgext.patchbomb' in hgextmods:   includes += ['email.*', 'email.mime.*']     extra['options'] = {   "py2exe" : {   "skip_archive" : 0,     # Don't pull in all this MFC stuff used by the makepy UI.   "excludes" : "pywin,pywin.dialogs,pywin.dialogs.list"   ",setup,distutils", # required only for in-place use   "includes" : includes,   "optimize" : 1   }   }   shutil.copyfile('thg', 'thgw')   extra['console'] = [   {'script':'thg',   'icon_resources':[(0,'icons/thg_logo.ico')],   'description':'TortoiseHg GUI tools for Mercurial SCM',   'copyright':thgcopyright,   'product_version':version},   {'script':'contrib/hg',   'icon_resources':[(0,'icons/hg.ico')],   'description':'Mercurial Distributed SCM',   'copyright':hgcopyright,   'product_version':version},   {'script':'win32/docdiff.py',   'icon_resources':[(0,'icons/TortoiseMerge.ico')],   'copyright':thgcopyright,   'product_version':version}   ]   extra['windows'] = [   {'script':'thgw',   'icon_resources':[(0,'icons/thg_logo.ico')],   'description':'TortoiseHg GUI tools for Mercurial SCM',   'copyright':thgcopyright,   'product_version':version},   {'script':'TortoiseHgOverlayServer.py',   'icon_resources':[(0,'icons/thg_logo.ico')],   'description':'TortoiseHg Overlay Icon Server',   'copyright':thgcopyright,   'product_version':version}   ]     return _scripts, _packages, _data_files, extra      def setup_posix():   # Specific definitios for Posix installations   _extra = {}   _scripts = ['thg']   _packages = ['tortoisehg', 'tortoisehg.hgqt', 'tortoisehg.util']   _data_files = [(os.path.join('share/pixmaps/tortoisehg', root),   [os.path.join(root, file_) for file_ in files])   for root, dirs, files in os.walk('icons')]   _data_files += [(os.path.join('share', root),   [os.path.join(root, file_) for file_ in files])   for root, dirs, files in os.walk('locale')]   _data_files += [('lib/nautilus/extensions-2.0/python',   ['contrib/nautilus-thg.py'])]     # Create a config.py. Distributions will need to supply their own   cfgfile = os.path.join('tortoisehg', 'util', 'config.py')   if not os.path.exists(cfgfile) and not os.path.exists('.hg/requires'):   f = open(cfgfile, "w")   f.write('bin_path = "/usr/bin"\n')   f.write('license_path = "/usr/share/doc/tortoisehg/Copying.txt.gz"\n')   f.write('locale_path = "/usr/share/locale"\n')   f.write('icon_path = "/usr/share/pixmaps/tortoisehg/icons"\n')   f.write('nofork = True\n')   f.close()     return _scripts, _packages, _data_files, _extra    def runcmd(cmd, env):   p = subprocess.Popen(cmd, stdout=subprocess.PIPE,   stderr=subprocess.PIPE, env=env)   out, err = p.communicate()   # If root is executing setup.py, but the repository is owned by   # another user (as in "sudo python setup.py install") we will get   # trust warnings since the .hg/hgrc file is untrusted. That is   # fine, we don't want to load it anyway.   err = [e for e in err.splitlines()   if not e.startswith('Not trusting file')]   if err:   return ''   return out    if __name__ == '__main__':   version = ''     if os.path.isdir('.hg'):   from tortoisehg.util import version as _version   branch, version = _version.liveversion()   if version.endswith('+'):   version += time.strftime('%Y%m%d')   elif os.path.exists('.hg_archival.txt'):   kw = dict([t.strip() for t in l.split(':', 1)]   for l in open('.hg_archival.txt'))   if 'tag' in kw:   version = kw['tag']   elif 'latesttag' in kw:   version = '%(latesttag)s+%(latesttagdistance)s-%(node).12s' % kw   else:   version = kw.get('node', '')[:12]     if version:   f = open("tortoisehg/util/__version__.py", "w")   f.write('# this file is autogenerated by setup.py\n')   f.write('version = "%s"\n' % version)   f.close()     try:   import tortoisehg.util.__version__   version = tortoisehg.util.__version__.version   except ImportError:   version = 'unknown'     if os.name == "nt":   (scripts, packages, data_files, extra) = setup_windows(version)   desc = 'Windows shell extension for Mercurial VCS'   # Windows binary file versions for exe/dll files must have the   # form W.X.Y.Z, where W,X,Y,Z are numbers in the range 0..65535   from tortoisehg.util.version import package_version   setupversion = package_version()   productname = 'TortoiseHg'   else:   (scripts, packages, data_files, extra) = setup_posix()   desc = 'TortoiseHg dialogs for Mercurial VCS'   setupversion = version   productname = 'tortoisehg'     setup(name=productname,   version=setupversion,   author='Steve Borho',   author_email='steve@borho.org',   url='http://tortoisehg.org',   description=desc,   license='GNU GPL2',   scripts=scripts,   packages=packages,   data_files=data_files,   cmdclass=cmdclass,   **extra   )