##// END OF EJS Templates
setup: use setuptools on Windows (issue5400)...
Gregory Szorc -
r31289:718a57e9 default
parent child Browse files
Show More
@@ -1,758 +1,761 b''
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 sys, platform
7 import sys, platform
8 if getattr(sys, 'version_info', (0, 0, 0)) < (2, 6, 0, 'final'):
8 if getattr(sys, 'version_info', (0, 0, 0)) < (2, 6, 0, 'final'):
9 raise SystemExit("Mercurial requires Python 2.6 or later.")
9 raise SystemExit("Mercurial requires Python 2.6 or later.")
10
10
11 if sys.version_info[0] >= 3:
11 if sys.version_info[0] >= 3:
12 printf = eval('print')
12 printf = eval('print')
13 libdir_escape = 'unicode_escape'
13 libdir_escape = 'unicode_escape'
14 else:
14 else:
15 libdir_escape = 'string_escape'
15 libdir_escape = 'string_escape'
16 def printf(*args, **kwargs):
16 def printf(*args, **kwargs):
17 f = kwargs.get('file', sys.stdout)
17 f = kwargs.get('file', sys.stdout)
18 end = kwargs.get('end', '\n')
18 end = kwargs.get('end', '\n')
19 f.write(b' '.join(args) + end)
19 f.write(b' '.join(args) + end)
20
20
21 # Solaris Python packaging brain damage
21 # Solaris Python packaging brain damage
22 try:
22 try:
23 import hashlib
23 import hashlib
24 sha = hashlib.sha1()
24 sha = hashlib.sha1()
25 except ImportError:
25 except ImportError:
26 try:
26 try:
27 import sha
27 import sha
28 sha.sha # silence unused import warning
28 sha.sha # silence unused import warning
29 except ImportError:
29 except ImportError:
30 raise SystemExit(
30 raise SystemExit(
31 "Couldn't import standard hashlib (incomplete Python install).")
31 "Couldn't import standard hashlib (incomplete Python install).")
32
32
33 try:
33 try:
34 import zlib
34 import zlib
35 zlib.compressobj # silence unused import warning
35 zlib.compressobj # silence unused import warning
36 except ImportError:
36 except ImportError:
37 raise SystemExit(
37 raise SystemExit(
38 "Couldn't import standard zlib (incomplete Python install).")
38 "Couldn't import standard zlib (incomplete Python install).")
39
39
40 # The base IronPython distribution (as of 2.7.1) doesn't support bz2
40 # The base IronPython distribution (as of 2.7.1) doesn't support bz2
41 isironpython = False
41 isironpython = False
42 try:
42 try:
43 isironpython = (platform.python_implementation()
43 isironpython = (platform.python_implementation()
44 .lower().find("ironpython") != -1)
44 .lower().find("ironpython") != -1)
45 except AttributeError:
45 except AttributeError:
46 pass
46 pass
47
47
48 if isironpython:
48 if isironpython:
49 sys.stderr.write("warning: IronPython detected (no bz2 support)\n")
49 sys.stderr.write("warning: IronPython detected (no bz2 support)\n")
50 else:
50 else:
51 try:
51 try:
52 import bz2
52 import bz2
53 bz2.BZ2Compressor # silence unused import warning
53 bz2.BZ2Compressor # silence unused import warning
54 except ImportError:
54 except ImportError:
55 raise SystemExit(
55 raise SystemExit(
56 "Couldn't import standard bz2 (incomplete Python install).")
56 "Couldn't import standard bz2 (incomplete Python install).")
57
57
58 ispypy = "PyPy" in sys.version
58 ispypy = "PyPy" in sys.version
59
59
60 import ctypes
60 import ctypes
61 import os, stat, subprocess, time
61 import os, stat, subprocess, time
62 import re
62 import re
63 import shutil
63 import shutil
64 import tempfile
64 import tempfile
65 from distutils import log
65 from distutils import log
66 if 'FORCE_SETUPTOOLS' in os.environ:
66 # We have issues with setuptools on some platforms and builders. Until
67 # those are resolved, setuptools is opt-in except for platforms where
68 # we don't have issues.
69 if os.name == 'nt' or 'FORCE_SETUPTOOLS' in os.environ:
67 from setuptools import setup
70 from setuptools import setup
68 else:
71 else:
69 from distutils.core import setup
72 from distutils.core import setup
70 from distutils.ccompiler import new_compiler
73 from distutils.ccompiler import new_compiler
71 from distutils.core import Command, Extension
74 from distutils.core import Command, Extension
72 from distutils.dist import Distribution
75 from distutils.dist import Distribution
73 from distutils.command.build import build
76 from distutils.command.build import build
74 from distutils.command.build_ext import build_ext
77 from distutils.command.build_ext import build_ext
75 from distutils.command.build_py import build_py
78 from distutils.command.build_py import build_py
76 from distutils.command.build_scripts import build_scripts
79 from distutils.command.build_scripts import build_scripts
77 from distutils.command.install_lib import install_lib
80 from distutils.command.install_lib import install_lib
78 from distutils.command.install_scripts import install_scripts
81 from distutils.command.install_scripts import install_scripts
79 from distutils.spawn import spawn, find_executable
82 from distutils.spawn import spawn, find_executable
80 from distutils import file_util
83 from distutils import file_util
81 from distutils.errors import (
84 from distutils.errors import (
82 CCompilerError,
85 CCompilerError,
83 DistutilsError,
86 DistutilsError,
84 DistutilsExecError,
87 DistutilsExecError,
85 )
88 )
86 from distutils.sysconfig import get_python_inc, get_config_var
89 from distutils.sysconfig import get_python_inc, get_config_var
87 from distutils.version import StrictVersion
90 from distutils.version import StrictVersion
88
91
89 scripts = ['hg']
92 scripts = ['hg']
90 if os.name == 'nt':
93 if os.name == 'nt':
91 # We remove hg.bat if we are able to build hg.exe.
94 # We remove hg.bat if we are able to build hg.exe.
92 scripts.append('contrib/win32/hg.bat')
95 scripts.append('contrib/win32/hg.bat')
93
96
94 # simplified version of distutils.ccompiler.CCompiler.has_function
97 # simplified version of distutils.ccompiler.CCompiler.has_function
95 # that actually removes its temporary files.
98 # that actually removes its temporary files.
96 def hasfunction(cc, funcname):
99 def hasfunction(cc, funcname):
97 tmpdir = tempfile.mkdtemp(prefix='hg-install-')
100 tmpdir = tempfile.mkdtemp(prefix='hg-install-')
98 devnull = oldstderr = None
101 devnull = oldstderr = None
99 try:
102 try:
100 fname = os.path.join(tmpdir, 'funcname.c')
103 fname = os.path.join(tmpdir, 'funcname.c')
101 f = open(fname, 'w')
104 f = open(fname, 'w')
102 f.write('int main(void) {\n')
105 f.write('int main(void) {\n')
103 f.write(' %s();\n' % funcname)
106 f.write(' %s();\n' % funcname)
104 f.write('}\n')
107 f.write('}\n')
105 f.close()
108 f.close()
106 # Redirect stderr to /dev/null to hide any error messages
109 # Redirect stderr to /dev/null to hide any error messages
107 # from the compiler.
110 # from the compiler.
108 # This will have to be changed if we ever have to check
111 # This will have to be changed if we ever have to check
109 # for a function on Windows.
112 # for a function on Windows.
110 devnull = open('/dev/null', 'w')
113 devnull = open('/dev/null', 'w')
111 oldstderr = os.dup(sys.stderr.fileno())
114 oldstderr = os.dup(sys.stderr.fileno())
112 os.dup2(devnull.fileno(), sys.stderr.fileno())
115 os.dup2(devnull.fileno(), sys.stderr.fileno())
113 objects = cc.compile([fname], output_dir=tmpdir)
116 objects = cc.compile([fname], output_dir=tmpdir)
114 cc.link_executable(objects, os.path.join(tmpdir, "a.out"))
117 cc.link_executable(objects, os.path.join(tmpdir, "a.out"))
115 return True
118 return True
116 except Exception:
119 except Exception:
117 return False
120 return False
118 finally:
121 finally:
119 if oldstderr is not None:
122 if oldstderr is not None:
120 os.dup2(oldstderr, sys.stderr.fileno())
123 os.dup2(oldstderr, sys.stderr.fileno())
121 if devnull is not None:
124 if devnull is not None:
122 devnull.close()
125 devnull.close()
123 shutil.rmtree(tmpdir)
126 shutil.rmtree(tmpdir)
124
127
125 # py2exe needs to be installed to work
128 # py2exe needs to be installed to work
126 try:
129 try:
127 import py2exe
130 import py2exe
128 py2exe.Distribution # silence unused import warning
131 py2exe.Distribution # silence unused import warning
129 py2exeloaded = True
132 py2exeloaded = True
130 # import py2exe's patched Distribution class
133 # import py2exe's patched Distribution class
131 from distutils.core import Distribution
134 from distutils.core import Distribution
132 except ImportError:
135 except ImportError:
133 py2exeloaded = False
136 py2exeloaded = False
134
137
135 def runcmd(cmd, env):
138 def runcmd(cmd, env):
136 if (sys.platform == 'plan9'
139 if (sys.platform == 'plan9'
137 and (sys.version_info[0] == 2 and sys.version_info[1] < 7)):
140 and (sys.version_info[0] == 2 and sys.version_info[1] < 7)):
138 # subprocess kludge to work around issues in half-baked Python
141 # subprocess kludge to work around issues in half-baked Python
139 # ports, notably bichued/python:
142 # ports, notably bichued/python:
140 _, out, err = os.popen3(cmd)
143 _, out, err = os.popen3(cmd)
141 return str(out), str(err)
144 return str(out), str(err)
142 else:
145 else:
143 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
146 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
144 stderr=subprocess.PIPE, env=env)
147 stderr=subprocess.PIPE, env=env)
145 out, err = p.communicate()
148 out, err = p.communicate()
146 return out, err
149 return out, err
147
150
148 def runhg(cmd, env):
151 def runhg(cmd, env):
149 out, err = runcmd(cmd, env)
152 out, err = runcmd(cmd, env)
150 # If root is executing setup.py, but the repository is owned by
153 # If root is executing setup.py, but the repository is owned by
151 # another user (as in "sudo python setup.py install") we will get
154 # another user (as in "sudo python setup.py install") we will get
152 # trust warnings since the .hg/hgrc file is untrusted. That is
155 # trust warnings since the .hg/hgrc file is untrusted. That is
153 # fine, we don't want to load it anyway. Python may warn about
156 # fine, we don't want to load it anyway. Python may warn about
154 # a missing __init__.py in mercurial/locale, we also ignore that.
157 # a missing __init__.py in mercurial/locale, we also ignore that.
155 err = [e for e in err.splitlines()
158 err = [e for e in err.splitlines()
156 if not e.startswith(b'not trusting file') \
159 if not e.startswith(b'not trusting file') \
157 and not e.startswith(b'warning: Not importing') \
160 and not e.startswith(b'warning: Not importing') \
158 and not e.startswith(b'obsolete feature not enabled')]
161 and not e.startswith(b'obsolete feature not enabled')]
159 if err:
162 if err:
160 printf("stderr from '%s':" % (' '.join(cmd)), file=sys.stderr)
163 printf("stderr from '%s':" % (' '.join(cmd)), file=sys.stderr)
161 printf(b'\n'.join([b' ' + e for e in err]), file=sys.stderr)
164 printf(b'\n'.join([b' ' + e for e in err]), file=sys.stderr)
162 return ''
165 return ''
163 return out
166 return out
164
167
165 version = ''
168 version = ''
166
169
167 # Execute hg out of this directory with a custom environment which takes care
170 # Execute hg out of this directory with a custom environment which takes care
168 # to not use any hgrc files and do no localization.
171 # to not use any hgrc files and do no localization.
169 env = {'HGMODULEPOLICY': 'py',
172 env = {'HGMODULEPOLICY': 'py',
170 'HGRCPATH': '',
173 'HGRCPATH': '',
171 'LANGUAGE': 'C',
174 'LANGUAGE': 'C',
172 'PATH': ''} # make pypi modules that use os.environ['PATH'] happy
175 'PATH': ''} # make pypi modules that use os.environ['PATH'] happy
173 if 'LD_LIBRARY_PATH' in os.environ:
176 if 'LD_LIBRARY_PATH' in os.environ:
174 env['LD_LIBRARY_PATH'] = os.environ['LD_LIBRARY_PATH']
177 env['LD_LIBRARY_PATH'] = os.environ['LD_LIBRARY_PATH']
175 if 'SystemRoot' in os.environ:
178 if 'SystemRoot' in os.environ:
176 # Copy SystemRoot into the custom environment for Python 2.6
179 # Copy SystemRoot into the custom environment for Python 2.6
177 # under Windows. Otherwise, the subprocess will fail with
180 # under Windows. Otherwise, the subprocess will fail with
178 # error 0xc0150004. See: http://bugs.python.org/issue3440
181 # error 0xc0150004. See: http://bugs.python.org/issue3440
179 env['SystemRoot'] = os.environ['SystemRoot']
182 env['SystemRoot'] = os.environ['SystemRoot']
180
183
181 if os.path.isdir('.hg'):
184 if os.path.isdir('.hg'):
182 cmd = [sys.executable, 'hg', 'log', '-r', '.', '--template', '{tags}\n']
185 cmd = [sys.executable, 'hg', 'log', '-r', '.', '--template', '{tags}\n']
183 numerictags = [t for t in runhg(cmd, env).split() if t[0].isdigit()]
186 numerictags = [t for t in runhg(cmd, env).split() if t[0].isdigit()]
184 hgid = runhg([sys.executable, 'hg', 'id', '-i'], env).strip()
187 hgid = runhg([sys.executable, 'hg', 'id', '-i'], env).strip()
185 if numerictags: # tag(s) found
188 if numerictags: # tag(s) found
186 version = numerictags[-1]
189 version = numerictags[-1]
187 if hgid.endswith('+'): # propagate the dirty status to the tag
190 if hgid.endswith('+'): # propagate the dirty status to the tag
188 version += '+'
191 version += '+'
189 else: # no tag found
192 else: # no tag found
190 ltagcmd = [sys.executable, 'hg', 'parents', '--template',
193 ltagcmd = [sys.executable, 'hg', 'parents', '--template',
191 '{latesttag}']
194 '{latesttag}']
192 ltag = runhg(ltagcmd, env)
195 ltag = runhg(ltagcmd, env)
193 changessincecmd = [sys.executable, 'hg', 'log', '-T', 'x\n', '-r',
196 changessincecmd = [sys.executable, 'hg', 'log', '-T', 'x\n', '-r',
194 "only(.,'%s')" % ltag]
197 "only(.,'%s')" % ltag]
195 changessince = len(runhg(changessincecmd, env).splitlines())
198 changessince = len(runhg(changessincecmd, env).splitlines())
196 version = '%s+%s-%s' % (ltag, changessince, hgid)
199 version = '%s+%s-%s' % (ltag, changessince, hgid)
197 if version.endswith('+'):
200 if version.endswith('+'):
198 version += time.strftime('%Y%m%d')
201 version += time.strftime('%Y%m%d')
199 elif os.path.exists('.hg_archival.txt'):
202 elif os.path.exists('.hg_archival.txt'):
200 kw = dict([[t.strip() for t in l.split(':', 1)]
203 kw = dict([[t.strip() for t in l.split(':', 1)]
201 for l in open('.hg_archival.txt')])
204 for l in open('.hg_archival.txt')])
202 if 'tag' in kw:
205 if 'tag' in kw:
203 version = kw['tag']
206 version = kw['tag']
204 elif 'latesttag' in kw:
207 elif 'latesttag' in kw:
205 if 'changessincelatesttag' in kw:
208 if 'changessincelatesttag' in kw:
206 version = '%(latesttag)s+%(changessincelatesttag)s-%(node).12s' % kw
209 version = '%(latesttag)s+%(changessincelatesttag)s-%(node).12s' % kw
207 else:
210 else:
208 version = '%(latesttag)s+%(latesttagdistance)s-%(node).12s' % kw
211 version = '%(latesttag)s+%(latesttagdistance)s-%(node).12s' % kw
209 else:
212 else:
210 version = kw.get('node', '')[:12]
213 version = kw.get('node', '')[:12]
211
214
212 if version:
215 if version:
213 with open("mercurial/__version__.py", "w") as f:
216 with open("mercurial/__version__.py", "w") as f:
214 f.write('# this file is autogenerated by setup.py\n')
217 f.write('# this file is autogenerated by setup.py\n')
215 f.write('version = "%s"\n' % version)
218 f.write('version = "%s"\n' % version)
216
219
217 try:
220 try:
218 oldpolicy = os.environ.get('HGMODULEPOLICY', None)
221 oldpolicy = os.environ.get('HGMODULEPOLICY', None)
219 os.environ['HGMODULEPOLICY'] = 'py'
222 os.environ['HGMODULEPOLICY'] = 'py'
220 from mercurial import __version__
223 from mercurial import __version__
221 version = __version__.version
224 version = __version__.version
222 except ImportError:
225 except ImportError:
223 version = 'unknown'
226 version = 'unknown'
224 finally:
227 finally:
225 if oldpolicy is None:
228 if oldpolicy is None:
226 del os.environ['HGMODULEPOLICY']
229 del os.environ['HGMODULEPOLICY']
227 else:
230 else:
228 os.environ['HGMODULEPOLICY'] = oldpolicy
231 os.environ['HGMODULEPOLICY'] = oldpolicy
229
232
230 class hgbuild(build):
233 class hgbuild(build):
231 # Insert hgbuildmo first so that files in mercurial/locale/ are found
234 # Insert hgbuildmo first so that files in mercurial/locale/ are found
232 # when build_py is run next.
235 # when build_py is run next.
233 sub_commands = [('build_mo', None)] + build.sub_commands
236 sub_commands = [('build_mo', None)] + build.sub_commands
234
237
235 class hgbuildmo(build):
238 class hgbuildmo(build):
236
239
237 description = "build translations (.mo files)"
240 description = "build translations (.mo files)"
238
241
239 def run(self):
242 def run(self):
240 if not find_executable('msgfmt'):
243 if not find_executable('msgfmt'):
241 self.warn("could not find msgfmt executable, no translations "
244 self.warn("could not find msgfmt executable, no translations "
242 "will be built")
245 "will be built")
243 return
246 return
244
247
245 podir = 'i18n'
248 podir = 'i18n'
246 if not os.path.isdir(podir):
249 if not os.path.isdir(podir):
247 self.warn("could not find %s/ directory" % podir)
250 self.warn("could not find %s/ directory" % podir)
248 return
251 return
249
252
250 join = os.path.join
253 join = os.path.join
251 for po in os.listdir(podir):
254 for po in os.listdir(podir):
252 if not po.endswith('.po'):
255 if not po.endswith('.po'):
253 continue
256 continue
254 pofile = join(podir, po)
257 pofile = join(podir, po)
255 modir = join('locale', po[:-3], 'LC_MESSAGES')
258 modir = join('locale', po[:-3], 'LC_MESSAGES')
256 mofile = join(modir, 'hg.mo')
259 mofile = join(modir, 'hg.mo')
257 mobuildfile = join('mercurial', mofile)
260 mobuildfile = join('mercurial', mofile)
258 cmd = ['msgfmt', '-v', '-o', mobuildfile, pofile]
261 cmd = ['msgfmt', '-v', '-o', mobuildfile, pofile]
259 if sys.platform != 'sunos5':
262 if sys.platform != 'sunos5':
260 # msgfmt on Solaris does not know about -c
263 # msgfmt on Solaris does not know about -c
261 cmd.append('-c')
264 cmd.append('-c')
262 self.mkpath(join('mercurial', modir))
265 self.mkpath(join('mercurial', modir))
263 self.make_file([pofile], mobuildfile, spawn, (cmd,))
266 self.make_file([pofile], mobuildfile, spawn, (cmd,))
264
267
265
268
266 class hgdist(Distribution):
269 class hgdist(Distribution):
267 pure = False
270 pure = False
268 cffi = ispypy
271 cffi = ispypy
269
272
270 global_options = Distribution.global_options + \
273 global_options = Distribution.global_options + \
271 [('pure', None, "use pure (slow) Python "
274 [('pure', None, "use pure (slow) Python "
272 "code instead of C extensions"),
275 "code instead of C extensions"),
273 ]
276 ]
274
277
275 def has_ext_modules(self):
278 def has_ext_modules(self):
276 # self.ext_modules is emptied in hgbuildpy.finalize_options which is
279 # self.ext_modules is emptied in hgbuildpy.finalize_options which is
277 # too late for some cases
280 # too late for some cases
278 return not self.pure and Distribution.has_ext_modules(self)
281 return not self.pure and Distribution.has_ext_modules(self)
279
282
280 # This is ugly as a one-liner. So use a variable.
283 # This is ugly as a one-liner. So use a variable.
281 buildextnegops = dict(getattr(build_ext, 'negative_options', {}))
284 buildextnegops = dict(getattr(build_ext, 'negative_options', {}))
282 buildextnegops['no-zstd'] = 'zstd'
285 buildextnegops['no-zstd'] = 'zstd'
283
286
284 class hgbuildext(build_ext):
287 class hgbuildext(build_ext):
285 user_options = build_ext.user_options + [
288 user_options = build_ext.user_options + [
286 ('zstd', None, 'compile zstd bindings [default]'),
289 ('zstd', None, 'compile zstd bindings [default]'),
287 ('no-zstd', None, 'do not compile zstd bindings'),
290 ('no-zstd', None, 'do not compile zstd bindings'),
288 ]
291 ]
289
292
290 boolean_options = build_ext.boolean_options + ['zstd']
293 boolean_options = build_ext.boolean_options + ['zstd']
291 negative_opt = buildextnegops
294 negative_opt = buildextnegops
292
295
293 def initialize_options(self):
296 def initialize_options(self):
294 self.zstd = True
297 self.zstd = True
295 return build_ext.initialize_options(self)
298 return build_ext.initialize_options(self)
296
299
297 def build_extensions(self):
300 def build_extensions(self):
298 # Filter out zstd if disabled via argument.
301 # Filter out zstd if disabled via argument.
299 if not self.zstd:
302 if not self.zstd:
300 self.extensions = [e for e in self.extensions
303 self.extensions = [e for e in self.extensions
301 if e.name != 'mercurial.zstd']
304 if e.name != 'mercurial.zstd']
302
305
303 return build_ext.build_extensions(self)
306 return build_ext.build_extensions(self)
304
307
305 def build_extension(self, ext):
308 def build_extension(self, ext):
306 try:
309 try:
307 build_ext.build_extension(self, ext)
310 build_ext.build_extension(self, ext)
308 except CCompilerError:
311 except CCompilerError:
309 if not getattr(ext, 'optional', False):
312 if not getattr(ext, 'optional', False):
310 raise
313 raise
311 log.warn("Failed to build optional extension '%s' (skipping)",
314 log.warn("Failed to build optional extension '%s' (skipping)",
312 ext.name)
315 ext.name)
313
316
314 class hgbuildscripts(build_scripts):
317 class hgbuildscripts(build_scripts):
315 def run(self):
318 def run(self):
316 if os.name != 'nt' or self.distribution.pure:
319 if os.name != 'nt' or self.distribution.pure:
317 return build_scripts.run(self)
320 return build_scripts.run(self)
318
321
319 exebuilt = False
322 exebuilt = False
320 try:
323 try:
321 self.run_command('build_hgexe')
324 self.run_command('build_hgexe')
322 exebuilt = True
325 exebuilt = True
323 except (DistutilsError, CCompilerError):
326 except (DistutilsError, CCompilerError):
324 log.warn('failed to build optional hg.exe')
327 log.warn('failed to build optional hg.exe')
325
328
326 if exebuilt:
329 if exebuilt:
327 # Copying hg.exe to the scripts build directory ensures it is
330 # Copying hg.exe to the scripts build directory ensures it is
328 # installed by the install_scripts command.
331 # installed by the install_scripts command.
329 hgexecommand = self.get_finalized_command('build_hgexe')
332 hgexecommand = self.get_finalized_command('build_hgexe')
330 dest = os.path.join(self.build_dir, 'hg.exe')
333 dest = os.path.join(self.build_dir, 'hg.exe')
331 self.mkpath(self.build_dir)
334 self.mkpath(self.build_dir)
332 self.copy_file(hgexecommand.hgexepath, dest)
335 self.copy_file(hgexecommand.hgexepath, dest)
333
336
334 # Remove hg.bat because it is redundant with hg.exe.
337 # Remove hg.bat because it is redundant with hg.exe.
335 self.scripts.remove('contrib/win32/hg.bat')
338 self.scripts.remove('contrib/win32/hg.bat')
336
339
337 return build_scripts.run(self)
340 return build_scripts.run(self)
338
341
339 class hgbuildpy(build_py):
342 class hgbuildpy(build_py):
340 def finalize_options(self):
343 def finalize_options(self):
341 build_py.finalize_options(self)
344 build_py.finalize_options(self)
342
345
343 if self.distribution.pure:
346 if self.distribution.pure:
344 self.distribution.ext_modules = []
347 self.distribution.ext_modules = []
345 elif self.distribution.cffi:
348 elif self.distribution.cffi:
346 from mercurial.cffi import (
349 from mercurial.cffi import (
347 bdiff,
350 bdiff,
348 mpatch,
351 mpatch,
349 )
352 )
350 exts = [mpatch.ffi.distutils_extension(),
353 exts = [mpatch.ffi.distutils_extension(),
351 bdiff.ffi.distutils_extension()]
354 bdiff.ffi.distutils_extension()]
352 # cffi modules go here
355 # cffi modules go here
353 if sys.platform == 'darwin':
356 if sys.platform == 'darwin':
354 from mercurial.cffi import osutil
357 from mercurial.cffi import osutil
355 exts.append(osutil.ffi.distutils_extension())
358 exts.append(osutil.ffi.distutils_extension())
356 self.distribution.ext_modules = exts
359 self.distribution.ext_modules = exts
357 else:
360 else:
358 h = os.path.join(get_python_inc(), 'Python.h')
361 h = os.path.join(get_python_inc(), 'Python.h')
359 if not os.path.exists(h):
362 if not os.path.exists(h):
360 raise SystemExit('Python headers are required to build '
363 raise SystemExit('Python headers are required to build '
361 'Mercurial but weren\'t found in %s' % h)
364 'Mercurial but weren\'t found in %s' % h)
362
365
363 def run(self):
366 def run(self):
364 if self.distribution.pure:
367 if self.distribution.pure:
365 modulepolicy = 'py'
368 modulepolicy = 'py'
366 else:
369 else:
367 modulepolicy = 'c'
370 modulepolicy = 'c'
368 with open("mercurial/__modulepolicy__.py", "w") as f:
371 with open("mercurial/__modulepolicy__.py", "w") as f:
369 f.write('# this file is autogenerated by setup.py\n')
372 f.write('# this file is autogenerated by setup.py\n')
370 f.write('modulepolicy = "%s"\n' % modulepolicy)
373 f.write('modulepolicy = "%s"\n' % modulepolicy)
371
374
372 build_py.run(self)
375 build_py.run(self)
373
376
374 class buildhgextindex(Command):
377 class buildhgextindex(Command):
375 description = 'generate prebuilt index of hgext (for frozen package)'
378 description = 'generate prebuilt index of hgext (for frozen package)'
376 user_options = []
379 user_options = []
377 _indexfilename = 'hgext/__index__.py'
380 _indexfilename = 'hgext/__index__.py'
378
381
379 def initialize_options(self):
382 def initialize_options(self):
380 pass
383 pass
381
384
382 def finalize_options(self):
385 def finalize_options(self):
383 pass
386 pass
384
387
385 def run(self):
388 def run(self):
386 if os.path.exists(self._indexfilename):
389 if os.path.exists(self._indexfilename):
387 with open(self._indexfilename, 'w') as f:
390 with open(self._indexfilename, 'w') as f:
388 f.write('# empty\n')
391 f.write('# empty\n')
389
392
390 # here no extension enabled, disabled() lists up everything
393 # here no extension enabled, disabled() lists up everything
391 code = ('import pprint; from mercurial import extensions; '
394 code = ('import pprint; from mercurial import extensions; '
392 'pprint.pprint(extensions.disabled())')
395 'pprint.pprint(extensions.disabled())')
393 out, err = runcmd([sys.executable, '-c', code], env)
396 out, err = runcmd([sys.executable, '-c', code], env)
394 if err:
397 if err:
395 raise DistutilsExecError(err)
398 raise DistutilsExecError(err)
396
399
397 with open(self._indexfilename, 'w') as f:
400 with open(self._indexfilename, 'w') as f:
398 f.write('# this file is autogenerated by setup.py\n')
401 f.write('# this file is autogenerated by setup.py\n')
399 f.write('docs = ')
402 f.write('docs = ')
400 f.write(out)
403 f.write(out)
401
404
402 class buildhgexe(build_ext):
405 class buildhgexe(build_ext):
403 description = 'compile hg.exe from mercurial/exewrapper.c'
406 description = 'compile hg.exe from mercurial/exewrapper.c'
404
407
405 def build_extensions(self):
408 def build_extensions(self):
406 if os.name != 'nt':
409 if os.name != 'nt':
407 return
410 return
408 if isinstance(self.compiler, HackedMingw32CCompiler):
411 if isinstance(self.compiler, HackedMingw32CCompiler):
409 self.compiler.compiler_so = self.compiler.compiler # no -mdll
412 self.compiler.compiler_so = self.compiler.compiler # no -mdll
410 self.compiler.dll_libraries = [] # no -lmsrvc90
413 self.compiler.dll_libraries = [] # no -lmsrvc90
411
414
412 # Different Python installs can have different Python library
415 # Different Python installs can have different Python library
413 # names. e.g. the official CPython distribution uses pythonXY.dll
416 # names. e.g. the official CPython distribution uses pythonXY.dll
414 # and MinGW uses libpythonX.Y.dll.
417 # and MinGW uses libpythonX.Y.dll.
415 _kernel32 = ctypes.windll.kernel32
418 _kernel32 = ctypes.windll.kernel32
416 _kernel32.GetModuleFileNameA.argtypes = [ctypes.c_void_p,
419 _kernel32.GetModuleFileNameA.argtypes = [ctypes.c_void_p,
417 ctypes.c_void_p,
420 ctypes.c_void_p,
418 ctypes.c_ulong]
421 ctypes.c_ulong]
419 _kernel32.GetModuleFileNameA.restype = ctypes.c_ulong
422 _kernel32.GetModuleFileNameA.restype = ctypes.c_ulong
420 size = 1000
423 size = 1000
421 buf = ctypes.create_string_buffer(size + 1)
424 buf = ctypes.create_string_buffer(size + 1)
422 filelen = _kernel32.GetModuleFileNameA(sys.dllhandle, ctypes.byref(buf),
425 filelen = _kernel32.GetModuleFileNameA(sys.dllhandle, ctypes.byref(buf),
423 size)
426 size)
424
427
425 if filelen > 0 and filelen != size:
428 if filelen > 0 and filelen != size:
426 dllbasename = os.path.basename(buf.value)
429 dllbasename = os.path.basename(buf.value)
427 if not dllbasename.lower().endswith('.dll'):
430 if not dllbasename.lower().endswith('.dll'):
428 raise SystemExit('Python DLL does not end with .dll: %s' %
431 raise SystemExit('Python DLL does not end with .dll: %s' %
429 dllbasename)
432 dllbasename)
430 pythonlib = dllbasename[:-4]
433 pythonlib = dllbasename[:-4]
431 else:
434 else:
432 log.warn('could not determine Python DLL filename; '
435 log.warn('could not determine Python DLL filename; '
433 'assuming pythonXY')
436 'assuming pythonXY')
434
437
435 hv = sys.hexversion
438 hv = sys.hexversion
436 pythonlib = 'python%d%d' % (hv >> 24, (hv >> 16) & 0xff)
439 pythonlib = 'python%d%d' % (hv >> 24, (hv >> 16) & 0xff)
437
440
438 log.info('using %s as Python library name' % pythonlib)
441 log.info('using %s as Python library name' % pythonlib)
439 with open('mercurial/hgpythonlib.h', 'wb') as f:
442 with open('mercurial/hgpythonlib.h', 'wb') as f:
440 f.write('/* this file is autogenerated by setup.py */\n')
443 f.write('/* this file is autogenerated by setup.py */\n')
441 f.write('#define HGPYTHONLIB "%s"\n' % pythonlib)
444 f.write('#define HGPYTHONLIB "%s"\n' % pythonlib)
442 objects = self.compiler.compile(['mercurial/exewrapper.c'],
445 objects = self.compiler.compile(['mercurial/exewrapper.c'],
443 output_dir=self.build_temp)
446 output_dir=self.build_temp)
444 dir = os.path.dirname(self.get_ext_fullpath('dummy'))
447 dir = os.path.dirname(self.get_ext_fullpath('dummy'))
445 target = os.path.join(dir, 'hg')
448 target = os.path.join(dir, 'hg')
446 self.compiler.link_executable(objects, target,
449 self.compiler.link_executable(objects, target,
447 libraries=[],
450 libraries=[],
448 output_dir=self.build_temp)
451 output_dir=self.build_temp)
449
452
450 @property
453 @property
451 def hgexepath(self):
454 def hgexepath(self):
452 dir = os.path.dirname(self.get_ext_fullpath('dummy'))
455 dir = os.path.dirname(self.get_ext_fullpath('dummy'))
453 return os.path.join(self.build_temp, dir, 'hg.exe')
456 return os.path.join(self.build_temp, dir, 'hg.exe')
454
457
455 class hginstalllib(install_lib):
458 class hginstalllib(install_lib):
456 '''
459 '''
457 This is a specialization of install_lib that replaces the copy_file used
460 This is a specialization of install_lib that replaces the copy_file used
458 there so that it supports setting the mode of files after copying them,
461 there so that it supports setting the mode of files after copying them,
459 instead of just preserving the mode that the files originally had. If your
462 instead of just preserving the mode that the files originally had. If your
460 system has a umask of something like 027, preserving the permissions when
463 system has a umask of something like 027, preserving the permissions when
461 copying will lead to a broken install.
464 copying will lead to a broken install.
462
465
463 Note that just passing keep_permissions=False to copy_file would be
466 Note that just passing keep_permissions=False to copy_file would be
464 insufficient, as it might still be applying a umask.
467 insufficient, as it might still be applying a umask.
465 '''
468 '''
466
469
467 def run(self):
470 def run(self):
468 realcopyfile = file_util.copy_file
471 realcopyfile = file_util.copy_file
469 def copyfileandsetmode(*args, **kwargs):
472 def copyfileandsetmode(*args, **kwargs):
470 src, dst = args[0], args[1]
473 src, dst = args[0], args[1]
471 dst, copied = realcopyfile(*args, **kwargs)
474 dst, copied = realcopyfile(*args, **kwargs)
472 if copied:
475 if copied:
473 st = os.stat(src)
476 st = os.stat(src)
474 # Persist executable bit (apply it to group and other if user
477 # Persist executable bit (apply it to group and other if user
475 # has it)
478 # has it)
476 if st[stat.ST_MODE] & stat.S_IXUSR:
479 if st[stat.ST_MODE] & stat.S_IXUSR:
477 setmode = int('0755', 8)
480 setmode = int('0755', 8)
478 else:
481 else:
479 setmode = int('0644', 8)
482 setmode = int('0644', 8)
480 m = stat.S_IMODE(st[stat.ST_MODE])
483 m = stat.S_IMODE(st[stat.ST_MODE])
481 m = (m & ~int('0777', 8)) | setmode
484 m = (m & ~int('0777', 8)) | setmode
482 os.chmod(dst, m)
485 os.chmod(dst, m)
483 file_util.copy_file = copyfileandsetmode
486 file_util.copy_file = copyfileandsetmode
484 try:
487 try:
485 install_lib.run(self)
488 install_lib.run(self)
486 finally:
489 finally:
487 file_util.copy_file = realcopyfile
490 file_util.copy_file = realcopyfile
488
491
489 class hginstallscripts(install_scripts):
492 class hginstallscripts(install_scripts):
490 '''
493 '''
491 This is a specialization of install_scripts that replaces the @LIBDIR@ with
494 This is a specialization of install_scripts that replaces the @LIBDIR@ with
492 the configured directory for modules. If possible, the path is made relative
495 the configured directory for modules. If possible, the path is made relative
493 to the directory for scripts.
496 to the directory for scripts.
494 '''
497 '''
495
498
496 def initialize_options(self):
499 def initialize_options(self):
497 install_scripts.initialize_options(self)
500 install_scripts.initialize_options(self)
498
501
499 self.install_lib = None
502 self.install_lib = None
500
503
501 def finalize_options(self):
504 def finalize_options(self):
502 install_scripts.finalize_options(self)
505 install_scripts.finalize_options(self)
503 self.set_undefined_options('install',
506 self.set_undefined_options('install',
504 ('install_lib', 'install_lib'))
507 ('install_lib', 'install_lib'))
505
508
506 def run(self):
509 def run(self):
507 install_scripts.run(self)
510 install_scripts.run(self)
508
511
509 # It only makes sense to replace @LIBDIR@ with the install path if
512 # It only makes sense to replace @LIBDIR@ with the install path if
510 # the install path is known. For wheels, the logic below calculates
513 # the install path is known. For wheels, the logic below calculates
511 # the libdir to be "../..". This is because the internal layout of a
514 # the libdir to be "../..". This is because the internal layout of a
512 # wheel archive looks like:
515 # wheel archive looks like:
513 #
516 #
514 # mercurial-3.6.1.data/scripts/hg
517 # mercurial-3.6.1.data/scripts/hg
515 # mercurial/__init__.py
518 # mercurial/__init__.py
516 #
519 #
517 # When installing wheels, the subdirectories of the "<pkg>.data"
520 # When installing wheels, the subdirectories of the "<pkg>.data"
518 # directory are translated to system local paths and files therein
521 # directory are translated to system local paths and files therein
519 # are copied in place. The mercurial/* files are installed into the
522 # are copied in place. The mercurial/* files are installed into the
520 # site-packages directory. However, the site-packages directory
523 # site-packages directory. However, the site-packages directory
521 # isn't known until wheel install time. This means we have no clue
524 # isn't known until wheel install time. This means we have no clue
522 # at wheel generation time what the installed site-packages directory
525 # at wheel generation time what the installed site-packages directory
523 # will be. And, wheels don't appear to provide the ability to register
526 # will be. And, wheels don't appear to provide the ability to register
524 # custom code to run during wheel installation. This all means that
527 # custom code to run during wheel installation. This all means that
525 # we can't reliably set the libdir in wheels: the default behavior
528 # we can't reliably set the libdir in wheels: the default behavior
526 # of looking in sys.path must do.
529 # of looking in sys.path must do.
527
530
528 if (os.path.splitdrive(self.install_dir)[0] !=
531 if (os.path.splitdrive(self.install_dir)[0] !=
529 os.path.splitdrive(self.install_lib)[0]):
532 os.path.splitdrive(self.install_lib)[0]):
530 # can't make relative paths from one drive to another, so use an
533 # can't make relative paths from one drive to another, so use an
531 # absolute path instead
534 # absolute path instead
532 libdir = self.install_lib
535 libdir = self.install_lib
533 else:
536 else:
534 common = os.path.commonprefix((self.install_dir, self.install_lib))
537 common = os.path.commonprefix((self.install_dir, self.install_lib))
535 rest = self.install_dir[len(common):]
538 rest = self.install_dir[len(common):]
536 uplevel = len([n for n in os.path.split(rest) if n])
539 uplevel = len([n for n in os.path.split(rest) if n])
537
540
538 libdir = uplevel * ('..' + os.sep) + self.install_lib[len(common):]
541 libdir = uplevel * ('..' + os.sep) + self.install_lib[len(common):]
539
542
540 for outfile in self.outfiles:
543 for outfile in self.outfiles:
541 with open(outfile, 'rb') as fp:
544 with open(outfile, 'rb') as fp:
542 data = fp.read()
545 data = fp.read()
543
546
544 # skip binary files
547 # skip binary files
545 if b'\0' in data:
548 if b'\0' in data:
546 continue
549 continue
547
550
548 # During local installs, the shebang will be rewritten to the final
551 # During local installs, the shebang will be rewritten to the final
549 # install path. During wheel packaging, the shebang has a special
552 # install path. During wheel packaging, the shebang has a special
550 # value.
553 # value.
551 if data.startswith(b'#!python'):
554 if data.startswith(b'#!python'):
552 log.info('not rewriting @LIBDIR@ in %s because install path '
555 log.info('not rewriting @LIBDIR@ in %s because install path '
553 'not known' % outfile)
556 'not known' % outfile)
554 continue
557 continue
555
558
556 data = data.replace(b'@LIBDIR@', libdir.encode(libdir_escape))
559 data = data.replace(b'@LIBDIR@', libdir.encode(libdir_escape))
557 with open(outfile, 'wb') as fp:
560 with open(outfile, 'wb') as fp:
558 fp.write(data)
561 fp.write(data)
559
562
560 cmdclass = {'build': hgbuild,
563 cmdclass = {'build': hgbuild,
561 'build_mo': hgbuildmo,
564 'build_mo': hgbuildmo,
562 'build_ext': hgbuildext,
565 'build_ext': hgbuildext,
563 'build_py': hgbuildpy,
566 'build_py': hgbuildpy,
564 'build_scripts': hgbuildscripts,
567 'build_scripts': hgbuildscripts,
565 'build_hgextindex': buildhgextindex,
568 'build_hgextindex': buildhgextindex,
566 'install_lib': hginstalllib,
569 'install_lib': hginstalllib,
567 'install_scripts': hginstallscripts,
570 'install_scripts': hginstallscripts,
568 'build_hgexe': buildhgexe,
571 'build_hgexe': buildhgexe,
569 }
572 }
570
573
571 packages = ['mercurial', 'mercurial.hgweb', 'mercurial.httpclient',
574 packages = ['mercurial', 'mercurial.hgweb', 'mercurial.httpclient',
572 'mercurial.pure',
575 'mercurial.pure',
573 'hgext', 'hgext.convert', 'hgext.fsmonitor',
576 'hgext', 'hgext.convert', 'hgext.fsmonitor',
574 'hgext.fsmonitor.pywatchman', 'hgext.highlight',
577 'hgext.fsmonitor.pywatchman', 'hgext.highlight',
575 'hgext.largefiles', 'hgext.zeroconf', 'hgext3rd']
578 'hgext.largefiles', 'hgext.zeroconf', 'hgext3rd']
576
579
577 common_depends = ['mercurial/bitmanipulation.h',
580 common_depends = ['mercurial/bitmanipulation.h',
578 'mercurial/compat.h',
581 'mercurial/compat.h',
579 'mercurial/util.h']
582 'mercurial/util.h']
580
583
581 osutil_cflags = []
584 osutil_cflags = []
582 osutil_ldflags = []
585 osutil_ldflags = []
583
586
584 # platform specific macros: HAVE_SETPROCTITLE
587 # platform specific macros: HAVE_SETPROCTITLE
585 for plat, func in [(re.compile('freebsd'), 'setproctitle')]:
588 for plat, func in [(re.compile('freebsd'), 'setproctitle')]:
586 if plat.search(sys.platform) and hasfunction(new_compiler(), func):
589 if plat.search(sys.platform) and hasfunction(new_compiler(), func):
587 osutil_cflags.append('-DHAVE_%s' % func.upper())
590 osutil_cflags.append('-DHAVE_%s' % func.upper())
588
591
589 if sys.platform == 'darwin':
592 if sys.platform == 'darwin':
590 osutil_ldflags += ['-framework', 'ApplicationServices']
593 osutil_ldflags += ['-framework', 'ApplicationServices']
591
594
592 extmodules = [
595 extmodules = [
593 Extension('mercurial.base85', ['mercurial/base85.c'],
596 Extension('mercurial.base85', ['mercurial/base85.c'],
594 depends=common_depends),
597 depends=common_depends),
595 Extension('mercurial.bdiff', ['mercurial/bdiff.c',
598 Extension('mercurial.bdiff', ['mercurial/bdiff.c',
596 'mercurial/bdiff_module.c'],
599 'mercurial/bdiff_module.c'],
597 depends=common_depends + ['mercurial/bdiff.h']),
600 depends=common_depends + ['mercurial/bdiff.h']),
598 Extension('mercurial.diffhelpers', ['mercurial/diffhelpers.c'],
601 Extension('mercurial.diffhelpers', ['mercurial/diffhelpers.c'],
599 depends=common_depends),
602 depends=common_depends),
600 Extension('mercurial.mpatch', ['mercurial/mpatch.c',
603 Extension('mercurial.mpatch', ['mercurial/mpatch.c',
601 'mercurial/mpatch_module.c'],
604 'mercurial/mpatch_module.c'],
602 depends=common_depends),
605 depends=common_depends),
603 Extension('mercurial.parsers', ['mercurial/dirs.c',
606 Extension('mercurial.parsers', ['mercurial/dirs.c',
604 'mercurial/manifest.c',
607 'mercurial/manifest.c',
605 'mercurial/parsers.c',
608 'mercurial/parsers.c',
606 'mercurial/pathencode.c'],
609 'mercurial/pathencode.c'],
607 depends=common_depends),
610 depends=common_depends),
608 Extension('mercurial.osutil', ['mercurial/osutil.c'],
611 Extension('mercurial.osutil', ['mercurial/osutil.c'],
609 extra_compile_args=osutil_cflags,
612 extra_compile_args=osutil_cflags,
610 extra_link_args=osutil_ldflags,
613 extra_link_args=osutil_ldflags,
611 depends=common_depends),
614 depends=common_depends),
612 Extension('hgext.fsmonitor.pywatchman.bser',
615 Extension('hgext.fsmonitor.pywatchman.bser',
613 ['hgext/fsmonitor/pywatchman/bser.c']),
616 ['hgext/fsmonitor/pywatchman/bser.c']),
614 ]
617 ]
615
618
616 sys.path.insert(0, 'contrib/python-zstandard')
619 sys.path.insert(0, 'contrib/python-zstandard')
617 import setup_zstd
620 import setup_zstd
618 extmodules.append(setup_zstd.get_c_extension(name='mercurial.zstd'))
621 extmodules.append(setup_zstd.get_c_extension(name='mercurial.zstd'))
619
622
620 try:
623 try:
621 from distutils import cygwinccompiler
624 from distutils import cygwinccompiler
622
625
623 # the -mno-cygwin option has been deprecated for years
626 # the -mno-cygwin option has been deprecated for years
624 compiler = cygwinccompiler.Mingw32CCompiler
627 compiler = cygwinccompiler.Mingw32CCompiler
625
628
626 class HackedMingw32CCompiler(cygwinccompiler.Mingw32CCompiler):
629 class HackedMingw32CCompiler(cygwinccompiler.Mingw32CCompiler):
627 def __init__(self, *args, **kwargs):
630 def __init__(self, *args, **kwargs):
628 compiler.__init__(self, *args, **kwargs)
631 compiler.__init__(self, *args, **kwargs)
629 for i in 'compiler compiler_so linker_exe linker_so'.split():
632 for i in 'compiler compiler_so linker_exe linker_so'.split():
630 try:
633 try:
631 getattr(self, i).remove('-mno-cygwin')
634 getattr(self, i).remove('-mno-cygwin')
632 except ValueError:
635 except ValueError:
633 pass
636 pass
634
637
635 cygwinccompiler.Mingw32CCompiler = HackedMingw32CCompiler
638 cygwinccompiler.Mingw32CCompiler = HackedMingw32CCompiler
636 except ImportError:
639 except ImportError:
637 # the cygwinccompiler package is not available on some Python
640 # the cygwinccompiler package is not available on some Python
638 # distributions like the ones from the optware project for Synology
641 # distributions like the ones from the optware project for Synology
639 # DiskStation boxes
642 # DiskStation boxes
640 class HackedMingw32CCompiler(object):
643 class HackedMingw32CCompiler(object):
641 pass
644 pass
642
645
643 packagedata = {'mercurial': ['locale/*/LC_MESSAGES/hg.mo',
646 packagedata = {'mercurial': ['locale/*/LC_MESSAGES/hg.mo',
644 'help/*.txt',
647 'help/*.txt',
645 'help/internals/*.txt',
648 'help/internals/*.txt',
646 'default.d/*.rc',
649 'default.d/*.rc',
647 'dummycert.pem']}
650 'dummycert.pem']}
648
651
649 def ordinarypath(p):
652 def ordinarypath(p):
650 return p and p[0] != '.' and p[-1] != '~'
653 return p and p[0] != '.' and p[-1] != '~'
651
654
652 for root in ('templates',):
655 for root in ('templates',):
653 for curdir, dirs, files in os.walk(os.path.join('mercurial', root)):
656 for curdir, dirs, files in os.walk(os.path.join('mercurial', root)):
654 curdir = curdir.split(os.sep, 1)[1]
657 curdir = curdir.split(os.sep, 1)[1]
655 dirs[:] = filter(ordinarypath, dirs)
658 dirs[:] = filter(ordinarypath, dirs)
656 for f in filter(ordinarypath, files):
659 for f in filter(ordinarypath, files):
657 f = os.path.join(curdir, f)
660 f = os.path.join(curdir, f)
658 packagedata['mercurial'].append(f)
661 packagedata['mercurial'].append(f)
659
662
660 datafiles = []
663 datafiles = []
661 setupversion = version
664 setupversion = version
662 extra = {}
665 extra = {}
663
666
664 if py2exeloaded:
667 if py2exeloaded:
665 extra['console'] = [
668 extra['console'] = [
666 {'script':'hg',
669 {'script':'hg',
667 'copyright':'Copyright (C) 2005-2017 Matt Mackall and others',
670 'copyright':'Copyright (C) 2005-2017 Matt Mackall and others',
668 'product_version':version}]
671 'product_version':version}]
669 # sub command of 'build' because 'py2exe' does not handle sub_commands
672 # sub command of 'build' because 'py2exe' does not handle sub_commands
670 build.sub_commands.insert(0, ('build_hgextindex', None))
673 build.sub_commands.insert(0, ('build_hgextindex', None))
671 # put dlls in sub directory so that they won't pollute PATH
674 # put dlls in sub directory so that they won't pollute PATH
672 extra['zipfile'] = 'lib/library.zip'
675 extra['zipfile'] = 'lib/library.zip'
673
676
674 if os.name == 'nt':
677 if os.name == 'nt':
675 # Windows binary file versions for exe/dll files must have the
678 # Windows binary file versions for exe/dll files must have the
676 # form W.X.Y.Z, where W,X,Y,Z are numbers in the range 0..65535
679 # form W.X.Y.Z, where W,X,Y,Z are numbers in the range 0..65535
677 setupversion = version.split('+', 1)[0]
680 setupversion = version.split('+', 1)[0]
678
681
679 if sys.platform == 'darwin' and os.path.exists('/usr/bin/xcodebuild'):
682 if sys.platform == 'darwin' and os.path.exists('/usr/bin/xcodebuild'):
680 version = runcmd(['/usr/bin/xcodebuild', '-version'], {})[0].splitlines()
683 version = runcmd(['/usr/bin/xcodebuild', '-version'], {})[0].splitlines()
681 if version:
684 if version:
682 version = version[0]
685 version = version[0]
683 if sys.version_info[0] == 3:
686 if sys.version_info[0] == 3:
684 version = version.decode('utf-8')
687 version = version.decode('utf-8')
685 xcode4 = (version.startswith('Xcode') and
688 xcode4 = (version.startswith('Xcode') and
686 StrictVersion(version.split()[1]) >= StrictVersion('4.0'))
689 StrictVersion(version.split()[1]) >= StrictVersion('4.0'))
687 xcode51 = re.match(r'^Xcode\s+5\.1', version) is not None
690 xcode51 = re.match(r'^Xcode\s+5\.1', version) is not None
688 else:
691 else:
689 # xcodebuild returns empty on OS X Lion with XCode 4.3 not
692 # xcodebuild returns empty on OS X Lion with XCode 4.3 not
690 # installed, but instead with only command-line tools. Assume
693 # installed, but instead with only command-line tools. Assume
691 # that only happens on >= Lion, thus no PPC support.
694 # that only happens on >= Lion, thus no PPC support.
692 xcode4 = True
695 xcode4 = True
693 xcode51 = False
696 xcode51 = False
694
697
695 # XCode 4.0 dropped support for ppc architecture, which is hardcoded in
698 # XCode 4.0 dropped support for ppc architecture, which is hardcoded in
696 # distutils.sysconfig
699 # distutils.sysconfig
697 if xcode4:
700 if xcode4:
698 os.environ['ARCHFLAGS'] = ''
701 os.environ['ARCHFLAGS'] = ''
699
702
700 # XCode 5.1 changes clang such that it now fails to compile if the
703 # XCode 5.1 changes clang such that it now fails to compile if the
701 # -mno-fused-madd flag is passed, but the version of Python shipped with
704 # -mno-fused-madd flag is passed, but the version of Python shipped with
702 # OS X 10.9 Mavericks includes this flag. This causes problems in all
705 # OS X 10.9 Mavericks includes this flag. This causes problems in all
703 # C extension modules, and a bug has been filed upstream at
706 # C extension modules, and a bug has been filed upstream at
704 # http://bugs.python.org/issue21244. We also need to patch this here
707 # http://bugs.python.org/issue21244. We also need to patch this here
705 # so Mercurial can continue to compile in the meantime.
708 # so Mercurial can continue to compile in the meantime.
706 if xcode51:
709 if xcode51:
707 cflags = get_config_var('CFLAGS')
710 cflags = get_config_var('CFLAGS')
708 if cflags and re.search(r'-mno-fused-madd\b', cflags) is not None:
711 if cflags and re.search(r'-mno-fused-madd\b', cflags) is not None:
709 os.environ['CFLAGS'] = (
712 os.environ['CFLAGS'] = (
710 os.environ.get('CFLAGS', '') + ' -Qunused-arguments')
713 os.environ.get('CFLAGS', '') + ' -Qunused-arguments')
711
714
712 setup(name='mercurial',
715 setup(name='mercurial',
713 version=setupversion,
716 version=setupversion,
714 author='Matt Mackall and many others',
717 author='Matt Mackall and many others',
715 author_email='mercurial@mercurial-scm.org',
718 author_email='mercurial@mercurial-scm.org',
716 url='https://mercurial-scm.org/',
719 url='https://mercurial-scm.org/',
717 download_url='https://mercurial-scm.org/release/',
720 download_url='https://mercurial-scm.org/release/',
718 description=('Fast scalable distributed SCM (revision control, version '
721 description=('Fast scalable distributed SCM (revision control, version '
719 'control) system'),
722 'control) system'),
720 long_description=('Mercurial is a distributed SCM tool written in Python.'
723 long_description=('Mercurial is a distributed SCM tool written in Python.'
721 ' It is used by a number of large projects that require'
724 ' It is used by a number of large projects that require'
722 ' fast, reliable distributed revision control, such as '
725 ' fast, reliable distributed revision control, such as '
723 'Mozilla.'),
726 'Mozilla.'),
724 license='GNU GPLv2 or any later version',
727 license='GNU GPLv2 or any later version',
725 classifiers=[
728 classifiers=[
726 'Development Status :: 6 - Mature',
729 'Development Status :: 6 - Mature',
727 'Environment :: Console',
730 'Environment :: Console',
728 'Intended Audience :: Developers',
731 'Intended Audience :: Developers',
729 'Intended Audience :: System Administrators',
732 'Intended Audience :: System Administrators',
730 'License :: OSI Approved :: GNU General Public License (GPL)',
733 'License :: OSI Approved :: GNU General Public License (GPL)',
731 'Natural Language :: Danish',
734 'Natural Language :: Danish',
732 'Natural Language :: English',
735 'Natural Language :: English',
733 'Natural Language :: German',
736 'Natural Language :: German',
734 'Natural Language :: Italian',
737 'Natural Language :: Italian',
735 'Natural Language :: Japanese',
738 'Natural Language :: Japanese',
736 'Natural Language :: Portuguese (Brazilian)',
739 'Natural Language :: Portuguese (Brazilian)',
737 'Operating System :: Microsoft :: Windows',
740 'Operating System :: Microsoft :: Windows',
738 'Operating System :: OS Independent',
741 'Operating System :: OS Independent',
739 'Operating System :: POSIX',
742 'Operating System :: POSIX',
740 'Programming Language :: C',
743 'Programming Language :: C',
741 'Programming Language :: Python',
744 'Programming Language :: Python',
742 'Topic :: Software Development :: Version Control',
745 'Topic :: Software Development :: Version Control',
743 ],
746 ],
744 scripts=scripts,
747 scripts=scripts,
745 packages=packages,
748 packages=packages,
746 ext_modules=extmodules,
749 ext_modules=extmodules,
747 data_files=datafiles,
750 data_files=datafiles,
748 package_data=packagedata,
751 package_data=packagedata,
749 cmdclass=cmdclass,
752 cmdclass=cmdclass,
750 distclass=hgdist,
753 distclass=hgdist,
751 options={'py2exe': {'packages': ['hgext', 'email']},
754 options={'py2exe': {'packages': ['hgext', 'email']},
752 'bdist_mpkg': {'zipdist': False,
755 'bdist_mpkg': {'zipdist': False,
753 'license': 'COPYING',
756 'license': 'COPYING',
754 'readme': 'contrib/macosx/Readme.html',
757 'readme': 'contrib/macosx/Readme.html',
755 'welcome': 'contrib/macosx/Welcome.html',
758 'welcome': 'contrib/macosx/Welcome.html',
756 },
759 },
757 },
760 },
758 **extra)
761 **extra)
General Comments 0
You need to be logged in to leave comments. Login now