##// END OF EJS Templates
py3: make setup.py's hgcommand() consistently return bytes...
Martin von Zweigbergk -
r45094:bda050bc stable
parent child Browse files
Show More
@@ -1,1729 +1,1729
1 #
1 #
2 # This is the mercurial setup script.
2 # This is the mercurial setup script.
3 #
3 #
4 # 'python setup.py install', or
4 # 'python setup.py install', or
5 # 'python setup.py --help' for more options
5 # 'python setup.py --help' for more options
6
6
7 import os
7 import os
8
8
9 # Mercurial will never work on Python 3 before 3.5 due to a lack
9 # Mercurial will never work on Python 3 before 3.5 due to a lack
10 # of % formatting on bytestrings, and can't work on 3.6.0 or 3.6.1
10 # of % formatting on bytestrings, and can't work on 3.6.0 or 3.6.1
11 # due to a bug in % formatting in bytestrings.
11 # due to a bug in % formatting in bytestrings.
12 # We cannot support Python 3.5.0, 3.5.1, 3.5.2 because of bug in
12 # We cannot support Python 3.5.0, 3.5.1, 3.5.2 because of bug in
13 # codecs.escape_encode() where it raises SystemError on empty bytestring
13 # codecs.escape_encode() where it raises SystemError on empty bytestring
14 # bug link: https://bugs.python.org/issue25270
14 # bug link: https://bugs.python.org/issue25270
15 supportedpy = ','.join(
15 supportedpy = ','.join(
16 [
16 [
17 '>=2.7',
17 '>=2.7',
18 '!=3.0.*',
18 '!=3.0.*',
19 '!=3.1.*',
19 '!=3.1.*',
20 '!=3.2.*',
20 '!=3.2.*',
21 '!=3.3.*',
21 '!=3.3.*',
22 '!=3.4.*',
22 '!=3.4.*',
23 '!=3.5.0',
23 '!=3.5.0',
24 '!=3.5.1',
24 '!=3.5.1',
25 '!=3.5.2',
25 '!=3.5.2',
26 '!=3.6.0',
26 '!=3.6.0',
27 '!=3.6.1',
27 '!=3.6.1',
28 ]
28 ]
29 )
29 )
30
30
31 import sys, platform
31 import sys, platform
32 import sysconfig
32 import sysconfig
33
33
34 if sys.version_info[0] >= 3:
34 if sys.version_info[0] >= 3:
35 printf = eval('print')
35 printf = eval('print')
36 libdir_escape = 'unicode_escape'
36 libdir_escape = 'unicode_escape'
37
37
38 def sysstr(s):
38 def sysstr(s):
39 return s.decode('latin-1')
39 return s.decode('latin-1')
40
40
41
41
42 else:
42 else:
43 libdir_escape = 'string_escape'
43 libdir_escape = 'string_escape'
44
44
45 def printf(*args, **kwargs):
45 def printf(*args, **kwargs):
46 f = kwargs.get('file', sys.stdout)
46 f = kwargs.get('file', sys.stdout)
47 end = kwargs.get('end', '\n')
47 end = kwargs.get('end', '\n')
48 f.write(b' '.join(args) + end)
48 f.write(b' '.join(args) + end)
49
49
50 def sysstr(s):
50 def sysstr(s):
51 return s
51 return s
52
52
53
53
54 # Attempt to guide users to a modern pip - this means that 2.6 users
54 # Attempt to guide users to a modern pip - this means that 2.6 users
55 # should have a chance of getting a 4.2 release, and when we ratchet
55 # should have a chance of getting a 4.2 release, and when we ratchet
56 # the version requirement forward again hopefully everyone will get
56 # the version requirement forward again hopefully everyone will get
57 # something that works for them.
57 # something that works for them.
58 if sys.version_info < (2, 7, 0, 'final'):
58 if sys.version_info < (2, 7, 0, 'final'):
59 pip_message = (
59 pip_message = (
60 'This may be due to an out of date pip. '
60 'This may be due to an out of date pip. '
61 'Make sure you have pip >= 9.0.1.'
61 'Make sure you have pip >= 9.0.1.'
62 )
62 )
63 try:
63 try:
64 import pip
64 import pip
65
65
66 pip_version = tuple([int(x) for x in pip.__version__.split('.')[:3]])
66 pip_version = tuple([int(x) for x in pip.__version__.split('.')[:3]])
67 if pip_version < (9, 0, 1):
67 if pip_version < (9, 0, 1):
68 pip_message = (
68 pip_message = (
69 'Your pip version is out of date, please install '
69 'Your pip version is out of date, please install '
70 'pip >= 9.0.1. pip {} detected.'.format(pip.__version__)
70 'pip >= 9.0.1. pip {} detected.'.format(pip.__version__)
71 )
71 )
72 else:
72 else:
73 # pip is new enough - it must be something else
73 # pip is new enough - it must be something else
74 pip_message = ''
74 pip_message = ''
75 except Exception:
75 except Exception:
76 pass
76 pass
77 error = """
77 error = """
78 Mercurial does not support Python older than 2.7.
78 Mercurial does not support Python older than 2.7.
79 Python {py} detected.
79 Python {py} detected.
80 {pip}
80 {pip}
81 """.format(
81 """.format(
82 py=sys.version_info, pip=pip_message
82 py=sys.version_info, pip=pip_message
83 )
83 )
84 printf(error, file=sys.stderr)
84 printf(error, file=sys.stderr)
85 sys.exit(1)
85 sys.exit(1)
86
86
87 if sys.version_info[0] >= 3:
87 if sys.version_info[0] >= 3:
88 DYLIB_SUFFIX = sysconfig.get_config_vars()['EXT_SUFFIX']
88 DYLIB_SUFFIX = sysconfig.get_config_vars()['EXT_SUFFIX']
89 else:
89 else:
90 # deprecated in Python 3
90 # deprecated in Python 3
91 DYLIB_SUFFIX = sysconfig.get_config_vars()['SO']
91 DYLIB_SUFFIX = sysconfig.get_config_vars()['SO']
92
92
93 # Solaris Python packaging brain damage
93 # Solaris Python packaging brain damage
94 try:
94 try:
95 import hashlib
95 import hashlib
96
96
97 sha = hashlib.sha1()
97 sha = hashlib.sha1()
98 except ImportError:
98 except ImportError:
99 try:
99 try:
100 import sha
100 import sha
101
101
102 sha.sha # silence unused import warning
102 sha.sha # silence unused import warning
103 except ImportError:
103 except ImportError:
104 raise SystemExit(
104 raise SystemExit(
105 "Couldn't import standard hashlib (incomplete Python install)."
105 "Couldn't import standard hashlib (incomplete Python install)."
106 )
106 )
107
107
108 try:
108 try:
109 import zlib
109 import zlib
110
110
111 zlib.compressobj # silence unused import warning
111 zlib.compressobj # silence unused import warning
112 except ImportError:
112 except ImportError:
113 raise SystemExit(
113 raise SystemExit(
114 "Couldn't import standard zlib (incomplete Python install)."
114 "Couldn't import standard zlib (incomplete Python install)."
115 )
115 )
116
116
117 # The base IronPython distribution (as of 2.7.1) doesn't support bz2
117 # The base IronPython distribution (as of 2.7.1) doesn't support bz2
118 isironpython = False
118 isironpython = False
119 try:
119 try:
120 isironpython = (
120 isironpython = (
121 platform.python_implementation().lower().find("ironpython") != -1
121 platform.python_implementation().lower().find("ironpython") != -1
122 )
122 )
123 except AttributeError:
123 except AttributeError:
124 pass
124 pass
125
125
126 if isironpython:
126 if isironpython:
127 sys.stderr.write("warning: IronPython detected (no bz2 support)\n")
127 sys.stderr.write("warning: IronPython detected (no bz2 support)\n")
128 else:
128 else:
129 try:
129 try:
130 import bz2
130 import bz2
131
131
132 bz2.BZ2Compressor # silence unused import warning
132 bz2.BZ2Compressor # silence unused import warning
133 except ImportError:
133 except ImportError:
134 raise SystemExit(
134 raise SystemExit(
135 "Couldn't import standard bz2 (incomplete Python install)."
135 "Couldn't import standard bz2 (incomplete Python install)."
136 )
136 )
137
137
138 ispypy = "PyPy" in sys.version
138 ispypy = "PyPy" in sys.version
139
139
140 hgrustext = os.environ.get('HGWITHRUSTEXT')
140 hgrustext = os.environ.get('HGWITHRUSTEXT')
141 # TODO record it for proper rebuild upon changes
141 # TODO record it for proper rebuild upon changes
142 # (see mercurial/__modulepolicy__.py)
142 # (see mercurial/__modulepolicy__.py)
143 if hgrustext != 'cpython' and hgrustext is not None:
143 if hgrustext != 'cpython' and hgrustext is not None:
144 hgrustext = 'direct-ffi'
144 hgrustext = 'direct-ffi'
145
145
146 import ctypes
146 import ctypes
147 import errno
147 import errno
148 import stat, subprocess, time
148 import stat, subprocess, time
149 import re
149 import re
150 import shutil
150 import shutil
151 import tempfile
151 import tempfile
152 from distutils import log
152 from distutils import log
153
153
154 # We have issues with setuptools on some platforms and builders. Until
154 # We have issues with setuptools on some platforms and builders. Until
155 # those are resolved, setuptools is opt-in except for platforms where
155 # those are resolved, setuptools is opt-in except for platforms where
156 # we don't have issues.
156 # we don't have issues.
157 issetuptools = os.name == 'nt' or 'FORCE_SETUPTOOLS' in os.environ
157 issetuptools = os.name == 'nt' or 'FORCE_SETUPTOOLS' in os.environ
158 if issetuptools:
158 if issetuptools:
159 from setuptools import setup
159 from setuptools import setup
160 else:
160 else:
161 from distutils.core import setup
161 from distutils.core import setup
162 from distutils.ccompiler import new_compiler
162 from distutils.ccompiler import new_compiler
163 from distutils.core import Command, Extension
163 from distutils.core import Command, Extension
164 from distutils.dist import Distribution
164 from distutils.dist import Distribution
165 from distutils.command.build import build
165 from distutils.command.build import build
166 from distutils.command.build_ext import build_ext
166 from distutils.command.build_ext import build_ext
167 from distutils.command.build_py import build_py
167 from distutils.command.build_py import build_py
168 from distutils.command.build_scripts import build_scripts
168 from distutils.command.build_scripts import build_scripts
169 from distutils.command.install import install
169 from distutils.command.install import install
170 from distutils.command.install_lib import install_lib
170 from distutils.command.install_lib import install_lib
171 from distutils.command.install_scripts import install_scripts
171 from distutils.command.install_scripts import install_scripts
172 from distutils.spawn import spawn, find_executable
172 from distutils.spawn import spawn, find_executable
173 from distutils import file_util
173 from distutils import file_util
174 from distutils.errors import (
174 from distutils.errors import (
175 CCompilerError,
175 CCompilerError,
176 DistutilsError,
176 DistutilsError,
177 DistutilsExecError,
177 DistutilsExecError,
178 )
178 )
179 from distutils.sysconfig import get_python_inc, get_config_var
179 from distutils.sysconfig import get_python_inc, get_config_var
180 from distutils.version import StrictVersion
180 from distutils.version import StrictVersion
181
181
182 # Explain to distutils.StrictVersion how our release candidates are versionned
182 # Explain to distutils.StrictVersion how our release candidates are versionned
183 StrictVersion.version_re = re.compile(r'^(\d+)\.(\d+)(\.(\d+))?-?(rc(\d+))?$')
183 StrictVersion.version_re = re.compile(r'^(\d+)\.(\d+)(\.(\d+))?-?(rc(\d+))?$')
184
184
185
185
186 def write_if_changed(path, content):
186 def write_if_changed(path, content):
187 """Write content to a file iff the content hasn't changed."""
187 """Write content to a file iff the content hasn't changed."""
188 if os.path.exists(path):
188 if os.path.exists(path):
189 with open(path, 'rb') as fh:
189 with open(path, 'rb') as fh:
190 current = fh.read()
190 current = fh.read()
191 else:
191 else:
192 current = b''
192 current = b''
193
193
194 if current != content:
194 if current != content:
195 with open(path, 'wb') as fh:
195 with open(path, 'wb') as fh:
196 fh.write(content)
196 fh.write(content)
197
197
198
198
199 scripts = ['hg']
199 scripts = ['hg']
200 if os.name == 'nt':
200 if os.name == 'nt':
201 # We remove hg.bat if we are able to build hg.exe.
201 # We remove hg.bat if we are able to build hg.exe.
202 scripts.append('contrib/win32/hg.bat')
202 scripts.append('contrib/win32/hg.bat')
203
203
204
204
205 def cancompile(cc, code):
205 def cancompile(cc, code):
206 tmpdir = tempfile.mkdtemp(prefix='hg-install-')
206 tmpdir = tempfile.mkdtemp(prefix='hg-install-')
207 devnull = oldstderr = None
207 devnull = oldstderr = None
208 try:
208 try:
209 fname = os.path.join(tmpdir, 'testcomp.c')
209 fname = os.path.join(tmpdir, 'testcomp.c')
210 f = open(fname, 'w')
210 f = open(fname, 'w')
211 f.write(code)
211 f.write(code)
212 f.close()
212 f.close()
213 # Redirect stderr to /dev/null to hide any error messages
213 # Redirect stderr to /dev/null to hide any error messages
214 # from the compiler.
214 # from the compiler.
215 # This will have to be changed if we ever have to check
215 # This will have to be changed if we ever have to check
216 # for a function on Windows.
216 # for a function on Windows.
217 devnull = open('/dev/null', 'w')
217 devnull = open('/dev/null', 'w')
218 oldstderr = os.dup(sys.stderr.fileno())
218 oldstderr = os.dup(sys.stderr.fileno())
219 os.dup2(devnull.fileno(), sys.stderr.fileno())
219 os.dup2(devnull.fileno(), sys.stderr.fileno())
220 objects = cc.compile([fname], output_dir=tmpdir)
220 objects = cc.compile([fname], output_dir=tmpdir)
221 cc.link_executable(objects, os.path.join(tmpdir, "a.out"))
221 cc.link_executable(objects, os.path.join(tmpdir, "a.out"))
222 return True
222 return True
223 except Exception:
223 except Exception:
224 return False
224 return False
225 finally:
225 finally:
226 if oldstderr is not None:
226 if oldstderr is not None:
227 os.dup2(oldstderr, sys.stderr.fileno())
227 os.dup2(oldstderr, sys.stderr.fileno())
228 if devnull is not None:
228 if devnull is not None:
229 devnull.close()
229 devnull.close()
230 shutil.rmtree(tmpdir)
230 shutil.rmtree(tmpdir)
231
231
232
232
233 # simplified version of distutils.ccompiler.CCompiler.has_function
233 # simplified version of distutils.ccompiler.CCompiler.has_function
234 # that actually removes its temporary files.
234 # that actually removes its temporary files.
235 def hasfunction(cc, funcname):
235 def hasfunction(cc, funcname):
236 code = 'int main(void) { %s(); }\n' % funcname
236 code = 'int main(void) { %s(); }\n' % funcname
237 return cancompile(cc, code)
237 return cancompile(cc, code)
238
238
239
239
240 def hasheader(cc, headername):
240 def hasheader(cc, headername):
241 code = '#include <%s>\nint main(void) { return 0; }\n' % headername
241 code = '#include <%s>\nint main(void) { return 0; }\n' % headername
242 return cancompile(cc, code)
242 return cancompile(cc, code)
243
243
244
244
245 # py2exe needs to be installed to work
245 # py2exe needs to be installed to work
246 try:
246 try:
247 import py2exe
247 import py2exe
248
248
249 py2exe.Distribution # silence unused import warning
249 py2exe.Distribution # silence unused import warning
250 py2exeloaded = True
250 py2exeloaded = True
251 # import py2exe's patched Distribution class
251 # import py2exe's patched Distribution class
252 from distutils.core import Distribution
252 from distutils.core import Distribution
253 except ImportError:
253 except ImportError:
254 py2exeloaded = False
254 py2exeloaded = False
255
255
256
256
257 def runcmd(cmd, env, cwd=None):
257 def runcmd(cmd, env, cwd=None):
258 p = subprocess.Popen(
258 p = subprocess.Popen(
259 cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, cwd=cwd
259 cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, cwd=cwd
260 )
260 )
261 out, err = p.communicate()
261 out, err = p.communicate()
262 return p.returncode, out, err
262 return p.returncode, out, err
263
263
264
264
265 class hgcommand(object):
265 class hgcommand(object):
266 def __init__(self, cmd, env):
266 def __init__(self, cmd, env):
267 self.cmd = cmd
267 self.cmd = cmd
268 self.env = env
268 self.env = env
269
269
270 def run(self, args):
270 def run(self, args):
271 cmd = self.cmd + args
271 cmd = self.cmd + args
272 returncode, out, err = runcmd(cmd, self.env)
272 returncode, out, err = runcmd(cmd, self.env)
273 err = filterhgerr(err)
273 err = filterhgerr(err)
274 if err or returncode != 0:
274 if err or returncode != 0:
275 printf("stderr from '%s':" % (' '.join(cmd)), file=sys.stderr)
275 printf("stderr from '%s':" % (' '.join(cmd)), file=sys.stderr)
276 printf(err, file=sys.stderr)
276 printf(err, file=sys.stderr)
277 return ''
277 return b''
278 return out
278 return out
279
279
280
280
281 def filterhgerr(err):
281 def filterhgerr(err):
282 # If root is executing setup.py, but the repository is owned by
282 # If root is executing setup.py, but the repository is owned by
283 # another user (as in "sudo python setup.py install") we will get
283 # another user (as in "sudo python setup.py install") we will get
284 # trust warnings since the .hg/hgrc file is untrusted. That is
284 # trust warnings since the .hg/hgrc file is untrusted. That is
285 # fine, we don't want to load it anyway. Python may warn about
285 # fine, we don't want to load it anyway. Python may warn about
286 # a missing __init__.py in mercurial/locale, we also ignore that.
286 # a missing __init__.py in mercurial/locale, we also ignore that.
287 err = [
287 err = [
288 e
288 e
289 for e in err.splitlines()
289 for e in err.splitlines()
290 if (
290 if (
291 not e.startswith(b'not trusting file')
291 not e.startswith(b'not trusting file')
292 and not e.startswith(b'warning: Not importing')
292 and not e.startswith(b'warning: Not importing')
293 and not e.startswith(b'obsolete feature not enabled')
293 and not e.startswith(b'obsolete feature not enabled')
294 and not e.startswith(b'*** failed to import extension')
294 and not e.startswith(b'*** failed to import extension')
295 and not e.startswith(b'devel-warn:')
295 and not e.startswith(b'devel-warn:')
296 and not (
296 and not (
297 e.startswith(b'(third party extension')
297 e.startswith(b'(third party extension')
298 and e.endswith(b'or newer of Mercurial; disabling)')
298 and e.endswith(b'or newer of Mercurial; disabling)')
299 )
299 )
300 )
300 )
301 ]
301 ]
302 return b'\n'.join(b' ' + e for e in err)
302 return b'\n'.join(b' ' + e for e in err)
303
303
304
304
305 def findhg():
305 def findhg():
306 """Try to figure out how we should invoke hg for examining the local
306 """Try to figure out how we should invoke hg for examining the local
307 repository contents.
307 repository contents.
308
308
309 Returns an hgcommand object."""
309 Returns an hgcommand object."""
310 # By default, prefer the "hg" command in the user's path. This was
310 # By default, prefer the "hg" command in the user's path. This was
311 # presumably the hg command that the user used to create this repository.
311 # presumably the hg command that the user used to create this repository.
312 #
312 #
313 # This repository may require extensions or other settings that would not
313 # This repository may require extensions or other settings that would not
314 # be enabled by running the hg script directly from this local repository.
314 # be enabled by running the hg script directly from this local repository.
315 hgenv = os.environ.copy()
315 hgenv = os.environ.copy()
316 # Use HGPLAIN to disable hgrc settings that would change output formatting,
316 # Use HGPLAIN to disable hgrc settings that would change output formatting,
317 # and disable localization for the same reasons.
317 # and disable localization for the same reasons.
318 hgenv['HGPLAIN'] = '1'
318 hgenv['HGPLAIN'] = '1'
319 hgenv['LANGUAGE'] = 'C'
319 hgenv['LANGUAGE'] = 'C'
320 hgcmd = ['hg']
320 hgcmd = ['hg']
321 # Run a simple "hg log" command just to see if using hg from the user's
321 # Run a simple "hg log" command just to see if using hg from the user's
322 # path works and can successfully interact with this repository. Windows
322 # path works and can successfully interact with this repository. Windows
323 # gives precedence to hg.exe in the current directory, so fall back to the
323 # gives precedence to hg.exe in the current directory, so fall back to the
324 # python invocation of local hg, where pythonXY.dll can always be found.
324 # python invocation of local hg, where pythonXY.dll can always be found.
325 check_cmd = ['log', '-r.', '-Ttest']
325 check_cmd = ['log', '-r.', '-Ttest']
326 if os.name != 'nt':
326 if os.name != 'nt':
327 try:
327 try:
328 retcode, out, err = runcmd(hgcmd + check_cmd, hgenv)
328 retcode, out, err = runcmd(hgcmd + check_cmd, hgenv)
329 except EnvironmentError:
329 except EnvironmentError:
330 retcode = -1
330 retcode = -1
331 if retcode == 0 and not filterhgerr(err):
331 if retcode == 0 and not filterhgerr(err):
332 return hgcommand(hgcmd, hgenv)
332 return hgcommand(hgcmd, hgenv)
333
333
334 # Fall back to trying the local hg installation.
334 # Fall back to trying the local hg installation.
335 hgenv = localhgenv()
335 hgenv = localhgenv()
336 hgcmd = [sys.executable, 'hg']
336 hgcmd = [sys.executable, 'hg']
337 try:
337 try:
338 retcode, out, err = runcmd(hgcmd + check_cmd, hgenv)
338 retcode, out, err = runcmd(hgcmd + check_cmd, hgenv)
339 except EnvironmentError:
339 except EnvironmentError:
340 retcode = -1
340 retcode = -1
341 if retcode == 0 and not filterhgerr(err):
341 if retcode == 0 and not filterhgerr(err):
342 return hgcommand(hgcmd, hgenv)
342 return hgcommand(hgcmd, hgenv)
343
343
344 raise SystemExit(
344 raise SystemExit(
345 'Unable to find a working hg binary to extract the '
345 'Unable to find a working hg binary to extract the '
346 'version from the repository tags'
346 'version from the repository tags'
347 )
347 )
348
348
349
349
350 def localhgenv():
350 def localhgenv():
351 """Get an environment dictionary to use for invoking or importing
351 """Get an environment dictionary to use for invoking or importing
352 mercurial from the local repository."""
352 mercurial from the local repository."""
353 # Execute hg out of this directory with a custom environment which takes
353 # Execute hg out of this directory with a custom environment which takes
354 # care to not use any hgrc files and do no localization.
354 # care to not use any hgrc files and do no localization.
355 env = {
355 env = {
356 'HGMODULEPOLICY': 'py',
356 'HGMODULEPOLICY': 'py',
357 'HGRCPATH': '',
357 'HGRCPATH': '',
358 'LANGUAGE': 'C',
358 'LANGUAGE': 'C',
359 'PATH': '',
359 'PATH': '',
360 } # make pypi modules that use os.environ['PATH'] happy
360 } # make pypi modules that use os.environ['PATH'] happy
361 if 'LD_LIBRARY_PATH' in os.environ:
361 if 'LD_LIBRARY_PATH' in os.environ:
362 env['LD_LIBRARY_PATH'] = os.environ['LD_LIBRARY_PATH']
362 env['LD_LIBRARY_PATH'] = os.environ['LD_LIBRARY_PATH']
363 if 'SystemRoot' in os.environ:
363 if 'SystemRoot' in os.environ:
364 # SystemRoot is required by Windows to load various DLLs. See:
364 # SystemRoot is required by Windows to load various DLLs. See:
365 # https://bugs.python.org/issue13524#msg148850
365 # https://bugs.python.org/issue13524#msg148850
366 env['SystemRoot'] = os.environ['SystemRoot']
366 env['SystemRoot'] = os.environ['SystemRoot']
367 return env
367 return env
368
368
369
369
370 version = ''
370 version = ''
371
371
372 if os.path.isdir('.hg'):
372 if os.path.isdir('.hg'):
373 hg = findhg()
373 hg = findhg()
374 cmd = ['log', '-r', '.', '--template', '{tags}\n']
374 cmd = ['log', '-r', '.', '--template', '{tags}\n']
375 numerictags = [t for t in sysstr(hg.run(cmd)).split() if t[0:1].isdigit()]
375 numerictags = [t for t in sysstr(hg.run(cmd)).split() if t[0:1].isdigit()]
376 hgid = sysstr(hg.run(['id', '-i'])).strip()
376 hgid = sysstr(hg.run(['id', '-i'])).strip()
377 if not hgid:
377 if not hgid:
378 # Bail out if hg is having problems interacting with this repository,
378 # Bail out if hg is having problems interacting with this repository,
379 # rather than falling through and producing a bogus version number.
379 # rather than falling through and producing a bogus version number.
380 # Continuing with an invalid version number will break extensions
380 # Continuing with an invalid version number will break extensions
381 # that define minimumhgversion.
381 # that define minimumhgversion.
382 raise SystemExit('Unable to determine hg version from local repository')
382 raise SystemExit('Unable to determine hg version from local repository')
383 if numerictags: # tag(s) found
383 if numerictags: # tag(s) found
384 version = numerictags[-1]
384 version = numerictags[-1]
385 if hgid.endswith('+'): # propagate the dirty status to the tag
385 if hgid.endswith('+'): # propagate the dirty status to the tag
386 version += '+'
386 version += '+'
387 else: # no tag found
387 else: # no tag found
388 ltagcmd = ['parents', '--template', '{latesttag}']
388 ltagcmd = ['parents', '--template', '{latesttag}']
389 ltag = sysstr(hg.run(ltagcmd))
389 ltag = sysstr(hg.run(ltagcmd))
390 changessincecmd = ['log', '-T', 'x\n', '-r', "only(.,'%s')" % ltag]
390 changessincecmd = ['log', '-T', 'x\n', '-r', "only(.,'%s')" % ltag]
391 changessince = len(hg.run(changessincecmd).splitlines())
391 changessince = len(hg.run(changessincecmd).splitlines())
392 version = '%s+%s-%s' % (ltag, changessince, hgid)
392 version = '%s+%s-%s' % (ltag, changessince, hgid)
393 if version.endswith('+'):
393 if version.endswith('+'):
394 version += time.strftime('%Y%m%d')
394 version += time.strftime('%Y%m%d')
395 elif os.path.exists('.hg_archival.txt'):
395 elif os.path.exists('.hg_archival.txt'):
396 kw = dict(
396 kw = dict(
397 [[t.strip() for t in l.split(':', 1)] for l in open('.hg_archival.txt')]
397 [[t.strip() for t in l.split(':', 1)] for l in open('.hg_archival.txt')]
398 )
398 )
399 if 'tag' in kw:
399 if 'tag' in kw:
400 version = kw['tag']
400 version = kw['tag']
401 elif 'latesttag' in kw:
401 elif 'latesttag' in kw:
402 if 'changessincelatesttag' in kw:
402 if 'changessincelatesttag' in kw:
403 version = '%(latesttag)s+%(changessincelatesttag)s-%(node).12s' % kw
403 version = '%(latesttag)s+%(changessincelatesttag)s-%(node).12s' % kw
404 else:
404 else:
405 version = '%(latesttag)s+%(latesttagdistance)s-%(node).12s' % kw
405 version = '%(latesttag)s+%(latesttagdistance)s-%(node).12s' % kw
406 else:
406 else:
407 version = kw.get('node', '')[:12]
407 version = kw.get('node', '')[:12]
408
408
409 if version:
409 if version:
410 versionb = version
410 versionb = version
411 if not isinstance(versionb, bytes):
411 if not isinstance(versionb, bytes):
412 versionb = versionb.encode('ascii')
412 versionb = versionb.encode('ascii')
413
413
414 write_if_changed(
414 write_if_changed(
415 'mercurial/__version__.py',
415 'mercurial/__version__.py',
416 b''.join(
416 b''.join(
417 [
417 [
418 b'# this file is autogenerated by setup.py\n'
418 b'# this file is autogenerated by setup.py\n'
419 b'version = b"%s"\n' % versionb,
419 b'version = b"%s"\n' % versionb,
420 ]
420 ]
421 ),
421 ),
422 )
422 )
423
423
424 try:
424 try:
425 oldpolicy = os.environ.get('HGMODULEPOLICY', None)
425 oldpolicy = os.environ.get('HGMODULEPOLICY', None)
426 os.environ['HGMODULEPOLICY'] = 'py'
426 os.environ['HGMODULEPOLICY'] = 'py'
427 from mercurial import __version__
427 from mercurial import __version__
428
428
429 version = __version__.version
429 version = __version__.version
430 except ImportError:
430 except ImportError:
431 version = b'unknown'
431 version = b'unknown'
432 finally:
432 finally:
433 if oldpolicy is None:
433 if oldpolicy is None:
434 del os.environ['HGMODULEPOLICY']
434 del os.environ['HGMODULEPOLICY']
435 else:
435 else:
436 os.environ['HGMODULEPOLICY'] = oldpolicy
436 os.environ['HGMODULEPOLICY'] = oldpolicy
437
437
438
438
439 class hgbuild(build):
439 class hgbuild(build):
440 # Insert hgbuildmo first so that files in mercurial/locale/ are found
440 # Insert hgbuildmo first so that files in mercurial/locale/ are found
441 # when build_py is run next.
441 # when build_py is run next.
442 sub_commands = [('build_mo', None)] + build.sub_commands
442 sub_commands = [('build_mo', None)] + build.sub_commands
443
443
444
444
445 class hgbuildmo(build):
445 class hgbuildmo(build):
446
446
447 description = "build translations (.mo files)"
447 description = "build translations (.mo files)"
448
448
449 def run(self):
449 def run(self):
450 if not find_executable('msgfmt'):
450 if not find_executable('msgfmt'):
451 self.warn(
451 self.warn(
452 "could not find msgfmt executable, no translations "
452 "could not find msgfmt executable, no translations "
453 "will be built"
453 "will be built"
454 )
454 )
455 return
455 return
456
456
457 podir = 'i18n'
457 podir = 'i18n'
458 if not os.path.isdir(podir):
458 if not os.path.isdir(podir):
459 self.warn("could not find %s/ directory" % podir)
459 self.warn("could not find %s/ directory" % podir)
460 return
460 return
461
461
462 join = os.path.join
462 join = os.path.join
463 for po in os.listdir(podir):
463 for po in os.listdir(podir):
464 if not po.endswith('.po'):
464 if not po.endswith('.po'):
465 continue
465 continue
466 pofile = join(podir, po)
466 pofile = join(podir, po)
467 modir = join('locale', po[:-3], 'LC_MESSAGES')
467 modir = join('locale', po[:-3], 'LC_MESSAGES')
468 mofile = join(modir, 'hg.mo')
468 mofile = join(modir, 'hg.mo')
469 mobuildfile = join('mercurial', mofile)
469 mobuildfile = join('mercurial', mofile)
470 cmd = ['msgfmt', '-v', '-o', mobuildfile, pofile]
470 cmd = ['msgfmt', '-v', '-o', mobuildfile, pofile]
471 if sys.platform != 'sunos5':
471 if sys.platform != 'sunos5':
472 # msgfmt on Solaris does not know about -c
472 # msgfmt on Solaris does not know about -c
473 cmd.append('-c')
473 cmd.append('-c')
474 self.mkpath(join('mercurial', modir))
474 self.mkpath(join('mercurial', modir))
475 self.make_file([pofile], mobuildfile, spawn, (cmd,))
475 self.make_file([pofile], mobuildfile, spawn, (cmd,))
476
476
477
477
478 class hgdist(Distribution):
478 class hgdist(Distribution):
479 pure = False
479 pure = False
480 rust = hgrustext is not None
480 rust = hgrustext is not None
481 cffi = ispypy
481 cffi = ispypy
482
482
483 global_options = Distribution.global_options + [
483 global_options = Distribution.global_options + [
484 ('pure', None, "use pure (slow) Python code instead of C extensions"),
484 ('pure', None, "use pure (slow) Python code instead of C extensions"),
485 ('rust', None, "use Rust extensions additionally to C extensions"),
485 ('rust', None, "use Rust extensions additionally to C extensions"),
486 ]
486 ]
487
487
488 def has_ext_modules(self):
488 def has_ext_modules(self):
489 # self.ext_modules is emptied in hgbuildpy.finalize_options which is
489 # self.ext_modules is emptied in hgbuildpy.finalize_options which is
490 # too late for some cases
490 # too late for some cases
491 return not self.pure and Distribution.has_ext_modules(self)
491 return not self.pure and Distribution.has_ext_modules(self)
492
492
493
493
494 # This is ugly as a one-liner. So use a variable.
494 # This is ugly as a one-liner. So use a variable.
495 buildextnegops = dict(getattr(build_ext, 'negative_options', {}))
495 buildextnegops = dict(getattr(build_ext, 'negative_options', {}))
496 buildextnegops['no-zstd'] = 'zstd'
496 buildextnegops['no-zstd'] = 'zstd'
497 buildextnegops['no-rust'] = 'rust'
497 buildextnegops['no-rust'] = 'rust'
498
498
499
499
500 class hgbuildext(build_ext):
500 class hgbuildext(build_ext):
501 user_options = build_ext.user_options + [
501 user_options = build_ext.user_options + [
502 ('zstd', None, 'compile zstd bindings [default]'),
502 ('zstd', None, 'compile zstd bindings [default]'),
503 ('no-zstd', None, 'do not compile zstd bindings'),
503 ('no-zstd', None, 'do not compile zstd bindings'),
504 (
504 (
505 'rust',
505 'rust',
506 None,
506 None,
507 'compile Rust extensions if they are in use '
507 'compile Rust extensions if they are in use '
508 '(requires Cargo) [default]',
508 '(requires Cargo) [default]',
509 ),
509 ),
510 ('no-rust', None, 'do not compile Rust extensions'),
510 ('no-rust', None, 'do not compile Rust extensions'),
511 ]
511 ]
512
512
513 boolean_options = build_ext.boolean_options + ['zstd', 'rust']
513 boolean_options = build_ext.boolean_options + ['zstd', 'rust']
514 negative_opt = buildextnegops
514 negative_opt = buildextnegops
515
515
516 def initialize_options(self):
516 def initialize_options(self):
517 self.zstd = True
517 self.zstd = True
518 self.rust = True
518 self.rust = True
519
519
520 return build_ext.initialize_options(self)
520 return build_ext.initialize_options(self)
521
521
522 def finalize_options(self):
522 def finalize_options(self):
523 # Unless overridden by the end user, build extensions in parallel.
523 # Unless overridden by the end user, build extensions in parallel.
524 # Only influences behavior on Python 3.5+.
524 # Only influences behavior on Python 3.5+.
525 if getattr(self, 'parallel', None) is None:
525 if getattr(self, 'parallel', None) is None:
526 self.parallel = True
526 self.parallel = True
527
527
528 return build_ext.finalize_options(self)
528 return build_ext.finalize_options(self)
529
529
530 def build_extensions(self):
530 def build_extensions(self):
531 ruststandalones = [
531 ruststandalones = [
532 e for e in self.extensions if isinstance(e, RustStandaloneExtension)
532 e for e in self.extensions if isinstance(e, RustStandaloneExtension)
533 ]
533 ]
534 self.extensions = [
534 self.extensions = [
535 e for e in self.extensions if e not in ruststandalones
535 e for e in self.extensions if e not in ruststandalones
536 ]
536 ]
537 # Filter out zstd if disabled via argument.
537 # Filter out zstd if disabled via argument.
538 if not self.zstd:
538 if not self.zstd:
539 self.extensions = [
539 self.extensions = [
540 e for e in self.extensions if e.name != 'mercurial.zstd'
540 e for e in self.extensions if e.name != 'mercurial.zstd'
541 ]
541 ]
542
542
543 # Build Rust standalon extensions if it'll be used
543 # Build Rust standalon extensions if it'll be used
544 # and its build is not explictely disabled (for external build
544 # and its build is not explictely disabled (for external build
545 # as Linux distributions would do)
545 # as Linux distributions would do)
546 if self.distribution.rust and self.rust and hgrustext != 'direct-ffi':
546 if self.distribution.rust and self.rust and hgrustext != 'direct-ffi':
547 for rustext in ruststandalones:
547 for rustext in ruststandalones:
548 rustext.build('' if self.inplace else self.build_lib)
548 rustext.build('' if self.inplace else self.build_lib)
549
549
550 return build_ext.build_extensions(self)
550 return build_ext.build_extensions(self)
551
551
552 def build_extension(self, ext):
552 def build_extension(self, ext):
553 if (
553 if (
554 self.distribution.rust
554 self.distribution.rust
555 and self.rust
555 and self.rust
556 and isinstance(ext, RustExtension)
556 and isinstance(ext, RustExtension)
557 ):
557 ):
558 ext.rustbuild()
558 ext.rustbuild()
559 try:
559 try:
560 build_ext.build_extension(self, ext)
560 build_ext.build_extension(self, ext)
561 except CCompilerError:
561 except CCompilerError:
562 if not getattr(ext, 'optional', False):
562 if not getattr(ext, 'optional', False):
563 raise
563 raise
564 log.warn(
564 log.warn(
565 "Failed to build optional extension '%s' (skipping)", ext.name
565 "Failed to build optional extension '%s' (skipping)", ext.name
566 )
566 )
567
567
568
568
569 class hgbuildscripts(build_scripts):
569 class hgbuildscripts(build_scripts):
570 def run(self):
570 def run(self):
571 if os.name != 'nt' or self.distribution.pure:
571 if os.name != 'nt' or self.distribution.pure:
572 return build_scripts.run(self)
572 return build_scripts.run(self)
573
573
574 exebuilt = False
574 exebuilt = False
575 try:
575 try:
576 self.run_command('build_hgexe')
576 self.run_command('build_hgexe')
577 exebuilt = True
577 exebuilt = True
578 except (DistutilsError, CCompilerError):
578 except (DistutilsError, CCompilerError):
579 log.warn('failed to build optional hg.exe')
579 log.warn('failed to build optional hg.exe')
580
580
581 if exebuilt:
581 if exebuilt:
582 # Copying hg.exe to the scripts build directory ensures it is
582 # Copying hg.exe to the scripts build directory ensures it is
583 # installed by the install_scripts command.
583 # installed by the install_scripts command.
584 hgexecommand = self.get_finalized_command('build_hgexe')
584 hgexecommand = self.get_finalized_command('build_hgexe')
585 dest = os.path.join(self.build_dir, 'hg.exe')
585 dest = os.path.join(self.build_dir, 'hg.exe')
586 self.mkpath(self.build_dir)
586 self.mkpath(self.build_dir)
587 self.copy_file(hgexecommand.hgexepath, dest)
587 self.copy_file(hgexecommand.hgexepath, dest)
588
588
589 # Remove hg.bat because it is redundant with hg.exe.
589 # Remove hg.bat because it is redundant with hg.exe.
590 self.scripts.remove('contrib/win32/hg.bat')
590 self.scripts.remove('contrib/win32/hg.bat')
591
591
592 return build_scripts.run(self)
592 return build_scripts.run(self)
593
593
594
594
595 class hgbuildpy(build_py):
595 class hgbuildpy(build_py):
596 def finalize_options(self):
596 def finalize_options(self):
597 build_py.finalize_options(self)
597 build_py.finalize_options(self)
598
598
599 if self.distribution.pure:
599 if self.distribution.pure:
600 self.distribution.ext_modules = []
600 self.distribution.ext_modules = []
601 elif self.distribution.cffi:
601 elif self.distribution.cffi:
602 from mercurial.cffi import (
602 from mercurial.cffi import (
603 bdiffbuild,
603 bdiffbuild,
604 mpatchbuild,
604 mpatchbuild,
605 )
605 )
606
606
607 exts = [
607 exts = [
608 mpatchbuild.ffi.distutils_extension(),
608 mpatchbuild.ffi.distutils_extension(),
609 bdiffbuild.ffi.distutils_extension(),
609 bdiffbuild.ffi.distutils_extension(),
610 ]
610 ]
611 # cffi modules go here
611 # cffi modules go here
612 if sys.platform == 'darwin':
612 if sys.platform == 'darwin':
613 from mercurial.cffi import osutilbuild
613 from mercurial.cffi import osutilbuild
614
614
615 exts.append(osutilbuild.ffi.distutils_extension())
615 exts.append(osutilbuild.ffi.distutils_extension())
616 self.distribution.ext_modules = exts
616 self.distribution.ext_modules = exts
617 else:
617 else:
618 h = os.path.join(get_python_inc(), 'Python.h')
618 h = os.path.join(get_python_inc(), 'Python.h')
619 if not os.path.exists(h):
619 if not os.path.exists(h):
620 raise SystemExit(
620 raise SystemExit(
621 'Python headers are required to build '
621 'Python headers are required to build '
622 'Mercurial but weren\'t found in %s' % h
622 'Mercurial but weren\'t found in %s' % h
623 )
623 )
624
624
625 def run(self):
625 def run(self):
626 basepath = os.path.join(self.build_lib, 'mercurial')
626 basepath = os.path.join(self.build_lib, 'mercurial')
627 self.mkpath(basepath)
627 self.mkpath(basepath)
628
628
629 rust = self.distribution.rust
629 rust = self.distribution.rust
630 if self.distribution.pure:
630 if self.distribution.pure:
631 modulepolicy = 'py'
631 modulepolicy = 'py'
632 elif self.build_lib == '.':
632 elif self.build_lib == '.':
633 # in-place build should run without rebuilding and Rust extensions
633 # in-place build should run without rebuilding and Rust extensions
634 modulepolicy = 'rust+c-allow' if rust else 'allow'
634 modulepolicy = 'rust+c-allow' if rust else 'allow'
635 else:
635 else:
636 modulepolicy = 'rust+c' if rust else 'c'
636 modulepolicy = 'rust+c' if rust else 'c'
637
637
638 content = b''.join(
638 content = b''.join(
639 [
639 [
640 b'# this file is autogenerated by setup.py\n',
640 b'# this file is autogenerated by setup.py\n',
641 b'modulepolicy = b"%s"\n' % modulepolicy.encode('ascii'),
641 b'modulepolicy = b"%s"\n' % modulepolicy.encode('ascii'),
642 ]
642 ]
643 )
643 )
644 write_if_changed(os.path.join(basepath, '__modulepolicy__.py'), content)
644 write_if_changed(os.path.join(basepath, '__modulepolicy__.py'), content)
645
645
646 build_py.run(self)
646 build_py.run(self)
647
647
648
648
649 class buildhgextindex(Command):
649 class buildhgextindex(Command):
650 description = 'generate prebuilt index of hgext (for frozen package)'
650 description = 'generate prebuilt index of hgext (for frozen package)'
651 user_options = []
651 user_options = []
652 _indexfilename = 'hgext/__index__.py'
652 _indexfilename = 'hgext/__index__.py'
653
653
654 def initialize_options(self):
654 def initialize_options(self):
655 pass
655 pass
656
656
657 def finalize_options(self):
657 def finalize_options(self):
658 pass
658 pass
659
659
660 def run(self):
660 def run(self):
661 if os.path.exists(self._indexfilename):
661 if os.path.exists(self._indexfilename):
662 with open(self._indexfilename, 'w') as f:
662 with open(self._indexfilename, 'w') as f:
663 f.write('# empty\n')
663 f.write('# empty\n')
664
664
665 # here no extension enabled, disabled() lists up everything
665 # here no extension enabled, disabled() lists up everything
666 code = (
666 code = (
667 'import pprint; from mercurial import extensions; '
667 'import pprint; from mercurial import extensions; '
668 'ext = extensions.disabled();'
668 'ext = extensions.disabled();'
669 'ext.pop("__index__", None);'
669 'ext.pop("__index__", None);'
670 'pprint.pprint(ext)'
670 'pprint.pprint(ext)'
671 )
671 )
672 returncode, out, err = runcmd(
672 returncode, out, err = runcmd(
673 [sys.executable, '-c', code], localhgenv()
673 [sys.executable, '-c', code], localhgenv()
674 )
674 )
675 if err or returncode != 0:
675 if err or returncode != 0:
676 raise DistutilsExecError(err)
676 raise DistutilsExecError(err)
677
677
678 with open(self._indexfilename, 'wb') as f:
678 with open(self._indexfilename, 'wb') as f:
679 f.write(b'# this file is autogenerated by setup.py\n')
679 f.write(b'# this file is autogenerated by setup.py\n')
680 f.write(b'docs = ')
680 f.write(b'docs = ')
681 f.write(out)
681 f.write(out)
682
682
683
683
684 class buildhgexe(build_ext):
684 class buildhgexe(build_ext):
685 description = 'compile hg.exe from mercurial/exewrapper.c'
685 description = 'compile hg.exe from mercurial/exewrapper.c'
686 user_options = build_ext.user_options + [
686 user_options = build_ext.user_options + [
687 (
687 (
688 'long-paths-support',
688 'long-paths-support',
689 None,
689 None,
690 'enable support for long paths on '
690 'enable support for long paths on '
691 'Windows (off by default and '
691 'Windows (off by default and '
692 'experimental)',
692 'experimental)',
693 ),
693 ),
694 ]
694 ]
695
695
696 LONG_PATHS_MANIFEST = """
696 LONG_PATHS_MANIFEST = """
697 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
697 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
698 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
698 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
699 <application>
699 <application>
700 <windowsSettings
700 <windowsSettings
701 xmlns:ws2="http://schemas.microsoft.com/SMI/2016/WindowsSettings">
701 xmlns:ws2="http://schemas.microsoft.com/SMI/2016/WindowsSettings">
702 <ws2:longPathAware>true</ws2:longPathAware>
702 <ws2:longPathAware>true</ws2:longPathAware>
703 </windowsSettings>
703 </windowsSettings>
704 </application>
704 </application>
705 </assembly>"""
705 </assembly>"""
706
706
707 def initialize_options(self):
707 def initialize_options(self):
708 build_ext.initialize_options(self)
708 build_ext.initialize_options(self)
709 self.long_paths_support = False
709 self.long_paths_support = False
710
710
711 def build_extensions(self):
711 def build_extensions(self):
712 if os.name != 'nt':
712 if os.name != 'nt':
713 return
713 return
714 if isinstance(self.compiler, HackedMingw32CCompiler):
714 if isinstance(self.compiler, HackedMingw32CCompiler):
715 self.compiler.compiler_so = self.compiler.compiler # no -mdll
715 self.compiler.compiler_so = self.compiler.compiler # no -mdll
716 self.compiler.dll_libraries = [] # no -lmsrvc90
716 self.compiler.dll_libraries = [] # no -lmsrvc90
717
717
718 pythonlib = None
718 pythonlib = None
719
719
720 if getattr(sys, 'dllhandle', None):
720 if getattr(sys, 'dllhandle', None):
721 # Different Python installs can have different Python library
721 # Different Python installs can have different Python library
722 # names. e.g. the official CPython distribution uses pythonXY.dll
722 # names. e.g. the official CPython distribution uses pythonXY.dll
723 # and MinGW uses libpythonX.Y.dll.
723 # and MinGW uses libpythonX.Y.dll.
724 _kernel32 = ctypes.windll.kernel32
724 _kernel32 = ctypes.windll.kernel32
725 _kernel32.GetModuleFileNameA.argtypes = [
725 _kernel32.GetModuleFileNameA.argtypes = [
726 ctypes.c_void_p,
726 ctypes.c_void_p,
727 ctypes.c_void_p,
727 ctypes.c_void_p,
728 ctypes.c_ulong,
728 ctypes.c_ulong,
729 ]
729 ]
730 _kernel32.GetModuleFileNameA.restype = ctypes.c_ulong
730 _kernel32.GetModuleFileNameA.restype = ctypes.c_ulong
731 size = 1000
731 size = 1000
732 buf = ctypes.create_string_buffer(size + 1)
732 buf = ctypes.create_string_buffer(size + 1)
733 filelen = _kernel32.GetModuleFileNameA(
733 filelen = _kernel32.GetModuleFileNameA(
734 sys.dllhandle, ctypes.byref(buf), size
734 sys.dllhandle, ctypes.byref(buf), size
735 )
735 )
736
736
737 if filelen > 0 and filelen != size:
737 if filelen > 0 and filelen != size:
738 dllbasename = os.path.basename(buf.value)
738 dllbasename = os.path.basename(buf.value)
739 if not dllbasename.lower().endswith(b'.dll'):
739 if not dllbasename.lower().endswith(b'.dll'):
740 raise SystemExit(
740 raise SystemExit(
741 'Python DLL does not end with .dll: %s' % dllbasename
741 'Python DLL does not end with .dll: %s' % dllbasename
742 )
742 )
743 pythonlib = dllbasename[:-4]
743 pythonlib = dllbasename[:-4]
744
744
745 if not pythonlib:
745 if not pythonlib:
746 log.warn(
746 log.warn(
747 'could not determine Python DLL filename; assuming pythonXY'
747 'could not determine Python DLL filename; assuming pythonXY'
748 )
748 )
749
749
750 hv = sys.hexversion
750 hv = sys.hexversion
751 pythonlib = b'python%d%d' % (hv >> 24, (hv >> 16) & 0xFF)
751 pythonlib = b'python%d%d' % (hv >> 24, (hv >> 16) & 0xFF)
752
752
753 log.info('using %s as Python library name' % pythonlib)
753 log.info('using %s as Python library name' % pythonlib)
754 with open('mercurial/hgpythonlib.h', 'wb') as f:
754 with open('mercurial/hgpythonlib.h', 'wb') as f:
755 f.write(b'/* this file is autogenerated by setup.py */\n')
755 f.write(b'/* this file is autogenerated by setup.py */\n')
756 f.write(b'#define HGPYTHONLIB "%s"\n' % pythonlib)
756 f.write(b'#define HGPYTHONLIB "%s"\n' % pythonlib)
757
757
758 macros = None
758 macros = None
759 if sys.version_info[0] >= 3:
759 if sys.version_info[0] >= 3:
760 macros = [('_UNICODE', None), ('UNICODE', None)]
760 macros = [('_UNICODE', None), ('UNICODE', None)]
761
761
762 objects = self.compiler.compile(
762 objects = self.compiler.compile(
763 ['mercurial/exewrapper.c'],
763 ['mercurial/exewrapper.c'],
764 output_dir=self.build_temp,
764 output_dir=self.build_temp,
765 macros=macros,
765 macros=macros,
766 )
766 )
767 dir = os.path.dirname(self.get_ext_fullpath('dummy'))
767 dir = os.path.dirname(self.get_ext_fullpath('dummy'))
768 self.hgtarget = os.path.join(dir, 'hg')
768 self.hgtarget = os.path.join(dir, 'hg')
769 self.compiler.link_executable(
769 self.compiler.link_executable(
770 objects, self.hgtarget, libraries=[], output_dir=self.build_temp
770 objects, self.hgtarget, libraries=[], output_dir=self.build_temp
771 )
771 )
772 if self.long_paths_support:
772 if self.long_paths_support:
773 self.addlongpathsmanifest()
773 self.addlongpathsmanifest()
774
774
775 def addlongpathsmanifest(self):
775 def addlongpathsmanifest(self):
776 r"""Add manifest pieces so that hg.exe understands long paths
776 r"""Add manifest pieces so that hg.exe understands long paths
777
777
778 This is an EXPERIMENTAL feature, use with care.
778 This is an EXPERIMENTAL feature, use with care.
779 To enable long paths support, one needs to do two things:
779 To enable long paths support, one needs to do two things:
780 - build Mercurial with --long-paths-support option
780 - build Mercurial with --long-paths-support option
781 - change HKLM\SYSTEM\CurrentControlSet\Control\FileSystem\
781 - change HKLM\SYSTEM\CurrentControlSet\Control\FileSystem\
782 LongPathsEnabled to have value 1.
782 LongPathsEnabled to have value 1.
783
783
784 Please ignore 'warning 81010002: Unrecognized Element "longPathAware"';
784 Please ignore 'warning 81010002: Unrecognized Element "longPathAware"';
785 it happens because Mercurial uses mt.exe circa 2008, which is not
785 it happens because Mercurial uses mt.exe circa 2008, which is not
786 yet aware of long paths support in the manifest (I think so at least).
786 yet aware of long paths support in the manifest (I think so at least).
787 This does not stop mt.exe from embedding/merging the XML properly.
787 This does not stop mt.exe from embedding/merging the XML properly.
788
788
789 Why resource #1 should be used for .exe manifests? I don't know and
789 Why resource #1 should be used for .exe manifests? I don't know and
790 wasn't able to find an explanation for mortals. But it seems to work.
790 wasn't able to find an explanation for mortals. But it seems to work.
791 """
791 """
792 exefname = self.compiler.executable_filename(self.hgtarget)
792 exefname = self.compiler.executable_filename(self.hgtarget)
793 fdauto, manfname = tempfile.mkstemp(suffix='.hg.exe.manifest')
793 fdauto, manfname = tempfile.mkstemp(suffix='.hg.exe.manifest')
794 os.close(fdauto)
794 os.close(fdauto)
795 with open(manfname, 'w') as f:
795 with open(manfname, 'w') as f:
796 f.write(self.LONG_PATHS_MANIFEST)
796 f.write(self.LONG_PATHS_MANIFEST)
797 log.info("long paths manifest is written to '%s'" % manfname)
797 log.info("long paths manifest is written to '%s'" % manfname)
798 inputresource = '-inputresource:%s;#1' % exefname
798 inputresource = '-inputresource:%s;#1' % exefname
799 outputresource = '-outputresource:%s;#1' % exefname
799 outputresource = '-outputresource:%s;#1' % exefname
800 log.info("running mt.exe to update hg.exe's manifest in-place")
800 log.info("running mt.exe to update hg.exe's manifest in-place")
801 # supplying both -manifest and -inputresource to mt.exe makes
801 # supplying both -manifest and -inputresource to mt.exe makes
802 # it merge the embedded and supplied manifests in the -outputresource
802 # it merge the embedded and supplied manifests in the -outputresource
803 self.spawn(
803 self.spawn(
804 [
804 [
805 'mt.exe',
805 'mt.exe',
806 '-nologo',
806 '-nologo',
807 '-manifest',
807 '-manifest',
808 manfname,
808 manfname,
809 inputresource,
809 inputresource,
810 outputresource,
810 outputresource,
811 ]
811 ]
812 )
812 )
813 log.info("done updating hg.exe's manifest")
813 log.info("done updating hg.exe's manifest")
814 os.remove(manfname)
814 os.remove(manfname)
815
815
816 @property
816 @property
817 def hgexepath(self):
817 def hgexepath(self):
818 dir = os.path.dirname(self.get_ext_fullpath('dummy'))
818 dir = os.path.dirname(self.get_ext_fullpath('dummy'))
819 return os.path.join(self.build_temp, dir, 'hg.exe')
819 return os.path.join(self.build_temp, dir, 'hg.exe')
820
820
821
821
822 class hgbuilddoc(Command):
822 class hgbuilddoc(Command):
823 description = 'build documentation'
823 description = 'build documentation'
824 user_options = [
824 user_options = [
825 ('man', None, 'generate man pages'),
825 ('man', None, 'generate man pages'),
826 ('html', None, 'generate html pages'),
826 ('html', None, 'generate html pages'),
827 ]
827 ]
828
828
829 def initialize_options(self):
829 def initialize_options(self):
830 self.man = None
830 self.man = None
831 self.html = None
831 self.html = None
832
832
833 def finalize_options(self):
833 def finalize_options(self):
834 # If --man or --html are set, only generate what we're told to.
834 # If --man or --html are set, only generate what we're told to.
835 # Otherwise generate everything.
835 # Otherwise generate everything.
836 have_subset = self.man is not None or self.html is not None
836 have_subset = self.man is not None or self.html is not None
837
837
838 if have_subset:
838 if have_subset:
839 self.man = True if self.man else False
839 self.man = True if self.man else False
840 self.html = True if self.html else False
840 self.html = True if self.html else False
841 else:
841 else:
842 self.man = True
842 self.man = True
843 self.html = True
843 self.html = True
844
844
845 def run(self):
845 def run(self):
846 def normalizecrlf(p):
846 def normalizecrlf(p):
847 with open(p, 'rb') as fh:
847 with open(p, 'rb') as fh:
848 orig = fh.read()
848 orig = fh.read()
849
849
850 if b'\r\n' not in orig:
850 if b'\r\n' not in orig:
851 return
851 return
852
852
853 log.info('normalizing %s to LF line endings' % p)
853 log.info('normalizing %s to LF line endings' % p)
854 with open(p, 'wb') as fh:
854 with open(p, 'wb') as fh:
855 fh.write(orig.replace(b'\r\n', b'\n'))
855 fh.write(orig.replace(b'\r\n', b'\n'))
856
856
857 def gentxt(root):
857 def gentxt(root):
858 txt = 'doc/%s.txt' % root
858 txt = 'doc/%s.txt' % root
859 log.info('generating %s' % txt)
859 log.info('generating %s' % txt)
860 res, out, err = runcmd(
860 res, out, err = runcmd(
861 [sys.executable, 'gendoc.py', root], os.environ, cwd='doc'
861 [sys.executable, 'gendoc.py', root], os.environ, cwd='doc'
862 )
862 )
863 if res:
863 if res:
864 raise SystemExit(
864 raise SystemExit(
865 'error running gendoc.py: %s' % '\n'.join([out, err])
865 'error running gendoc.py: %s' % '\n'.join([out, err])
866 )
866 )
867
867
868 with open(txt, 'wb') as fh:
868 with open(txt, 'wb') as fh:
869 fh.write(out)
869 fh.write(out)
870
870
871 def gengendoc(root):
871 def gengendoc(root):
872 gendoc = 'doc/%s.gendoc.txt' % root
872 gendoc = 'doc/%s.gendoc.txt' % root
873
873
874 log.info('generating %s' % gendoc)
874 log.info('generating %s' % gendoc)
875 res, out, err = runcmd(
875 res, out, err = runcmd(
876 [sys.executable, 'gendoc.py', '%s.gendoc' % root],
876 [sys.executable, 'gendoc.py', '%s.gendoc' % root],
877 os.environ,
877 os.environ,
878 cwd='doc',
878 cwd='doc',
879 )
879 )
880 if res:
880 if res:
881 raise SystemExit(
881 raise SystemExit(
882 'error running gendoc: %s' % '\n'.join([out, err])
882 'error running gendoc: %s' % '\n'.join([out, err])
883 )
883 )
884
884
885 with open(gendoc, 'wb') as fh:
885 with open(gendoc, 'wb') as fh:
886 fh.write(out)
886 fh.write(out)
887
887
888 def genman(root):
888 def genman(root):
889 log.info('generating doc/%s' % root)
889 log.info('generating doc/%s' % root)
890 res, out, err = runcmd(
890 res, out, err = runcmd(
891 [
891 [
892 sys.executable,
892 sys.executable,
893 'runrst',
893 'runrst',
894 'hgmanpage',
894 'hgmanpage',
895 '--halt',
895 '--halt',
896 'warning',
896 'warning',
897 '--strip-elements-with-class',
897 '--strip-elements-with-class',
898 'htmlonly',
898 'htmlonly',
899 '%s.txt' % root,
899 '%s.txt' % root,
900 root,
900 root,
901 ],
901 ],
902 os.environ,
902 os.environ,
903 cwd='doc',
903 cwd='doc',
904 )
904 )
905 if res:
905 if res:
906 raise SystemExit(
906 raise SystemExit(
907 'error running runrst: %s' % '\n'.join([out, err])
907 'error running runrst: %s' % '\n'.join([out, err])
908 )
908 )
909
909
910 normalizecrlf('doc/%s' % root)
910 normalizecrlf('doc/%s' % root)
911
911
912 def genhtml(root):
912 def genhtml(root):
913 log.info('generating doc/%s.html' % root)
913 log.info('generating doc/%s.html' % root)
914 res, out, err = runcmd(
914 res, out, err = runcmd(
915 [
915 [
916 sys.executable,
916 sys.executable,
917 'runrst',
917 'runrst',
918 'html',
918 'html',
919 '--halt',
919 '--halt',
920 'warning',
920 'warning',
921 '--link-stylesheet',
921 '--link-stylesheet',
922 '--stylesheet-path',
922 '--stylesheet-path',
923 'style.css',
923 'style.css',
924 '%s.txt' % root,
924 '%s.txt' % root,
925 '%s.html' % root,
925 '%s.html' % root,
926 ],
926 ],
927 os.environ,
927 os.environ,
928 cwd='doc',
928 cwd='doc',
929 )
929 )
930 if res:
930 if res:
931 raise SystemExit(
931 raise SystemExit(
932 'error running runrst: %s' % '\n'.join([out, err])
932 'error running runrst: %s' % '\n'.join([out, err])
933 )
933 )
934
934
935 normalizecrlf('doc/%s.html' % root)
935 normalizecrlf('doc/%s.html' % root)
936
936
937 # This logic is duplicated in doc/Makefile.
937 # This logic is duplicated in doc/Makefile.
938 sources = set(
938 sources = set(
939 f
939 f
940 for f in os.listdir('mercurial/helptext')
940 for f in os.listdir('mercurial/helptext')
941 if re.search(r'[0-9]\.txt$', f)
941 if re.search(r'[0-9]\.txt$', f)
942 )
942 )
943
943
944 # common.txt is a one-off.
944 # common.txt is a one-off.
945 gentxt('common')
945 gentxt('common')
946
946
947 for source in sorted(sources):
947 for source in sorted(sources):
948 assert source[-4:] == '.txt'
948 assert source[-4:] == '.txt'
949 root = source[:-4]
949 root = source[:-4]
950
950
951 gentxt(root)
951 gentxt(root)
952 gengendoc(root)
952 gengendoc(root)
953
953
954 if self.man:
954 if self.man:
955 genman(root)
955 genman(root)
956 if self.html:
956 if self.html:
957 genhtml(root)
957 genhtml(root)
958
958
959
959
960 class hginstall(install):
960 class hginstall(install):
961
961
962 user_options = install.user_options + [
962 user_options = install.user_options + [
963 (
963 (
964 'old-and-unmanageable',
964 'old-and-unmanageable',
965 None,
965 None,
966 'noop, present for eggless setuptools compat',
966 'noop, present for eggless setuptools compat',
967 ),
967 ),
968 (
968 (
969 'single-version-externally-managed',
969 'single-version-externally-managed',
970 None,
970 None,
971 'noop, present for eggless setuptools compat',
971 'noop, present for eggless setuptools compat',
972 ),
972 ),
973 ]
973 ]
974
974
975 # Also helps setuptools not be sad while we refuse to create eggs.
975 # Also helps setuptools not be sad while we refuse to create eggs.
976 single_version_externally_managed = True
976 single_version_externally_managed = True
977
977
978 def get_sub_commands(self):
978 def get_sub_commands(self):
979 # Screen out egg related commands to prevent egg generation. But allow
979 # Screen out egg related commands to prevent egg generation. But allow
980 # mercurial.egg-info generation, since that is part of modern
980 # mercurial.egg-info generation, since that is part of modern
981 # packaging.
981 # packaging.
982 excl = set(['bdist_egg'])
982 excl = set(['bdist_egg'])
983 return filter(lambda x: x not in excl, install.get_sub_commands(self))
983 return filter(lambda x: x not in excl, install.get_sub_commands(self))
984
984
985
985
986 class hginstalllib(install_lib):
986 class hginstalllib(install_lib):
987 '''
987 '''
988 This is a specialization of install_lib that replaces the copy_file used
988 This is a specialization of install_lib that replaces the copy_file used
989 there so that it supports setting the mode of files after copying them,
989 there so that it supports setting the mode of files after copying them,
990 instead of just preserving the mode that the files originally had. If your
990 instead of just preserving the mode that the files originally had. If your
991 system has a umask of something like 027, preserving the permissions when
991 system has a umask of something like 027, preserving the permissions when
992 copying will lead to a broken install.
992 copying will lead to a broken install.
993
993
994 Note that just passing keep_permissions=False to copy_file would be
994 Note that just passing keep_permissions=False to copy_file would be
995 insufficient, as it might still be applying a umask.
995 insufficient, as it might still be applying a umask.
996 '''
996 '''
997
997
998 def run(self):
998 def run(self):
999 realcopyfile = file_util.copy_file
999 realcopyfile = file_util.copy_file
1000
1000
1001 def copyfileandsetmode(*args, **kwargs):
1001 def copyfileandsetmode(*args, **kwargs):
1002 src, dst = args[0], args[1]
1002 src, dst = args[0], args[1]
1003 dst, copied = realcopyfile(*args, **kwargs)
1003 dst, copied = realcopyfile(*args, **kwargs)
1004 if copied:
1004 if copied:
1005 st = os.stat(src)
1005 st = os.stat(src)
1006 # Persist executable bit (apply it to group and other if user
1006 # Persist executable bit (apply it to group and other if user
1007 # has it)
1007 # has it)
1008 if st[stat.ST_MODE] & stat.S_IXUSR:
1008 if st[stat.ST_MODE] & stat.S_IXUSR:
1009 setmode = int('0755', 8)
1009 setmode = int('0755', 8)
1010 else:
1010 else:
1011 setmode = int('0644', 8)
1011 setmode = int('0644', 8)
1012 m = stat.S_IMODE(st[stat.ST_MODE])
1012 m = stat.S_IMODE(st[stat.ST_MODE])
1013 m = (m & ~int('0777', 8)) | setmode
1013 m = (m & ~int('0777', 8)) | setmode
1014 os.chmod(dst, m)
1014 os.chmod(dst, m)
1015
1015
1016 file_util.copy_file = copyfileandsetmode
1016 file_util.copy_file = copyfileandsetmode
1017 try:
1017 try:
1018 install_lib.run(self)
1018 install_lib.run(self)
1019 finally:
1019 finally:
1020 file_util.copy_file = realcopyfile
1020 file_util.copy_file = realcopyfile
1021
1021
1022
1022
1023 class hginstallscripts(install_scripts):
1023 class hginstallscripts(install_scripts):
1024 '''
1024 '''
1025 This is a specialization of install_scripts that replaces the @LIBDIR@ with
1025 This is a specialization of install_scripts that replaces the @LIBDIR@ with
1026 the configured directory for modules. If possible, the path is made relative
1026 the configured directory for modules. If possible, the path is made relative
1027 to the directory for scripts.
1027 to the directory for scripts.
1028 '''
1028 '''
1029
1029
1030 def initialize_options(self):
1030 def initialize_options(self):
1031 install_scripts.initialize_options(self)
1031 install_scripts.initialize_options(self)
1032
1032
1033 self.install_lib = None
1033 self.install_lib = None
1034
1034
1035 def finalize_options(self):
1035 def finalize_options(self):
1036 install_scripts.finalize_options(self)
1036 install_scripts.finalize_options(self)
1037 self.set_undefined_options('install', ('install_lib', 'install_lib'))
1037 self.set_undefined_options('install', ('install_lib', 'install_lib'))
1038
1038
1039 def run(self):
1039 def run(self):
1040 install_scripts.run(self)
1040 install_scripts.run(self)
1041
1041
1042 # It only makes sense to replace @LIBDIR@ with the install path if
1042 # It only makes sense to replace @LIBDIR@ with the install path if
1043 # the install path is known. For wheels, the logic below calculates
1043 # the install path is known. For wheels, the logic below calculates
1044 # the libdir to be "../..". This is because the internal layout of a
1044 # the libdir to be "../..". This is because the internal layout of a
1045 # wheel archive looks like:
1045 # wheel archive looks like:
1046 #
1046 #
1047 # mercurial-3.6.1.data/scripts/hg
1047 # mercurial-3.6.1.data/scripts/hg
1048 # mercurial/__init__.py
1048 # mercurial/__init__.py
1049 #
1049 #
1050 # When installing wheels, the subdirectories of the "<pkg>.data"
1050 # When installing wheels, the subdirectories of the "<pkg>.data"
1051 # directory are translated to system local paths and files therein
1051 # directory are translated to system local paths and files therein
1052 # are copied in place. The mercurial/* files are installed into the
1052 # are copied in place. The mercurial/* files are installed into the
1053 # site-packages directory. However, the site-packages directory
1053 # site-packages directory. However, the site-packages directory
1054 # isn't known until wheel install time. This means we have no clue
1054 # isn't known until wheel install time. This means we have no clue
1055 # at wheel generation time what the installed site-packages directory
1055 # at wheel generation time what the installed site-packages directory
1056 # will be. And, wheels don't appear to provide the ability to register
1056 # will be. And, wheels don't appear to provide the ability to register
1057 # custom code to run during wheel installation. This all means that
1057 # custom code to run during wheel installation. This all means that
1058 # we can't reliably set the libdir in wheels: the default behavior
1058 # we can't reliably set the libdir in wheels: the default behavior
1059 # of looking in sys.path must do.
1059 # of looking in sys.path must do.
1060
1060
1061 if (
1061 if (
1062 os.path.splitdrive(self.install_dir)[0]
1062 os.path.splitdrive(self.install_dir)[0]
1063 != os.path.splitdrive(self.install_lib)[0]
1063 != os.path.splitdrive(self.install_lib)[0]
1064 ):
1064 ):
1065 # can't make relative paths from one drive to another, so use an
1065 # can't make relative paths from one drive to another, so use an
1066 # absolute path instead
1066 # absolute path instead
1067 libdir = self.install_lib
1067 libdir = self.install_lib
1068 else:
1068 else:
1069 libdir = os.path.relpath(self.install_lib, self.install_dir)
1069 libdir = os.path.relpath(self.install_lib, self.install_dir)
1070
1070
1071 for outfile in self.outfiles:
1071 for outfile in self.outfiles:
1072 with open(outfile, 'rb') as fp:
1072 with open(outfile, 'rb') as fp:
1073 data = fp.read()
1073 data = fp.read()
1074
1074
1075 # skip binary files
1075 # skip binary files
1076 if b'\0' in data:
1076 if b'\0' in data:
1077 continue
1077 continue
1078
1078
1079 # During local installs, the shebang will be rewritten to the final
1079 # During local installs, the shebang will be rewritten to the final
1080 # install path. During wheel packaging, the shebang has a special
1080 # install path. During wheel packaging, the shebang has a special
1081 # value.
1081 # value.
1082 if data.startswith(b'#!python'):
1082 if data.startswith(b'#!python'):
1083 log.info(
1083 log.info(
1084 'not rewriting @LIBDIR@ in %s because install path '
1084 'not rewriting @LIBDIR@ in %s because install path '
1085 'not known' % outfile
1085 'not known' % outfile
1086 )
1086 )
1087 continue
1087 continue
1088
1088
1089 data = data.replace(b'@LIBDIR@', libdir.encode(libdir_escape))
1089 data = data.replace(b'@LIBDIR@', libdir.encode(libdir_escape))
1090 with open(outfile, 'wb') as fp:
1090 with open(outfile, 'wb') as fp:
1091 fp.write(data)
1091 fp.write(data)
1092
1092
1093
1093
1094 # virtualenv installs custom distutils/__init__.py and
1094 # virtualenv installs custom distutils/__init__.py and
1095 # distutils/distutils.cfg files which essentially proxy back to the
1095 # distutils/distutils.cfg files which essentially proxy back to the
1096 # "real" distutils in the main Python install. The presence of this
1096 # "real" distutils in the main Python install. The presence of this
1097 # directory causes py2exe to pick up the "hacked" distutils package
1097 # directory causes py2exe to pick up the "hacked" distutils package
1098 # from the virtualenv and "import distutils" will fail from the py2exe
1098 # from the virtualenv and "import distutils" will fail from the py2exe
1099 # build because the "real" distutils files can't be located.
1099 # build because the "real" distutils files can't be located.
1100 #
1100 #
1101 # We work around this by monkeypatching the py2exe code finding Python
1101 # We work around this by monkeypatching the py2exe code finding Python
1102 # modules to replace the found virtualenv distutils modules with the
1102 # modules to replace the found virtualenv distutils modules with the
1103 # original versions via filesystem scanning. This is a bit hacky. But
1103 # original versions via filesystem scanning. This is a bit hacky. But
1104 # it allows us to use virtualenvs for py2exe packaging, which is more
1104 # it allows us to use virtualenvs for py2exe packaging, which is more
1105 # deterministic and reproducible.
1105 # deterministic and reproducible.
1106 #
1106 #
1107 # It's worth noting that the common StackOverflow suggestions for this
1107 # It's worth noting that the common StackOverflow suggestions for this
1108 # problem involve copying the original distutils files into the
1108 # problem involve copying the original distutils files into the
1109 # virtualenv or into the staging directory after setup() is invoked.
1109 # virtualenv or into the staging directory after setup() is invoked.
1110 # The former is very brittle and can easily break setup(). Our hacking
1110 # The former is very brittle and can easily break setup(). Our hacking
1111 # of the found modules routine has a similar result as copying the files
1111 # of the found modules routine has a similar result as copying the files
1112 # manually. But it makes fewer assumptions about how py2exe works and
1112 # manually. But it makes fewer assumptions about how py2exe works and
1113 # is less brittle.
1113 # is less brittle.
1114
1114
1115 # This only catches virtualenvs made with virtualenv (as opposed to
1115 # This only catches virtualenvs made with virtualenv (as opposed to
1116 # venv, which is likely what Python 3 uses).
1116 # venv, which is likely what Python 3 uses).
1117 py2exehacked = py2exeloaded and getattr(sys, 'real_prefix', None) is not None
1117 py2exehacked = py2exeloaded and getattr(sys, 'real_prefix', None) is not None
1118
1118
1119 if py2exehacked:
1119 if py2exehacked:
1120 from distutils.command.py2exe import py2exe as buildpy2exe
1120 from distutils.command.py2exe import py2exe as buildpy2exe
1121 from py2exe.mf import Module as py2exemodule
1121 from py2exe.mf import Module as py2exemodule
1122
1122
1123 class hgbuildpy2exe(buildpy2exe):
1123 class hgbuildpy2exe(buildpy2exe):
1124 def find_needed_modules(self, mf, files, modules):
1124 def find_needed_modules(self, mf, files, modules):
1125 res = buildpy2exe.find_needed_modules(self, mf, files, modules)
1125 res = buildpy2exe.find_needed_modules(self, mf, files, modules)
1126
1126
1127 # Replace virtualenv's distutils modules with the real ones.
1127 # Replace virtualenv's distutils modules with the real ones.
1128 modules = {}
1128 modules = {}
1129 for k, v in res.modules.items():
1129 for k, v in res.modules.items():
1130 if k != 'distutils' and not k.startswith('distutils.'):
1130 if k != 'distutils' and not k.startswith('distutils.'):
1131 modules[k] = v
1131 modules[k] = v
1132
1132
1133 res.modules = modules
1133 res.modules = modules
1134
1134
1135 import opcode
1135 import opcode
1136
1136
1137 distutilsreal = os.path.join(
1137 distutilsreal = os.path.join(
1138 os.path.dirname(opcode.__file__), 'distutils'
1138 os.path.dirname(opcode.__file__), 'distutils'
1139 )
1139 )
1140
1140
1141 for root, dirs, files in os.walk(distutilsreal):
1141 for root, dirs, files in os.walk(distutilsreal):
1142 for f in sorted(files):
1142 for f in sorted(files):
1143 if not f.endswith('.py'):
1143 if not f.endswith('.py'):
1144 continue
1144 continue
1145
1145
1146 full = os.path.join(root, f)
1146 full = os.path.join(root, f)
1147
1147
1148 parents = ['distutils']
1148 parents = ['distutils']
1149
1149
1150 if root != distutilsreal:
1150 if root != distutilsreal:
1151 rel = os.path.relpath(root, distutilsreal)
1151 rel = os.path.relpath(root, distutilsreal)
1152 parents.extend(p for p in rel.split(os.sep))
1152 parents.extend(p for p in rel.split(os.sep))
1153
1153
1154 modname = '%s.%s' % ('.'.join(parents), f[:-3])
1154 modname = '%s.%s' % ('.'.join(parents), f[:-3])
1155
1155
1156 if modname.startswith('distutils.tests.'):
1156 if modname.startswith('distutils.tests.'):
1157 continue
1157 continue
1158
1158
1159 if modname.endswith('.__init__'):
1159 if modname.endswith('.__init__'):
1160 modname = modname[: -len('.__init__')]
1160 modname = modname[: -len('.__init__')]
1161 path = os.path.dirname(full)
1161 path = os.path.dirname(full)
1162 else:
1162 else:
1163 path = None
1163 path = None
1164
1164
1165 res.modules[modname] = py2exemodule(
1165 res.modules[modname] = py2exemodule(
1166 modname, full, path=path
1166 modname, full, path=path
1167 )
1167 )
1168
1168
1169 if 'distutils' not in res.modules:
1169 if 'distutils' not in res.modules:
1170 raise SystemExit('could not find distutils modules')
1170 raise SystemExit('could not find distutils modules')
1171
1171
1172 return res
1172 return res
1173
1173
1174
1174
1175 cmdclass = {
1175 cmdclass = {
1176 'build': hgbuild,
1176 'build': hgbuild,
1177 'build_doc': hgbuilddoc,
1177 'build_doc': hgbuilddoc,
1178 'build_mo': hgbuildmo,
1178 'build_mo': hgbuildmo,
1179 'build_ext': hgbuildext,
1179 'build_ext': hgbuildext,
1180 'build_py': hgbuildpy,
1180 'build_py': hgbuildpy,
1181 'build_scripts': hgbuildscripts,
1181 'build_scripts': hgbuildscripts,
1182 'build_hgextindex': buildhgextindex,
1182 'build_hgextindex': buildhgextindex,
1183 'install': hginstall,
1183 'install': hginstall,
1184 'install_lib': hginstalllib,
1184 'install_lib': hginstalllib,
1185 'install_scripts': hginstallscripts,
1185 'install_scripts': hginstallscripts,
1186 'build_hgexe': buildhgexe,
1186 'build_hgexe': buildhgexe,
1187 }
1187 }
1188
1188
1189 if py2exehacked:
1189 if py2exehacked:
1190 cmdclass['py2exe'] = hgbuildpy2exe
1190 cmdclass['py2exe'] = hgbuildpy2exe
1191
1191
1192 packages = [
1192 packages = [
1193 'mercurial',
1193 'mercurial',
1194 'mercurial.cext',
1194 'mercurial.cext',
1195 'mercurial.cffi',
1195 'mercurial.cffi',
1196 'mercurial.defaultrc',
1196 'mercurial.defaultrc',
1197 'mercurial.helptext',
1197 'mercurial.helptext',
1198 'mercurial.helptext.internals',
1198 'mercurial.helptext.internals',
1199 'mercurial.hgweb',
1199 'mercurial.hgweb',
1200 'mercurial.interfaces',
1200 'mercurial.interfaces',
1201 'mercurial.pure',
1201 'mercurial.pure',
1202 'mercurial.thirdparty',
1202 'mercurial.thirdparty',
1203 'mercurial.thirdparty.attr',
1203 'mercurial.thirdparty.attr',
1204 'mercurial.thirdparty.zope',
1204 'mercurial.thirdparty.zope',
1205 'mercurial.thirdparty.zope.interface',
1205 'mercurial.thirdparty.zope.interface',
1206 'mercurial.utils',
1206 'mercurial.utils',
1207 'mercurial.revlogutils',
1207 'mercurial.revlogutils',
1208 'mercurial.testing',
1208 'mercurial.testing',
1209 'hgext',
1209 'hgext',
1210 'hgext.convert',
1210 'hgext.convert',
1211 'hgext.fsmonitor',
1211 'hgext.fsmonitor',
1212 'hgext.fastannotate',
1212 'hgext.fastannotate',
1213 'hgext.fsmonitor.pywatchman',
1213 'hgext.fsmonitor.pywatchman',
1214 'hgext.highlight',
1214 'hgext.highlight',
1215 'hgext.infinitepush',
1215 'hgext.infinitepush',
1216 'hgext.largefiles',
1216 'hgext.largefiles',
1217 'hgext.lfs',
1217 'hgext.lfs',
1218 'hgext.narrow',
1218 'hgext.narrow',
1219 'hgext.remotefilelog',
1219 'hgext.remotefilelog',
1220 'hgext.zeroconf',
1220 'hgext.zeroconf',
1221 'hgext3rd',
1221 'hgext3rd',
1222 'hgdemandimport',
1222 'hgdemandimport',
1223 ]
1223 ]
1224 if sys.version_info[0] == 2:
1224 if sys.version_info[0] == 2:
1225 packages.extend(
1225 packages.extend(
1226 [
1226 [
1227 'mercurial.thirdparty.concurrent',
1227 'mercurial.thirdparty.concurrent',
1228 'mercurial.thirdparty.concurrent.futures',
1228 'mercurial.thirdparty.concurrent.futures',
1229 ]
1229 ]
1230 )
1230 )
1231
1231
1232 if 'HG_PY2EXE_EXTRA_INSTALL_PACKAGES' in os.environ:
1232 if 'HG_PY2EXE_EXTRA_INSTALL_PACKAGES' in os.environ:
1233 # py2exe can't cope with namespace packages very well, so we have to
1233 # py2exe can't cope with namespace packages very well, so we have to
1234 # install any hgext3rd.* extensions that we want in the final py2exe
1234 # install any hgext3rd.* extensions that we want in the final py2exe
1235 # image here. This is gross, but you gotta do what you gotta do.
1235 # image here. This is gross, but you gotta do what you gotta do.
1236 packages.extend(os.environ['HG_PY2EXE_EXTRA_INSTALL_PACKAGES'].split(' '))
1236 packages.extend(os.environ['HG_PY2EXE_EXTRA_INSTALL_PACKAGES'].split(' '))
1237
1237
1238 common_depends = [
1238 common_depends = [
1239 'mercurial/bitmanipulation.h',
1239 'mercurial/bitmanipulation.h',
1240 'mercurial/compat.h',
1240 'mercurial/compat.h',
1241 'mercurial/cext/util.h',
1241 'mercurial/cext/util.h',
1242 ]
1242 ]
1243 common_include_dirs = ['mercurial']
1243 common_include_dirs = ['mercurial']
1244
1244
1245 osutil_cflags = []
1245 osutil_cflags = []
1246 osutil_ldflags = []
1246 osutil_ldflags = []
1247
1247
1248 # platform specific macros
1248 # platform specific macros
1249 for plat, func in [('bsd', 'setproctitle')]:
1249 for plat, func in [('bsd', 'setproctitle')]:
1250 if re.search(plat, sys.platform) and hasfunction(new_compiler(), func):
1250 if re.search(plat, sys.platform) and hasfunction(new_compiler(), func):
1251 osutil_cflags.append('-DHAVE_%s' % func.upper())
1251 osutil_cflags.append('-DHAVE_%s' % func.upper())
1252
1252
1253 for plat, macro, code in [
1253 for plat, macro, code in [
1254 (
1254 (
1255 'bsd|darwin',
1255 'bsd|darwin',
1256 'BSD_STATFS',
1256 'BSD_STATFS',
1257 '''
1257 '''
1258 #include <sys/param.h>
1258 #include <sys/param.h>
1259 #include <sys/mount.h>
1259 #include <sys/mount.h>
1260 int main() { struct statfs s; return sizeof(s.f_fstypename); }
1260 int main() { struct statfs s; return sizeof(s.f_fstypename); }
1261 ''',
1261 ''',
1262 ),
1262 ),
1263 (
1263 (
1264 'linux',
1264 'linux',
1265 'LINUX_STATFS',
1265 'LINUX_STATFS',
1266 '''
1266 '''
1267 #include <linux/magic.h>
1267 #include <linux/magic.h>
1268 #include <sys/vfs.h>
1268 #include <sys/vfs.h>
1269 int main() { struct statfs s; return sizeof(s.f_type); }
1269 int main() { struct statfs s; return sizeof(s.f_type); }
1270 ''',
1270 ''',
1271 ),
1271 ),
1272 ]:
1272 ]:
1273 if re.search(plat, sys.platform) and cancompile(new_compiler(), code):
1273 if re.search(plat, sys.platform) and cancompile(new_compiler(), code):
1274 osutil_cflags.append('-DHAVE_%s' % macro)
1274 osutil_cflags.append('-DHAVE_%s' % macro)
1275
1275
1276 if sys.platform == 'darwin':
1276 if sys.platform == 'darwin':
1277 osutil_ldflags += ['-framework', 'ApplicationServices']
1277 osutil_ldflags += ['-framework', 'ApplicationServices']
1278
1278
1279 xdiff_srcs = [
1279 xdiff_srcs = [
1280 'mercurial/thirdparty/xdiff/xdiffi.c',
1280 'mercurial/thirdparty/xdiff/xdiffi.c',
1281 'mercurial/thirdparty/xdiff/xprepare.c',
1281 'mercurial/thirdparty/xdiff/xprepare.c',
1282 'mercurial/thirdparty/xdiff/xutils.c',
1282 'mercurial/thirdparty/xdiff/xutils.c',
1283 ]
1283 ]
1284
1284
1285 xdiff_headers = [
1285 xdiff_headers = [
1286 'mercurial/thirdparty/xdiff/xdiff.h',
1286 'mercurial/thirdparty/xdiff/xdiff.h',
1287 'mercurial/thirdparty/xdiff/xdiffi.h',
1287 'mercurial/thirdparty/xdiff/xdiffi.h',
1288 'mercurial/thirdparty/xdiff/xinclude.h',
1288 'mercurial/thirdparty/xdiff/xinclude.h',
1289 'mercurial/thirdparty/xdiff/xmacros.h',
1289 'mercurial/thirdparty/xdiff/xmacros.h',
1290 'mercurial/thirdparty/xdiff/xprepare.h',
1290 'mercurial/thirdparty/xdiff/xprepare.h',
1291 'mercurial/thirdparty/xdiff/xtypes.h',
1291 'mercurial/thirdparty/xdiff/xtypes.h',
1292 'mercurial/thirdparty/xdiff/xutils.h',
1292 'mercurial/thirdparty/xdiff/xutils.h',
1293 ]
1293 ]
1294
1294
1295
1295
1296 class RustCompilationError(CCompilerError):
1296 class RustCompilationError(CCompilerError):
1297 """Exception class for Rust compilation errors."""
1297 """Exception class for Rust compilation errors."""
1298
1298
1299
1299
1300 class RustExtension(Extension):
1300 class RustExtension(Extension):
1301 """Base classes for concrete Rust Extension classes.
1301 """Base classes for concrete Rust Extension classes.
1302 """
1302 """
1303
1303
1304 rusttargetdir = os.path.join('rust', 'target', 'release')
1304 rusttargetdir = os.path.join('rust', 'target', 'release')
1305
1305
1306 def __init__(
1306 def __init__(
1307 self, mpath, sources, rustlibname, subcrate, py3_features=None, **kw
1307 self, mpath, sources, rustlibname, subcrate, py3_features=None, **kw
1308 ):
1308 ):
1309 Extension.__init__(self, mpath, sources, **kw)
1309 Extension.__init__(self, mpath, sources, **kw)
1310 srcdir = self.rustsrcdir = os.path.join('rust', subcrate)
1310 srcdir = self.rustsrcdir = os.path.join('rust', subcrate)
1311 self.py3_features = py3_features
1311 self.py3_features = py3_features
1312
1312
1313 # adding Rust source and control files to depends so that the extension
1313 # adding Rust source and control files to depends so that the extension
1314 # gets rebuilt if they've changed
1314 # gets rebuilt if they've changed
1315 self.depends.append(os.path.join(srcdir, 'Cargo.toml'))
1315 self.depends.append(os.path.join(srcdir, 'Cargo.toml'))
1316 cargo_lock = os.path.join(srcdir, 'Cargo.lock')
1316 cargo_lock = os.path.join(srcdir, 'Cargo.lock')
1317 if os.path.exists(cargo_lock):
1317 if os.path.exists(cargo_lock):
1318 self.depends.append(cargo_lock)
1318 self.depends.append(cargo_lock)
1319 for dirpath, subdir, fnames in os.walk(os.path.join(srcdir, 'src')):
1319 for dirpath, subdir, fnames in os.walk(os.path.join(srcdir, 'src')):
1320 self.depends.extend(
1320 self.depends.extend(
1321 os.path.join(dirpath, fname)
1321 os.path.join(dirpath, fname)
1322 for fname in fnames
1322 for fname in fnames
1323 if os.path.splitext(fname)[1] == '.rs'
1323 if os.path.splitext(fname)[1] == '.rs'
1324 )
1324 )
1325
1325
1326 @staticmethod
1326 @staticmethod
1327 def rustdylibsuffix():
1327 def rustdylibsuffix():
1328 """Return the suffix for shared libraries produced by rustc.
1328 """Return the suffix for shared libraries produced by rustc.
1329
1329
1330 See also: https://doc.rust-lang.org/reference/linkage.html
1330 See also: https://doc.rust-lang.org/reference/linkage.html
1331 """
1331 """
1332 if sys.platform == 'darwin':
1332 if sys.platform == 'darwin':
1333 return '.dylib'
1333 return '.dylib'
1334 elif os.name == 'nt':
1334 elif os.name == 'nt':
1335 return '.dll'
1335 return '.dll'
1336 else:
1336 else:
1337 return '.so'
1337 return '.so'
1338
1338
1339 def rustbuild(self):
1339 def rustbuild(self):
1340 env = os.environ.copy()
1340 env = os.environ.copy()
1341 if 'HGTEST_RESTOREENV' in env:
1341 if 'HGTEST_RESTOREENV' in env:
1342 # Mercurial tests change HOME to a temporary directory,
1342 # Mercurial tests change HOME to a temporary directory,
1343 # but, if installed with rustup, the Rust toolchain needs
1343 # but, if installed with rustup, the Rust toolchain needs
1344 # HOME to be correct (otherwise the 'no default toolchain'
1344 # HOME to be correct (otherwise the 'no default toolchain'
1345 # error message is issued and the build fails).
1345 # error message is issued and the build fails).
1346 # This happens currently with test-hghave.t, which does
1346 # This happens currently with test-hghave.t, which does
1347 # invoke this build.
1347 # invoke this build.
1348
1348
1349 # Unix only fix (os.path.expanduser not really reliable if
1349 # Unix only fix (os.path.expanduser not really reliable if
1350 # HOME is shadowed like this)
1350 # HOME is shadowed like this)
1351 import pwd
1351 import pwd
1352
1352
1353 env['HOME'] = pwd.getpwuid(os.getuid()).pw_dir
1353 env['HOME'] = pwd.getpwuid(os.getuid()).pw_dir
1354
1354
1355 cargocmd = ['cargo', 'rustc', '-vv', '--release']
1355 cargocmd = ['cargo', 'rustc', '-vv', '--release']
1356 if sys.version_info[0] == 3 and self.py3_features is not None:
1356 if sys.version_info[0] == 3 and self.py3_features is not None:
1357 cargocmd.extend(
1357 cargocmd.extend(
1358 ('--features', self.py3_features, '--no-default-features')
1358 ('--features', self.py3_features, '--no-default-features')
1359 )
1359 )
1360 cargocmd.append('--')
1360 cargocmd.append('--')
1361 if sys.platform == 'darwin':
1361 if sys.platform == 'darwin':
1362 cargocmd.extend(
1362 cargocmd.extend(
1363 ("-C", "link-arg=-undefined", "-C", "link-arg=dynamic_lookup")
1363 ("-C", "link-arg=-undefined", "-C", "link-arg=dynamic_lookup")
1364 )
1364 )
1365 try:
1365 try:
1366 subprocess.check_call(cargocmd, env=env, cwd=self.rustsrcdir)
1366 subprocess.check_call(cargocmd, env=env, cwd=self.rustsrcdir)
1367 except OSError as exc:
1367 except OSError as exc:
1368 if exc.errno == errno.ENOENT:
1368 if exc.errno == errno.ENOENT:
1369 raise RustCompilationError("Cargo not found")
1369 raise RustCompilationError("Cargo not found")
1370 elif exc.errno == errno.EACCES:
1370 elif exc.errno == errno.EACCES:
1371 raise RustCompilationError(
1371 raise RustCompilationError(
1372 "Cargo found, but permisssion to execute it is denied"
1372 "Cargo found, but permisssion to execute it is denied"
1373 )
1373 )
1374 else:
1374 else:
1375 raise
1375 raise
1376 except subprocess.CalledProcessError:
1376 except subprocess.CalledProcessError:
1377 raise RustCompilationError(
1377 raise RustCompilationError(
1378 "Cargo failed. Working directory: %r, "
1378 "Cargo failed. Working directory: %r, "
1379 "command: %r, environment: %r"
1379 "command: %r, environment: %r"
1380 % (self.rustsrcdir, cargocmd, env)
1380 % (self.rustsrcdir, cargocmd, env)
1381 )
1381 )
1382
1382
1383
1383
1384 class RustEnhancedExtension(RustExtension):
1384 class RustEnhancedExtension(RustExtension):
1385 """A C Extension, conditionally enhanced with Rust code.
1385 """A C Extension, conditionally enhanced with Rust code.
1386
1386
1387 If the HGWITHRUSTEXT environment variable is set to something else
1387 If the HGWITHRUSTEXT environment variable is set to something else
1388 than 'cpython', the Rust sources get compiled and linked within
1388 than 'cpython', the Rust sources get compiled and linked within
1389 the C target shared library object.
1389 the C target shared library object.
1390 """
1390 """
1391
1391
1392 def __init__(self, mpath, sources, rustlibname, subcrate, **kw):
1392 def __init__(self, mpath, sources, rustlibname, subcrate, **kw):
1393 RustExtension.__init__(
1393 RustExtension.__init__(
1394 self, mpath, sources, rustlibname, subcrate, **kw
1394 self, mpath, sources, rustlibname, subcrate, **kw
1395 )
1395 )
1396 if hgrustext != 'direct-ffi':
1396 if hgrustext != 'direct-ffi':
1397 return
1397 return
1398 self.extra_compile_args.append('-DWITH_RUST')
1398 self.extra_compile_args.append('-DWITH_RUST')
1399 self.libraries.append(rustlibname)
1399 self.libraries.append(rustlibname)
1400 self.library_dirs.append(self.rusttargetdir)
1400 self.library_dirs.append(self.rusttargetdir)
1401
1401
1402 def rustbuild(self):
1402 def rustbuild(self):
1403 if hgrustext == 'direct-ffi':
1403 if hgrustext == 'direct-ffi':
1404 RustExtension.rustbuild(self)
1404 RustExtension.rustbuild(self)
1405
1405
1406
1406
1407 class RustStandaloneExtension(RustExtension):
1407 class RustStandaloneExtension(RustExtension):
1408 def __init__(self, pydottedname, rustcrate, dylibname, **kw):
1408 def __init__(self, pydottedname, rustcrate, dylibname, **kw):
1409 RustExtension.__init__(
1409 RustExtension.__init__(
1410 self, pydottedname, [], dylibname, rustcrate, **kw
1410 self, pydottedname, [], dylibname, rustcrate, **kw
1411 )
1411 )
1412 self.dylibname = dylibname
1412 self.dylibname = dylibname
1413
1413
1414 def build(self, target_dir):
1414 def build(self, target_dir):
1415 self.rustbuild()
1415 self.rustbuild()
1416 target = [target_dir]
1416 target = [target_dir]
1417 target.extend(self.name.split('.'))
1417 target.extend(self.name.split('.'))
1418 target[-1] += DYLIB_SUFFIX
1418 target[-1] += DYLIB_SUFFIX
1419 shutil.copy2(
1419 shutil.copy2(
1420 os.path.join(
1420 os.path.join(
1421 self.rusttargetdir, self.dylibname + self.rustdylibsuffix()
1421 self.rusttargetdir, self.dylibname + self.rustdylibsuffix()
1422 ),
1422 ),
1423 os.path.join(*target),
1423 os.path.join(*target),
1424 )
1424 )
1425
1425
1426
1426
1427 extmodules = [
1427 extmodules = [
1428 Extension(
1428 Extension(
1429 'mercurial.cext.base85',
1429 'mercurial.cext.base85',
1430 ['mercurial/cext/base85.c'],
1430 ['mercurial/cext/base85.c'],
1431 include_dirs=common_include_dirs,
1431 include_dirs=common_include_dirs,
1432 depends=common_depends,
1432 depends=common_depends,
1433 ),
1433 ),
1434 Extension(
1434 Extension(
1435 'mercurial.cext.bdiff',
1435 'mercurial.cext.bdiff',
1436 ['mercurial/bdiff.c', 'mercurial/cext/bdiff.c'] + xdiff_srcs,
1436 ['mercurial/bdiff.c', 'mercurial/cext/bdiff.c'] + xdiff_srcs,
1437 include_dirs=common_include_dirs,
1437 include_dirs=common_include_dirs,
1438 depends=common_depends + ['mercurial/bdiff.h'] + xdiff_headers,
1438 depends=common_depends + ['mercurial/bdiff.h'] + xdiff_headers,
1439 ),
1439 ),
1440 Extension(
1440 Extension(
1441 'mercurial.cext.mpatch',
1441 'mercurial.cext.mpatch',
1442 ['mercurial/mpatch.c', 'mercurial/cext/mpatch.c'],
1442 ['mercurial/mpatch.c', 'mercurial/cext/mpatch.c'],
1443 include_dirs=common_include_dirs,
1443 include_dirs=common_include_dirs,
1444 depends=common_depends,
1444 depends=common_depends,
1445 ),
1445 ),
1446 RustEnhancedExtension(
1446 RustEnhancedExtension(
1447 'mercurial.cext.parsers',
1447 'mercurial.cext.parsers',
1448 [
1448 [
1449 'mercurial/cext/charencode.c',
1449 'mercurial/cext/charencode.c',
1450 'mercurial/cext/dirs.c',
1450 'mercurial/cext/dirs.c',
1451 'mercurial/cext/manifest.c',
1451 'mercurial/cext/manifest.c',
1452 'mercurial/cext/parsers.c',
1452 'mercurial/cext/parsers.c',
1453 'mercurial/cext/pathencode.c',
1453 'mercurial/cext/pathencode.c',
1454 'mercurial/cext/revlog.c',
1454 'mercurial/cext/revlog.c',
1455 ],
1455 ],
1456 'hgdirectffi',
1456 'hgdirectffi',
1457 'hg-direct-ffi',
1457 'hg-direct-ffi',
1458 include_dirs=common_include_dirs,
1458 include_dirs=common_include_dirs,
1459 depends=common_depends
1459 depends=common_depends
1460 + [
1460 + [
1461 'mercurial/cext/charencode.h',
1461 'mercurial/cext/charencode.h',
1462 'mercurial/cext/revlog.h',
1462 'mercurial/cext/revlog.h',
1463 'rust/hg-core/src/ancestors.rs',
1463 'rust/hg-core/src/ancestors.rs',
1464 'rust/hg-core/src/lib.rs',
1464 'rust/hg-core/src/lib.rs',
1465 ],
1465 ],
1466 ),
1466 ),
1467 Extension(
1467 Extension(
1468 'mercurial.cext.osutil',
1468 'mercurial.cext.osutil',
1469 ['mercurial/cext/osutil.c'],
1469 ['mercurial/cext/osutil.c'],
1470 include_dirs=common_include_dirs,
1470 include_dirs=common_include_dirs,
1471 extra_compile_args=osutil_cflags,
1471 extra_compile_args=osutil_cflags,
1472 extra_link_args=osutil_ldflags,
1472 extra_link_args=osutil_ldflags,
1473 depends=common_depends,
1473 depends=common_depends,
1474 ),
1474 ),
1475 Extension(
1475 Extension(
1476 'mercurial.thirdparty.zope.interface._zope_interface_coptimizations',
1476 'mercurial.thirdparty.zope.interface._zope_interface_coptimizations',
1477 [
1477 [
1478 'mercurial/thirdparty/zope/interface/_zope_interface_coptimizations.c',
1478 'mercurial/thirdparty/zope/interface/_zope_interface_coptimizations.c',
1479 ],
1479 ],
1480 ),
1480 ),
1481 Extension(
1481 Extension(
1482 'mercurial.thirdparty.sha1dc',
1482 'mercurial.thirdparty.sha1dc',
1483 [
1483 [
1484 'mercurial/thirdparty/sha1dc/cext.c',
1484 'mercurial/thirdparty/sha1dc/cext.c',
1485 'mercurial/thirdparty/sha1dc/lib/sha1.c',
1485 'mercurial/thirdparty/sha1dc/lib/sha1.c',
1486 'mercurial/thirdparty/sha1dc/lib/ubc_check.c',
1486 'mercurial/thirdparty/sha1dc/lib/ubc_check.c',
1487 ],
1487 ],
1488 ),
1488 ),
1489 Extension(
1489 Extension(
1490 'hgext.fsmonitor.pywatchman.bser', ['hgext/fsmonitor/pywatchman/bser.c']
1490 'hgext.fsmonitor.pywatchman.bser', ['hgext/fsmonitor/pywatchman/bser.c']
1491 ),
1491 ),
1492 RustStandaloneExtension(
1492 RustStandaloneExtension(
1493 'mercurial.rustext', 'hg-cpython', 'librusthg', py3_features='python3'
1493 'mercurial.rustext', 'hg-cpython', 'librusthg', py3_features='python3'
1494 ),
1494 ),
1495 ]
1495 ]
1496
1496
1497
1497
1498 sys.path.insert(0, 'contrib/python-zstandard')
1498 sys.path.insert(0, 'contrib/python-zstandard')
1499 import setup_zstd
1499 import setup_zstd
1500
1500
1501 extmodules.append(
1501 extmodules.append(
1502 setup_zstd.get_c_extension(
1502 setup_zstd.get_c_extension(
1503 name='mercurial.zstd', root=os.path.abspath(os.path.dirname(__file__))
1503 name='mercurial.zstd', root=os.path.abspath(os.path.dirname(__file__))
1504 )
1504 )
1505 )
1505 )
1506
1506
1507 try:
1507 try:
1508 from distutils import cygwinccompiler
1508 from distutils import cygwinccompiler
1509
1509
1510 # the -mno-cygwin option has been deprecated for years
1510 # the -mno-cygwin option has been deprecated for years
1511 mingw32compilerclass = cygwinccompiler.Mingw32CCompiler
1511 mingw32compilerclass = cygwinccompiler.Mingw32CCompiler
1512
1512
1513 class HackedMingw32CCompiler(cygwinccompiler.Mingw32CCompiler):
1513 class HackedMingw32CCompiler(cygwinccompiler.Mingw32CCompiler):
1514 def __init__(self, *args, **kwargs):
1514 def __init__(self, *args, **kwargs):
1515 mingw32compilerclass.__init__(self, *args, **kwargs)
1515 mingw32compilerclass.__init__(self, *args, **kwargs)
1516 for i in 'compiler compiler_so linker_exe linker_so'.split():
1516 for i in 'compiler compiler_so linker_exe linker_so'.split():
1517 try:
1517 try:
1518 getattr(self, i).remove('-mno-cygwin')
1518 getattr(self, i).remove('-mno-cygwin')
1519 except ValueError:
1519 except ValueError:
1520 pass
1520 pass
1521
1521
1522 cygwinccompiler.Mingw32CCompiler = HackedMingw32CCompiler
1522 cygwinccompiler.Mingw32CCompiler = HackedMingw32CCompiler
1523 except ImportError:
1523 except ImportError:
1524 # the cygwinccompiler package is not available on some Python
1524 # the cygwinccompiler package is not available on some Python
1525 # distributions like the ones from the optware project for Synology
1525 # distributions like the ones from the optware project for Synology
1526 # DiskStation boxes
1526 # DiskStation boxes
1527 class HackedMingw32CCompiler(object):
1527 class HackedMingw32CCompiler(object):
1528 pass
1528 pass
1529
1529
1530
1530
1531 if os.name == 'nt':
1531 if os.name == 'nt':
1532 # Allow compiler/linker flags to be added to Visual Studio builds. Passing
1532 # Allow compiler/linker flags to be added to Visual Studio builds. Passing
1533 # extra_link_args to distutils.extensions.Extension() doesn't have any
1533 # extra_link_args to distutils.extensions.Extension() doesn't have any
1534 # effect.
1534 # effect.
1535 from distutils import msvccompiler
1535 from distutils import msvccompiler
1536
1536
1537 msvccompilerclass = msvccompiler.MSVCCompiler
1537 msvccompilerclass = msvccompiler.MSVCCompiler
1538
1538
1539 class HackedMSVCCompiler(msvccompiler.MSVCCompiler):
1539 class HackedMSVCCompiler(msvccompiler.MSVCCompiler):
1540 def initialize(self):
1540 def initialize(self):
1541 msvccompilerclass.initialize(self)
1541 msvccompilerclass.initialize(self)
1542 # "warning LNK4197: export 'func' specified multiple times"
1542 # "warning LNK4197: export 'func' specified multiple times"
1543 self.ldflags_shared.append('/ignore:4197')
1543 self.ldflags_shared.append('/ignore:4197')
1544 self.ldflags_shared_debug.append('/ignore:4197')
1544 self.ldflags_shared_debug.append('/ignore:4197')
1545
1545
1546 msvccompiler.MSVCCompiler = HackedMSVCCompiler
1546 msvccompiler.MSVCCompiler = HackedMSVCCompiler
1547
1547
1548 packagedata = {
1548 packagedata = {
1549 'mercurial': [
1549 'mercurial': [
1550 'locale/*/LC_MESSAGES/hg.mo',
1550 'locale/*/LC_MESSAGES/hg.mo',
1551 'defaultrc/*.rc',
1551 'defaultrc/*.rc',
1552 'dummycert.pem',
1552 'dummycert.pem',
1553 ],
1553 ],
1554 'mercurial.helptext': ['*.txt',],
1554 'mercurial.helptext': ['*.txt',],
1555 'mercurial.helptext.internals': ['*.txt',],
1555 'mercurial.helptext.internals': ['*.txt',],
1556 }
1556 }
1557
1557
1558
1558
1559 def ordinarypath(p):
1559 def ordinarypath(p):
1560 return p and p[0] != '.' and p[-1] != '~'
1560 return p and p[0] != '.' and p[-1] != '~'
1561
1561
1562
1562
1563 for root in ('templates',):
1563 for root in ('templates',):
1564 for curdir, dirs, files in os.walk(os.path.join('mercurial', root)):
1564 for curdir, dirs, files in os.walk(os.path.join('mercurial', root)):
1565 curdir = curdir.split(os.sep, 1)[1]
1565 curdir = curdir.split(os.sep, 1)[1]
1566 dirs[:] = filter(ordinarypath, dirs)
1566 dirs[:] = filter(ordinarypath, dirs)
1567 for f in filter(ordinarypath, files):
1567 for f in filter(ordinarypath, files):
1568 f = os.path.join(curdir, f)
1568 f = os.path.join(curdir, f)
1569 packagedata['mercurial'].append(f)
1569 packagedata['mercurial'].append(f)
1570
1570
1571 datafiles = []
1571 datafiles = []
1572
1572
1573 # distutils expects version to be str/unicode. Converting it to
1573 # distutils expects version to be str/unicode. Converting it to
1574 # unicode on Python 2 still works because it won't contain any
1574 # unicode on Python 2 still works because it won't contain any
1575 # non-ascii bytes and will be implicitly converted back to bytes
1575 # non-ascii bytes and will be implicitly converted back to bytes
1576 # when operated on.
1576 # when operated on.
1577 assert isinstance(version, bytes)
1577 assert isinstance(version, bytes)
1578 setupversion = version.decode('ascii')
1578 setupversion = version.decode('ascii')
1579
1579
1580 extra = {}
1580 extra = {}
1581
1581
1582 py2exepackages = [
1582 py2exepackages = [
1583 'hgdemandimport',
1583 'hgdemandimport',
1584 'hgext3rd',
1584 'hgext3rd',
1585 'hgext',
1585 'hgext',
1586 'email',
1586 'email',
1587 # implicitly imported per module policy
1587 # implicitly imported per module policy
1588 # (cffi wouldn't be used as a frozen exe)
1588 # (cffi wouldn't be used as a frozen exe)
1589 'mercurial.cext',
1589 'mercurial.cext',
1590 #'mercurial.cffi',
1590 #'mercurial.cffi',
1591 'mercurial.pure',
1591 'mercurial.pure',
1592 ]
1592 ]
1593
1593
1594 py2exeexcludes = []
1594 py2exeexcludes = []
1595 py2exedllexcludes = ['crypt32.dll']
1595 py2exedllexcludes = ['crypt32.dll']
1596
1596
1597 if issetuptools:
1597 if issetuptools:
1598 extra['python_requires'] = supportedpy
1598 extra['python_requires'] = supportedpy
1599
1599
1600 if py2exeloaded:
1600 if py2exeloaded:
1601 extra['console'] = [
1601 extra['console'] = [
1602 {
1602 {
1603 'script': 'hg',
1603 'script': 'hg',
1604 'copyright': 'Copyright (C) 2005-2020 Matt Mackall and others',
1604 'copyright': 'Copyright (C) 2005-2020 Matt Mackall and others',
1605 'product_version': version,
1605 'product_version': version,
1606 }
1606 }
1607 ]
1607 ]
1608 # Sub command of 'build' because 'py2exe' does not handle sub_commands.
1608 # Sub command of 'build' because 'py2exe' does not handle sub_commands.
1609 # Need to override hgbuild because it has a private copy of
1609 # Need to override hgbuild because it has a private copy of
1610 # build.sub_commands.
1610 # build.sub_commands.
1611 hgbuild.sub_commands.insert(0, ('build_hgextindex', None))
1611 hgbuild.sub_commands.insert(0, ('build_hgextindex', None))
1612 # put dlls in sub directory so that they won't pollute PATH
1612 # put dlls in sub directory so that they won't pollute PATH
1613 extra['zipfile'] = 'lib/library.zip'
1613 extra['zipfile'] = 'lib/library.zip'
1614
1614
1615 # We allow some configuration to be supplemented via environment
1615 # We allow some configuration to be supplemented via environment
1616 # variables. This is better than setup.cfg files because it allows
1616 # variables. This is better than setup.cfg files because it allows
1617 # supplementing configs instead of replacing them.
1617 # supplementing configs instead of replacing them.
1618 extrapackages = os.environ.get('HG_PY2EXE_EXTRA_PACKAGES')
1618 extrapackages = os.environ.get('HG_PY2EXE_EXTRA_PACKAGES')
1619 if extrapackages:
1619 if extrapackages:
1620 py2exepackages.extend(extrapackages.split(' '))
1620 py2exepackages.extend(extrapackages.split(' '))
1621
1621
1622 excludes = os.environ.get('HG_PY2EXE_EXTRA_EXCLUDES')
1622 excludes = os.environ.get('HG_PY2EXE_EXTRA_EXCLUDES')
1623 if excludes:
1623 if excludes:
1624 py2exeexcludes.extend(excludes.split(' '))
1624 py2exeexcludes.extend(excludes.split(' '))
1625
1625
1626 dllexcludes = os.environ.get('HG_PY2EXE_EXTRA_DLL_EXCLUDES')
1626 dllexcludes = os.environ.get('HG_PY2EXE_EXTRA_DLL_EXCLUDES')
1627 if dllexcludes:
1627 if dllexcludes:
1628 py2exedllexcludes.extend(dllexcludes.split(' '))
1628 py2exedllexcludes.extend(dllexcludes.split(' '))
1629
1629
1630 if os.name == 'nt':
1630 if os.name == 'nt':
1631 # Windows binary file versions for exe/dll files must have the
1631 # Windows binary file versions for exe/dll files must have the
1632 # form W.X.Y.Z, where W,X,Y,Z are numbers in the range 0..65535
1632 # form W.X.Y.Z, where W,X,Y,Z are numbers in the range 0..65535
1633 setupversion = setupversion.split(r'+', 1)[0]
1633 setupversion = setupversion.split(r'+', 1)[0]
1634
1634
1635 if sys.platform == 'darwin' and os.path.exists('/usr/bin/xcodebuild'):
1635 if sys.platform == 'darwin' and os.path.exists('/usr/bin/xcodebuild'):
1636 version = runcmd(['/usr/bin/xcodebuild', '-version'], {})[1].splitlines()
1636 version = runcmd(['/usr/bin/xcodebuild', '-version'], {})[1].splitlines()
1637 if version:
1637 if version:
1638 version = version[0]
1638 version = version[0]
1639 if sys.version_info[0] == 3:
1639 if sys.version_info[0] == 3:
1640 version = version.decode('utf-8')
1640 version = version.decode('utf-8')
1641 xcode4 = version.startswith('Xcode') and StrictVersion(
1641 xcode4 = version.startswith('Xcode') and StrictVersion(
1642 version.split()[1]
1642 version.split()[1]
1643 ) >= StrictVersion('4.0')
1643 ) >= StrictVersion('4.0')
1644 xcode51 = re.match(r'^Xcode\s+5\.1', version) is not None
1644 xcode51 = re.match(r'^Xcode\s+5\.1', version) is not None
1645 else:
1645 else:
1646 # xcodebuild returns empty on OS X Lion with XCode 4.3 not
1646 # xcodebuild returns empty on OS X Lion with XCode 4.3 not
1647 # installed, but instead with only command-line tools. Assume
1647 # installed, but instead with only command-line tools. Assume
1648 # that only happens on >= Lion, thus no PPC support.
1648 # that only happens on >= Lion, thus no PPC support.
1649 xcode4 = True
1649 xcode4 = True
1650 xcode51 = False
1650 xcode51 = False
1651
1651
1652 # XCode 4.0 dropped support for ppc architecture, which is hardcoded in
1652 # XCode 4.0 dropped support for ppc architecture, which is hardcoded in
1653 # distutils.sysconfig
1653 # distutils.sysconfig
1654 if xcode4:
1654 if xcode4:
1655 os.environ['ARCHFLAGS'] = ''
1655 os.environ['ARCHFLAGS'] = ''
1656
1656
1657 # XCode 5.1 changes clang such that it now fails to compile if the
1657 # XCode 5.1 changes clang such that it now fails to compile if the
1658 # -mno-fused-madd flag is passed, but the version of Python shipped with
1658 # -mno-fused-madd flag is passed, but the version of Python shipped with
1659 # OS X 10.9 Mavericks includes this flag. This causes problems in all
1659 # OS X 10.9 Mavericks includes this flag. This causes problems in all
1660 # C extension modules, and a bug has been filed upstream at
1660 # C extension modules, and a bug has been filed upstream at
1661 # http://bugs.python.org/issue21244. We also need to patch this here
1661 # http://bugs.python.org/issue21244. We also need to patch this here
1662 # so Mercurial can continue to compile in the meantime.
1662 # so Mercurial can continue to compile in the meantime.
1663 if xcode51:
1663 if xcode51:
1664 cflags = get_config_var('CFLAGS')
1664 cflags = get_config_var('CFLAGS')
1665 if cflags and re.search(r'-mno-fused-madd\b', cflags) is not None:
1665 if cflags and re.search(r'-mno-fused-madd\b', cflags) is not None:
1666 os.environ['CFLAGS'] = (
1666 os.environ['CFLAGS'] = (
1667 os.environ.get('CFLAGS', '') + ' -Qunused-arguments'
1667 os.environ.get('CFLAGS', '') + ' -Qunused-arguments'
1668 )
1668 )
1669
1669
1670 setup(
1670 setup(
1671 name='mercurial',
1671 name='mercurial',
1672 version=setupversion,
1672 version=setupversion,
1673 author='Matt Mackall and many others',
1673 author='Matt Mackall and many others',
1674 author_email='mercurial@mercurial-scm.org',
1674 author_email='mercurial@mercurial-scm.org',
1675 url='https://mercurial-scm.org/',
1675 url='https://mercurial-scm.org/',
1676 download_url='https://mercurial-scm.org/release/',
1676 download_url='https://mercurial-scm.org/release/',
1677 description=(
1677 description=(
1678 'Fast scalable distributed SCM (revision control, version '
1678 'Fast scalable distributed SCM (revision control, version '
1679 'control) system'
1679 'control) system'
1680 ),
1680 ),
1681 long_description=(
1681 long_description=(
1682 'Mercurial is a distributed SCM tool written in Python.'
1682 'Mercurial is a distributed SCM tool written in Python.'
1683 ' It is used by a number of large projects that require'
1683 ' It is used by a number of large projects that require'
1684 ' fast, reliable distributed revision control, such as '
1684 ' fast, reliable distributed revision control, such as '
1685 'Mozilla.'
1685 'Mozilla.'
1686 ),
1686 ),
1687 license='GNU GPLv2 or any later version',
1687 license='GNU GPLv2 or any later version',
1688 classifiers=[
1688 classifiers=[
1689 'Development Status :: 6 - Mature',
1689 'Development Status :: 6 - Mature',
1690 'Environment :: Console',
1690 'Environment :: Console',
1691 'Intended Audience :: Developers',
1691 'Intended Audience :: Developers',
1692 'Intended Audience :: System Administrators',
1692 'Intended Audience :: System Administrators',
1693 'License :: OSI Approved :: GNU General Public License (GPL)',
1693 'License :: OSI Approved :: GNU General Public License (GPL)',
1694 'Natural Language :: Danish',
1694 'Natural Language :: Danish',
1695 'Natural Language :: English',
1695 'Natural Language :: English',
1696 'Natural Language :: German',
1696 'Natural Language :: German',
1697 'Natural Language :: Italian',
1697 'Natural Language :: Italian',
1698 'Natural Language :: Japanese',
1698 'Natural Language :: Japanese',
1699 'Natural Language :: Portuguese (Brazilian)',
1699 'Natural Language :: Portuguese (Brazilian)',
1700 'Operating System :: Microsoft :: Windows',
1700 'Operating System :: Microsoft :: Windows',
1701 'Operating System :: OS Independent',
1701 'Operating System :: OS Independent',
1702 'Operating System :: POSIX',
1702 'Operating System :: POSIX',
1703 'Programming Language :: C',
1703 'Programming Language :: C',
1704 'Programming Language :: Python',
1704 'Programming Language :: Python',
1705 'Topic :: Software Development :: Version Control',
1705 'Topic :: Software Development :: Version Control',
1706 ],
1706 ],
1707 scripts=scripts,
1707 scripts=scripts,
1708 packages=packages,
1708 packages=packages,
1709 ext_modules=extmodules,
1709 ext_modules=extmodules,
1710 data_files=datafiles,
1710 data_files=datafiles,
1711 package_data=packagedata,
1711 package_data=packagedata,
1712 cmdclass=cmdclass,
1712 cmdclass=cmdclass,
1713 distclass=hgdist,
1713 distclass=hgdist,
1714 options={
1714 options={
1715 'py2exe': {
1715 'py2exe': {
1716 'bundle_files': 3,
1716 'bundle_files': 3,
1717 'dll_excludes': py2exedllexcludes,
1717 'dll_excludes': py2exedllexcludes,
1718 'excludes': py2exeexcludes,
1718 'excludes': py2exeexcludes,
1719 'packages': py2exepackages,
1719 'packages': py2exepackages,
1720 },
1720 },
1721 'bdist_mpkg': {
1721 'bdist_mpkg': {
1722 'zipdist': False,
1722 'zipdist': False,
1723 'license': 'COPYING',
1723 'license': 'COPYING',
1724 'readme': 'contrib/packaging/macosx/Readme.html',
1724 'readme': 'contrib/packaging/macosx/Readme.html',
1725 'welcome': 'contrib/packaging/macosx/Welcome.html',
1725 'welcome': 'contrib/packaging/macosx/Welcome.html',
1726 },
1726 },
1727 },
1727 },
1728 **extra
1728 **extra
1729 )
1729 )
General Comments 0
You need to be logged in to leave comments. Login now