Debian Codegraph @

setup.py

raw
1 # This is the mercurial setup script.
2
3 import ctypes
4 import logging
5 import os
6 import re
7 import shutil
8 import ssl
9 import stat
10 import subprocess
11 import sys
12 import sysconfig
13 import tempfile
14
15 if not ssl.HAS_TLSv1_2:
16 error = """
17 The `ssl` module does not advertise support for TLS 1.2.
18 Please make sure that your Python installation was compiled against an OpenSSL
19 version enabling these features (likely this requires the OpenSSL version to
20 be at least 1.0.1).
21 """
22 print(error, file=sys.stderr)
23 sys.exit(1)
24
25 DYLIB_SUFFIX = sysconfig.get_config_vars()['EXT_SUFFIX']
26
27 # Solaris Python packaging brain damage
28 try:
29 import hashlib
30
31 sha = hashlib.sha1()
32 except ImportError:
33 try:
34 import sha
35
36 del sha # silence unused import warning
37 except ImportError:
38 raise SystemExit(
39 "Couldn't import standard hashlib (incomplete Python install)."
40 )
41
42 try:
43 import zlib
44
45 del zlib # silence unused import warning
46 except ImportError:
47 raise SystemExit(
48 "Couldn't import standard zlib (incomplete Python install)."
49 )
50
51 try:
52 import bz2
53
54 del bz2 # silence unused import warning
55 except ImportError:
56 raise SystemExit(
57 "Couldn't import standard bz2 (incomplete Python install)."
58 )
59
60 from setuptools import setup, Command, Extension, Distribution
61 from setuptools.command.build import build
62 from setuptools.command.build_ext import build_ext
63 from setuptools.command.build_py import build_py
64 from setuptools.command.install import install
65 from setuptools.command.install_lib import install_lib
66
67 from setuptools.errors import (
68 CCompilerError,
69 BaseError as DistutilsError,
70 ExecError as DistutilsExecError,
71 )
72
73 # no setuptools.command.build_scripts
74 from distutils.command.build_scripts import build_scripts
75
76 from distutils.spawn import spawn
77 from distutils import file_util
78 from distutils.sysconfig import get_python_inc
79 from distutils.ccompiler import new_compiler
80
81 # raise an explicit error if setuptools_scm is not importable
82 try:
83 import setuptools_scm
84 except ImportError:
85 raise SystemExit(
86 "Couldn't import setuptools_scm (direct call of setup.py?)."
87 )
88 else:
89 del setuptools_scm
90
91
92 ispypy = "PyPy" in sys.version
93
94
95 def sysstr(s):
96 return s.decode('latin-1')
97
98
99 def eprint(*args, **kwargs):
100 kwargs['file'] = sys.stderr
101 print(*args, **kwargs)
102
103
104 def write_if_changed(path, content):
105 """Write content to a file iff the content hasn't changed."""
106 if os.path.exists(path):
107 with open(path, 'rb') as fh:
108 current = fh.read()
109 else:
110 current = b''
111
112 if current != content:
113 with open(path, 'wb') as fh:
114 fh.write(content)
115
116
117 scripts = ['hg']
118 if os.name == 'nt':
119 # We remove hg.bat if we are able to build hg.exe.
120 scripts.append('contrib/win32/hg.bat')
121
122
123 def cancompile(cc, code):
124 tmpdir = tempfile.mkdtemp(prefix='hg-install-')
125 oldstderr = None
126 try:
127 fname = os.path.join(tmpdir, 'testcomp.c')
128 with open(fname, 'w') as file:
129 file.write(code)
130 oldstderr = os.dup(sys.stderr.fileno())
131 # Redirect stderr to /dev/null to hide any error messages
132 # from the compiler.
133 # This will have to be changed if we ever have to check
134 # for a function on Windows.
135 with open('/dev/null', 'w') as devnull:
136 os.dup2(devnull.fileno(), sys.stderr.fileno())
137 objects = cc.compile([fname], output_dir=tmpdir)
138 cc.link_executable(objects, os.path.join(tmpdir, "a.out"))
139 return True
140 except Exception:
141 return False
142 finally:
143 if oldstderr is not None:
144 os.dup2(oldstderr, sys.stderr.fileno())
145 shutil.rmtree(tmpdir)
146
147
148 # simplified version of distutils.ccompiler.CCompiler.has_function
149 # that actually removes its temporary files.
150 def hasfunction(cc, funcname):
151 code = 'int main(void) { %s(); }\n' % funcname
152 return cancompile(cc, code)
153
154
155 def hasheader(cc, headername):
156 code = '#include <%s>\nint main(void) { return 0; }\n' % headername
157 return cancompile(cc, code)
158
159
160 # py2exe needs to be installed to work
161 try:
162 import py2exe
163
164 py2exe.patch_distutils()
165 py2exeloaded = True
166 # import py2exe's patched Distribution class
167 from distutils.core import Distribution
168 except ImportError:
169 py2exeloaded = False
170
171
172 def runcmd(cmd, env, cwd=None):
173 p = subprocess.Popen(
174 cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, cwd=cwd
175 )
176 out, err = p.communicate()
177 return p.returncode, out, err
178
179
180 class hgcommand:
181 def __init__(self, cmd, env):
182 self.cmd = cmd
183 self.env = env
184
185 def __repr__(self):
186 return f"<hgcommand cmd={self.cmd} env={self.env}>"
187
188 def run(self, args):
189 cmd = self.cmd + args
190 returncode, out, err = runcmd(cmd, self.env)
191 err = filterhgerr(err)
192 if err:
193 print("stderr from '%s':" % (' '.join(cmd)), file=sys.stderr)
194 print(err, file=sys.stderr)
195 if returncode != 0:
196 print(
197 "non zero-return '%s': %d" % (' '.join(cmd), returncode),
198 file=sys.stderr,
199 )
200 return b''
201 return out
202
203
204 def filterhgerr(err):
205 # If root is executing setup.py, but the repository is owned by
206 # another user (as in "sudo python setup.py install") we will get
207 # trust warnings since the .hg/hgrc file is untrusted. That is
208 # fine, we don't want to load it anyway. Python may warn about
209 # a missing __init__.py in mercurial/locale, we also ignore that.
210 err = [
211 e
212 for e in err.splitlines()
213 if (
214 not e.startswith(b'not trusting file')
215 and not e.startswith(b'warning: Not importing')
216 and not (
217 e.startswith(b'obsolete feature not enabled')
218 or e.startswith(b'"obsolete" feature not enabled')
219 )
220 and not e.startswith(b'*** failed to import extension')
221 and not e.startswith(b'devel-warn:')
222 and not (
223 e.startswith(b'(third party extension')
224 and e.endswith(b'or newer of Mercurial; disabling)')
225 )
226 )
227 ]
228 return b'\n'.join(b' ' + e for e in err)
229
230
231 def localhgenv(pure_python=True):
232 """Get an environment dictionary to use for invoking or importing
233 mercurial from the local repository."""
234 # Execute hg out of this directory with a custom environment which takes
235 # care to not use any hgrc files and do no localization.
236 env = {
237 'HGRCPATH': '',
238 'LANGUAGE': 'C',
239 'PATH': '',
240 } # make pypi modules that use os.environ['PATH'] happy
241 if pure_python:
242 env['HGMODULEPOLICY'] = 'py'
243 if 'LD_LIBRARY_PATH' in os.environ:
244 env['LD_LIBRARY_PATH'] = os.environ['LD_LIBRARY_PATH']
245 if 'SystemRoot' in os.environ:
246 # SystemRoot is required by Windows to load various DLLs. See:
247 # https://bugs.python.org/issue13524#msg148850
248 env['SystemRoot'] = os.environ['SystemRoot']
249 return env
250
251
252 version = ''
253
254
255 class hgbuild(build):
256 # Insert hgbuildmo first so that files in mercurial/locale/ are found
257 # when build_py is run next.
258 sub_commands = [('build_mo', None)] + build.sub_commands
259
260
261 class hgbuildmo(build):
262 description = "build translations (.mo files)"
263
264 def run(self):
265 result = self._run()
266 if (
267 not result
268 and os.environ.get('MERCURIAL_SETUP_FORCE_TRANSLATIONS') == '1'
269 ):
270 raise DistutilsExecError("failed to build translations")
271
272 def _run(self):
273 try:
274 from shutil import which as find_executable
275 except ImportError:
276 # Deprecated in py3.12
277 from distutils.spawn import find_executable
278
279 if not find_executable('msgfmt'):
280 logging.warning(
281 "could not find msgfmt executable, no translations "
282 "will be built"
283 )
284 return False
285
286 podir = 'i18n'
287 if not os.path.isdir(podir):
288 logging.warning("could not find %s/ directory", podir)
289 return False
290
291 join = os.path.join
292 for po in os.listdir(podir):
293 if not po.endswith('.po'):
294 continue
295 pofile = join(podir, po)
296 modir = join('locale', po[:-3], 'LC_MESSAGES')
297 mofile = join(modir, 'hg.mo')
298 mobuildfile = join('mercurial', mofile)
299 cmd = ['msgfmt', '-v', '-o', mobuildfile, pofile]
300 if sys.platform != 'sunos5':
301 # msgfmt on Solaris does not know about -c
302 cmd.append('-c')
303 self.mkpath(join('mercurial', modir))
304 self.make_file([pofile], mobuildfile, spawn, (cmd,))
305 return True
306
307
308 class hgdist(Distribution):
309 pure = False
310 rust = False
311 no_rust = False
312 cffi = ispypy
313
314 global_options = Distribution.global_options + [
315 ('pure', None, "use pure (slow) Python code instead of C extensions"),
316 ('rust', None, "use Rust extensions additionally to C extensions"),
317 (
318 'no-rust',
319 None,
320 "do not use Rust extensions additionally to C extensions",
321 ),
322 ]
323
324 negative_opt = Distribution.negative_opt.copy()
325 boolean_options = ['pure', 'rust', 'no-rust']
326 negative_opt['no-rust'] = 'rust'
327
328 def _set_command_options(self, command_obj, option_dict=None):
329 # Not all distutils versions in the wild have boolean_options.
330 # This should be cleaned up when we're Python 3 only.
331 command_obj.boolean_options = (
332 getattr(command_obj, 'boolean_options', []) + self.boolean_options
333 )
334 return Distribution._set_command_options(
335 self, command_obj, option_dict=option_dict
336 )
337
338 def has_ext_modules(self):
339 # self.ext_modules is emptied in hgbuildpy.finalize_options which is
340 # too late for some cases
341 return not self.pure and Distribution.has_ext_modules(self)
342
343
344 # This is ugly as a one-liner. So use a variable.
345 buildextnegops = dict(getattr(build_ext, 'negative_options', {}))
346 buildextnegops['no-zstd'] = 'zstd'
347 buildextnegops['no-rust'] = 'rust'
348
349
350 class hgbuildext(build_ext):
351 user_options = build_ext.user_options + [
352 ('zstd', None, 'compile zstd bindings [default]'),
353 ('no-zstd', None, 'do not compile zstd bindings'),
354 (
355 'rust',
356 None,
357 'compile Rust extensions if they are in use '
358 '(requires Cargo) [default]',
359 ),
360 ('no-rust', None, 'do not compile Rust extensions'),
361 ]
362
363 boolean_options = build_ext.boolean_options + ['zstd', 'rust']
364 negative_opt = buildextnegops
365
366 def initialize_options(self):
367 self.zstd = True
368 self.rust = True
369
370 return build_ext.initialize_options(self)
371
372 def finalize_options(self):
373 # Unless overridden by the end user, build extensions in parallel.
374 # Only influences behavior on Python 3.5+.
375 if getattr(self, 'parallel', None) is None:
376 self.parallel = True
377
378 return build_ext.finalize_options(self)
379
380 def build_extensions(self):
381 ruststandalones = [
382 e for e in self.extensions if isinstance(e, RustStandaloneExtension)
383 ]
384 self.extensions = [
385 e for e in self.extensions if e not in ruststandalones
386 ]
387 # Filter out zstd if disabled via argument.
388 if not self.zstd:
389 self.extensions = [
390 e for e in self.extensions if e.name != 'mercurial.zstd'
391 ]
392
393 # Build Rust standalone extensions if it'll be used
394 # and its build is not explicitly disabled (for external build
395 # as Linux distributions would do)
396 if self.distribution.rust and self.rust:
397 if not sys.platform.startswith('linux'):
398 logging.warning(
399 "rust extensions have only been tested on Linux "
400 "and may not behave correctly on other platforms"
401 )
402
403 for rustext in ruststandalones:
404 rustext.build('' if self.editable_mode else self.build_lib)
405
406 return build_ext.build_extensions(self)
407
408 def build_extension(self, ext):
409 if (
410 self.distribution.rust
411 and self.rust
412 and isinstance(ext, RustExtension)
413 ):
414 ext.rustbuild()
415 try:
416 build_ext.build_extension(self, ext)
417 except CCompilerError:
418 if not getattr(ext, 'optional', False):
419 raise
420 logging.warning(
421 "Failed to build optional extension '%s' (skipping)", ext.name
422 )
423
424
425 class hgbuildscripts(build_scripts):
426 def run(self):
427 if os.name != 'nt' or self.distribution.pure:
428 return build_scripts.run(self)
429
430 exebuilt = False
431 try:
432 self.run_command('build_hgexe')
433 exebuilt = True
434 except (DistutilsError, CCompilerError):
435 logging.warning('failed to build optional hg.exe')
436
437 if exebuilt:
438 # Copying hg.exe to the scripts build directory ensures it is
439 # installed by the install_scripts command.
440 hgexecommand = self.get_finalized_command('build_hgexe')
441 dest = os.path.join(self.build_dir, 'hg.exe')
442 self.mkpath(self.build_dir)
443 self.copy_file(hgexecommand.hgexepath, dest)
444
445 # Remove hg.bat because it is redundant with hg.exe.
446 self.scripts.remove('contrib/win32/hg.bat')
447
448 return build_scripts.run(self)
449
450
451 class hgbuildpy(build_py):
452 def finalize_options(self):
453 build_py.finalize_options(self)
454
455 if self.distribution.pure:
456 self.distribution.ext_modules = []
457 elif self.distribution.cffi:
458 from mercurial.cffi import (
459 bdiffbuild,
460 mpatchbuild,
461 )
462
463 exts = [
464 mpatchbuild.ffi.distutils_extension(),
465 bdiffbuild.ffi.distutils_extension(),
466 ]
467 # cffi modules go here
468 if sys.platform == 'darwin':
469 from mercurial.cffi import osutilbuild
470
471 exts.append(osutilbuild.ffi.distutils_extension())
472 self.distribution.ext_modules = exts
473 else:
474 h = os.path.join(get_python_inc(), 'Python.h')
475 if not os.path.exists(h):
476 raise SystemExit(
477 'Python headers are required to build '
478 'Mercurial but weren\'t found in %s' % h
479 )
480
481 def run(self):
482 rust = self.distribution.rust
483 if self.distribution.pure:
484 modulepolicy = 'py'
485 elif self.build_lib == '.':
486 # in-place build should run without rebuilding and Rust extensions
487 modulepolicy = 'rust+c-allow' if rust else 'allow'
488 else:
489 modulepolicy = 'rust+c' if rust else 'c'
490
491 content = b''.join(
492 [
493 b'# this file is autogenerated by setup.py\n',
494 b'modulepolicy = b"%s"\n' % modulepolicy.encode('ascii'),
495 ]
496 )
497
498 if self.editable_mode:
499 here = os.path.dirname(__file__)
500 basepath = os.path.join(here, 'mercurial')
501 else:
502 basepath = os.path.join(self.build_lib, 'mercurial')
503 self.mkpath(basepath)
504
505 write_if_changed(os.path.join(basepath, '__modulepolicy__.py'), content)
506
507 build_py.run(self)
508
509
510 class buildhgextindex(Command):
511 description = 'generate prebuilt index of hgext (for frozen package)'
512 user_options = []
513 _indexfilename = 'hgext/__index__.py'
514
515 def initialize_options(self):
516 pass
517
518 def finalize_options(self):
519 pass
520
521 def run(self):
522 if os.path.exists(self._indexfilename):
523 with open(self._indexfilename, 'w') as f:
524 f.write('# empty\n')
525
526 # here no extension enabled, disabled() lists up everything
527 code = (
528 'import pprint; from mercurial import extensions; '
529 'ext = extensions.disabled();'
530 'ext.pop("__index__", None);'
531 'pprint.pprint(ext)'
532 )
533 returncode, out, err = runcmd(
534 [sys.executable, '-c', code], localhgenv()
535 )
536 if err or returncode != 0:
537 raise DistutilsExecError(err)
538
539 with open(self._indexfilename, 'wb') as f:
540 f.write(b'# this file is autogenerated by setup.py\n')
541 f.write(b'docs = ')
542 f.write(out)
543
544
545 class buildhgexe(build_ext):
546 description = 'compile hg.exe from mercurial/exewrapper.c'
547
548 LONG_PATHS_MANIFEST = """\
549 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
550 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
551 <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
552 <security>
553 <requestedPrivileges>
554 <requestedExecutionLevel
555 level="asInvoker"
556 uiAccess="false"
557 />
558 </requestedPrivileges>
559 </security>
560 </trustInfo>
561 <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
562 <application>
563 <!-- Windows Vista -->
564 <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/>
565 <!-- Windows 7 -->
566 <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
567 <!-- Windows 8 -->
568 <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
569 <!-- Windows 8.1 -->
570 <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
571 <!-- Windows 10 and Windows 11 -->
572 <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
573 </application>
574 </compatibility>
575 <application xmlns="urn:schemas-microsoft-com:asm.v3">
576 <windowsSettings
577 xmlns:ws2="http://schemas.microsoft.com/SMI/2016/WindowsSettings">
578 <ws2:longPathAware>true</ws2:longPathAware>
579 </windowsSettings>
580 </application>
581 <dependency>
582 <dependentAssembly>
583 <assemblyIdentity type="win32"
584 name="Microsoft.Windows.Common-Controls"
585 version="6.0.0.0"
586 processorArchitecture="*"
587 publicKeyToken="6595b64144ccf1df"
588 language="*" />
589 </dependentAssembly>
590 </dependency>
591 </assembly>
592 """
593
594 def initialize_options(self):
595 build_ext.initialize_options(self)
596
597 def build_extensions(self):
598 if os.name != 'nt':
599 return
600 if isinstance(self.compiler, HackedMingw32CCompiler):
601 self.compiler.compiler_so = self.compiler.compiler # no -mdll
602 self.compiler.dll_libraries = [] # no -lmsrvc90
603
604 pythonlib = None
605
606 dirname = os.path.dirname(self.get_ext_fullpath('dummy'))
607 self.hgtarget = os.path.join(dirname, 'hg')
608
609 if getattr(sys, 'dllhandle', None):
610 # Different Python installs can have different Python library
611 # names. e.g. the official CPython distribution uses pythonXY.dll
612 # and MinGW uses libpythonX.Y.dll.
613 _kernel32 = ctypes.windll.kernel32
614 _kernel32.GetModuleFileNameA.argtypes = [
615 ctypes.c_void_p,
616 ctypes.c_void_p,
617 ctypes.c_ulong,
618 ]
619 _kernel32.GetModuleFileNameA.restype = ctypes.c_ulong
620 size = 1000
621 buf = ctypes.create_string_buffer(size + 1)
622 filelen = _kernel32.GetModuleFileNameA(
623 sys.dllhandle, ctypes.byref(buf), size
624 )
625
626 if filelen > 0 and filelen != size:
627 dllbasename = os.path.basename(buf.value)
628 if not dllbasename.lower().endswith(b'.dll'):
629 raise SystemExit(
630 'Python DLL does not end with .dll: %s' % dllbasename
631 )
632 pythonlib = dllbasename[:-4]
633
634 # Copy the pythonXY.dll next to the binary so that it runs
635 # without tampering with PATH.
636 dest = os.path.join(
637 os.path.dirname(self.hgtarget),
638 os.fsdecode(dllbasename),
639 )
640
641 if not os.path.exists(dest):
642 shutil.copy(buf.value, dest)
643
644 # Also overwrite python3.dll so that hgext.git is usable.
645 # TODO: also handle the MSYS flavor
646 python_x = os.path.join(
647 os.path.dirname(os.fsdecode(buf.value)),
648 "python3.dll",
649 )
650
651 if os.path.exists(python_x):
652 dest = os.path.join(
653 os.path.dirname(self.hgtarget),
654 os.path.basename(python_x),
655 )
656
657 shutil.copy(python_x, dest)
658
659 if not pythonlib:
660 logging.warning(
661 'could not determine Python DLL filename; assuming pythonXY'
662 )
663
664 hv = sys.hexversion
665 pythonlib = b'python%d%d' % (hv >> 24, (hv >> 16) & 0xFF)
666
667 logging.info('using %s as Python library name', pythonlib)
668 with open('mercurial/hgpythonlib.h', 'wb') as f:
669 f.write(b'/* this file is autogenerated by setup.py */\n')
670 f.write(b'#define HGPYTHONLIB "%s"\n' % pythonlib)
671
672 objects = self.compiler.compile(
673 ['mercurial/exewrapper.c'],
674 output_dir=self.build_temp,
675 macros=[('_UNICODE', None), ('UNICODE', None)],
676 )
677 self.compiler.link_executable(objects, self.hgtarget, libraries=[])
678
679 self.addlongpathsmanifest()
680
681 def addlongpathsmanifest(self):
682 """Add manifest pieces so that hg.exe understands long paths
683
684 Why resource #1 should be used for .exe manifests? I don't know and
685 wasn't able to find an explanation for mortals. But it seems to work.
686 """
687 exefname = self.compiler.executable_filename(self.hgtarget)
688 fdauto, manfname = tempfile.mkstemp(suffix='.hg.exe.manifest')
689 os.close(fdauto)
690 with open(manfname, 'w', encoding="UTF-8") as f:
691 f.write(self.LONG_PATHS_MANIFEST)
692 logging.info("long paths manifest is written to '%s'", manfname)
693 outputresource = '-outputresource:%s;#1' % exefname
694 logging.info("running mt.exe to update hg.exe's manifest in-place")
695
696 self.spawn(
697 [
698 self.compiler.mt,
699 '-nologo',
700 '-manifest',
701 manfname,
702 outputresource,
703 ]
704 )
705 logging.info("done updating hg.exe's manifest")
706 os.remove(manfname)
707
708 @property
709 def hgexepath(self):
710 return os.path.join(
711 os.path.dirname(self.get_ext_fullpath('dummy')), 'hg.exe'
712 )
713
714
715 class hgbuilddoc(Command):
716 description = 'build documentation'
717 user_options = [
718 ('man', None, 'generate man pages'),
719 ('html', None, 'generate html pages'),
720 ]
721
722 def initialize_options(self):
723 self.man = None
724 self.html = None
725
726 def finalize_options(self):
727 # If --man or --html are set, only generate what we're told to.
728 # Otherwise generate everything.
729 have_subset = self.man is not None or self.html is not None
730
731 if have_subset:
732 self.man = True if self.man else False
733 self.html = True if self.html else False
734 else:
735 self.man = True
736 self.html = True
737
738 def run(self):
739 def normalizecrlf(p):
740 with open(p, 'rb') as fh:
741 orig = fh.read()
742
743 if b'\r\n' not in orig:
744 return
745
746 logging.info('normalizing %s to LF line endings', p)
747 with open(p, 'wb') as fh:
748 fh.write(orig.replace(b'\r\n', b'\n'))
749
750 def gentxt(root):
751 txt = 'doc/%s.txt' % root
752 logging.info('generating %s', txt)
753 res, out, err = runcmd(
754 [sys.executable, 'gendoc.py', root], os.environ, cwd='doc'
755 )
756 if res:
757 raise SystemExit(
758 'error running gendoc.py: %s'
759 % '\n'.join([sysstr(out), sysstr(err)])
760 )
761
762 with open(txt, 'wb') as fh:
763 fh.write(out)
764
765 def gengendoc(root):
766 gendoc = 'doc/%s.gendoc.txt' % root
767
768 logging.info('generating %s', gendoc)
769 res, out, err = runcmd(
770 [sys.executable, 'gendoc.py', '%s.gendoc' % root],
771 os.environ,
772 cwd='doc',
773 )
774 if res:
775 raise SystemExit(
776 'error running gendoc: %s'
777 % '\n'.join([sysstr(out), sysstr(err)])
778 )
779
780 with open(gendoc, 'wb') as fh:
781 fh.write(out)
782
783 def genman(root):
784 logging.info('generating doc/%s', root)
785 res, out, err = runcmd(
786 [
787 sys.executable,
788 'runrst',
789 'hgmanpage',
790 '--halt',
791 'warning',
792 '--strip-elements-with-class',
793 'htmlonly',
794 '%s.txt' % root,
795 root,
796 ],
797 os.environ,
798 cwd='doc',
799 )
800 if res:
801 raise SystemExit(
802 'error running runrst: %s'
803 % '\n'.join([sysstr(out), sysstr(err)])
804 )
805
806 normalizecrlf('doc/%s' % root)
807
808 def genhtml(root):
809 logging.info('generating doc/%s.html', root)
810 res, out, err = runcmd(
811 [
812 sys.executable,
813 'runrst',
814 'html',
815 '--halt',
816 'warning',
817 '--link-stylesheet',
818 '--stylesheet-path',
819 'style.css',
820 '%s.txt' % root,
821 '%s.html' % root,
822 ],
823 os.environ,
824 cwd='doc',
825 )
826 if res:
827 raise SystemExit(
828 'error running runrst: %s'
829 % '\n'.join([sysstr(out), sysstr(err)])
830 )
831
832 normalizecrlf('doc/%s.html' % root)
833
834 # This logic is duplicated in doc/Makefile.
835 sources = {
836 f
837 for f in os.listdir('mercurial/helptext')
838 if re.search(r'[0-9]\.txt$', f)
839 }
840
841 # common.txt is a one-off.
842 gentxt('common')
843
844 for source in sorted(sources):
845 assert source[-4:] == '.txt'
846 root = source[:-4]
847
848 gentxt(root)
849 gengendoc(root)
850
851 if self.man:
852 genman(root)
853 if self.html:
854 genhtml(root)
855
856
857 class hginstall(install):
858 user_options = install.user_options + [
859 (
860 'old-and-unmanageable',
861 None,
862 'noop, present for eggless setuptools compat',
863 ),
864 (
865 'single-version-externally-managed',
866 None,
867 'noop, present for eggless setuptools compat',
868 ),
869 ]
870
871 sub_commands = install.sub_commands + [
872 ('install_completion', lambda self: True)
873 ]
874
875 # Also helps setuptools not be sad while we refuse to create eggs.
876 single_version_externally_managed = True
877
878 def get_sub_commands(self):
879 # Screen out egg related commands to prevent egg generation. But allow
880 # mercurial.egg-info generation, since that is part of modern
881 # packaging.
882 excl = {'bdist_egg'}
883 return filter(lambda x: x not in excl, install.get_sub_commands(self))
884
885
886 class hginstalllib(install_lib):
887 """
888 This is a specialization of install_lib that replaces the copy_file used
889 there so that it supports setting the mode of files after copying them,
890 instead of just preserving the mode that the files originally had. If your
891 system has a umask of something like 027, preserving the permissions when
892 copying will lead to a broken install.
893
894 Note that just passing keep_permissions=False to copy_file would be
895 insufficient, as it might still be applying a umask.
896 """
897
898 def run(self):
899 realcopyfile = file_util.copy_file
900
901 def copyfileandsetmode(*args, **kwargs):
902 src, dst = args[0], args[1]
903 dst, copied = realcopyfile(*args, **kwargs)
904 if copied:
905 st = os.stat(src)
906 # Persist executable bit (apply it to group and other if user
907 # has it)
908 if st[stat.ST_MODE] & stat.S_IXUSR:
909 setmode = int('0755', 8)
910 else:
911 setmode = int('0644', 8)
912 m = stat.S_IMODE(st[stat.ST_MODE])
913 m = (m & ~int('0777', 8)) | setmode
914 os.chmod(dst, m)
915
916 file_util.copy_file = copyfileandsetmode
917 try:
918 install_lib.run(self)
919 finally:
920 file_util.copy_file = realcopyfile
921
922
923 class hginstallcompletion(Command):
924 description = 'Install shell completion'
925
926 def initialize_options(self):
927 self.install_dir = None
928 self.outputs = []
929
930 def finalize_options(self):
931 self.set_undefined_options(
932 'install_data', ('install_dir', 'install_dir')
933 )
934
935 def get_outputs(self):
936 return self.outputs
937
938 def run(self):
939 for src, dir_path, dest in (
940 (
941 'bash_completion',
942 ('share', 'bash-completion', 'completions'),
943 'hg',
944 ),
945 ('zsh_completion', ('share', 'zsh', 'site-functions'), '_hg'),
946 ):
947 dir = os.path.join(self.install_dir, *dir_path)
948 self.mkpath(dir)
949
950 dest = os.path.join(dir, dest)
951 self.outputs.append(dest)
952 self.copy_file(os.path.join('contrib', src), dest)
953
954
955 cmdclass = {
956 'build': hgbuild,
957 'build_doc': hgbuilddoc,
958 'build_mo': hgbuildmo,
959 'build_ext': hgbuildext,
960 'build_py': hgbuildpy,
961 'build_scripts': hgbuildscripts,
962 'build_hgextindex': buildhgextindex,
963 'install': hginstall,
964 'install_completion': hginstallcompletion,
965 'install_lib': hginstalllib,
966 'build_hgexe': buildhgexe,
967 }
968
969 packages = [
970 'mercurial',
971 'mercurial.admin',
972 'mercurial.cext',
973 'mercurial.cffi',
974 'mercurial.cmd_impls',
975 'mercurial.configuration',
976 'mercurial.branching',
977 'mercurial.defaultrc',
978 'mercurial.dirstateutils',
979 'mercurial.exchanges',
980 'mercurial.helptext',
981 'mercurial.helptext.internals',
982 'mercurial.hgweb',
983 'mercurial.interfaces',
984 'mercurial.main_script',
985 'mercurial.merge_utils',
986 'mercurial.narrow',
987 'mercurial.pure',
988 'mercurial.stabletailgraph',
989 'mercurial.store_utils',
990 'mercurial.templates',
991 'mercurial.thirdparty',
992 'mercurial.thirdparty.attr',
993 'mercurial.thirdparty.tomli',
994 'mercurial.upgrade_utils',
995 'mercurial.utils',
996 'mercurial.repo',
997 'mercurial.revlogutils',
998 'mercurial.testing',
999 'hgext',
1000 'hgext.convert',
1001 'hgext.fsmonitor',
1002 'hgext.fastannotate',
1003 'hgext.fsmonitor.pywatchman',
1004 'hgext.git',
1005 'hgext.highlight',
1006 'hgext.hooklib',
1007 'hgext.largefiles',
1008 'hgext.lfs',
1009 'hgext.narrow',
1010 'hgext.remotefilelog',
1011 'hgext.zeroconf',
1012 'hgext3rd',
1013 'hgdemandimport',
1014 ]
1015
1016 for name in os.listdir(os.path.join('mercurial', 'templates')):
1017 if name != '__pycache__' and os.path.isdir(
1018 os.path.join('mercurial', 'templates', name)
1019 ):
1020 packages.append('mercurial.templates.%s' % name)
1021
1022 if 'HG_PY2EXE_EXTRA_INSTALL_PACKAGES' in os.environ:
1023 # py2exe can't cope with namespace packages very well, so we have to
1024 # install any hgext3rd.* extensions that we want in the final py2exe
1025 # image here. This is gross, but you gotta do what you gotta do.
1026 packages.extend(os.environ['HG_PY2EXE_EXTRA_INSTALL_PACKAGES'].split(' '))
1027
1028 common_depends = [
1029 'mercurial/bitmanipulation.h',
1030 'mercurial/compat.h',
1031 'mercurial/cext/util.h',
1032 ]
1033 common_include_dirs = ['mercurial']
1034
1035 common_cflags = []
1036
1037 # MSVC 2008 still needs declarations at the top of the scope, but Python 3.9
1038 # makes declarations not at the top of a scope in the headers.
1039 if os.name != 'nt' and sys.version_info[1] < 9:
1040 common_cflags = ['-Werror=declaration-after-statement']
1041
1042 osutil_cflags = []
1043 osutil_ldflags = []
1044
1045 # platform specific macros
1046 for plat, func in [('bsd', 'setproctitle')]:
1047 if re.search(plat, sys.platform) and hasfunction(new_compiler(), func):
1048 osutil_cflags.append('-DHAVE_%s' % func.upper())
1049
1050 for plat, macro, code in [
1051 (
1052 'bsd|darwin',
1053 'BSD_STATFS',
1054 '''
1055 #include <sys/param.h>
1056 #include <sys/mount.h>
1057 int main() { struct statfs s; return sizeof(s.f_fstypename); }
1058 ''',
1059 ),
1060 (
1061 'linux',
1062 'LINUX_STATFS',
1063 '''
1064 #include <linux/magic.h>
1065 #include <sys/vfs.h>
1066 int main() { struct statfs s; return sizeof(s.f_type); }
1067 ''',
1068 ),
1069 ]:
1070 if re.search(plat, sys.platform) and cancompile(new_compiler(), code):
1071 osutil_cflags.append('-DHAVE_%s' % macro)
1072
1073 if sys.platform == 'darwin':
1074 osutil_ldflags += ['-framework', 'ApplicationServices']
1075
1076 if sys.platform == 'sunos5':
1077 osutil_ldflags += ['-lsocket']
1078
1079 xdiff_srcs = [
1080 'mercurial/thirdparty/xdiff/xdiffi.c',
1081 'mercurial/thirdparty/xdiff/xprepare.c',
1082 'mercurial/thirdparty/xdiff/xutils.c',
1083 ]
1084
1085 xdiff_headers = [
1086 'mercurial/thirdparty/xdiff/xdiff.h',
1087 'mercurial/thirdparty/xdiff/xdiffi.h',
1088 'mercurial/thirdparty/xdiff/xinclude.h',
1089 'mercurial/thirdparty/xdiff/xmacros.h',
1090 'mercurial/thirdparty/xdiff/xprepare.h',
1091 'mercurial/thirdparty/xdiff/xtypes.h',
1092 'mercurial/thirdparty/xdiff/xutils.h',
1093 ]
1094
1095
1096 class RustCompilationError(CCompilerError):
1097 """Exception class for Rust compilation errors."""
1098
1099
1100 class RustExtension(Extension):
1101 """Base classes for concrete Rust Extension classes."""
1102
1103 rusttargetdir = os.path.join('rust', 'target', 'release')
1104
1105 def __init__(self, mpath, sources, rustlibname, subcrate, **kw):
1106 Extension.__init__(self, mpath, sources, **kw)
1107 srcdir = self.rustsrcdir = os.path.join('rust', subcrate)
1108
1109 # adding Rust source and control files to depends so that the extension
1110 # gets rebuilt if they've changed
1111 self.depends.append(os.path.join(srcdir, 'Cargo.toml'))
1112 cargo_lock = os.path.join(srcdir, 'Cargo.lock')
1113 if os.path.exists(cargo_lock):
1114 self.depends.append(cargo_lock)
1115 for dirpath, subdir, fnames in os.walk(os.path.join(srcdir, 'src')):
1116 if dirpath == os.path.join(srcdir, "target"):
1117 # Skip this large artifacts free
1118 continue
1119 self.depends.extend(
1120 os.path.join(dirpath, fname)
1121 for fname in fnames
1122 if os.path.splitext(fname)[1] == '.rs'
1123 )
1124
1125 @staticmethod
1126 def rustdylibsuffix():
1127 """Return the suffix for shared libraries produced by rustc.
1128
1129 See also: https://doc.rust-lang.org/reference/linkage.html
1130 """
1131 if sys.platform == 'darwin':
1132 return '.dylib'
1133 elif os.name == 'nt':
1134 return '.dll'
1135 else:
1136 return '.so'
1137
1138 def rustbuild(self):
1139 env = os.environ.copy()
1140 if 'HGTEST_RESTOREENV' in env:
1141 # Mercurial tests change HOME to a temporary directory,
1142 # but, if installed with rustup, the Rust toolchain needs
1143 # HOME to be correct (otherwise the 'no default toolchain'
1144 # error message is issued and the build fails).
1145 # This happens currently with test-hghave.t, which does
1146 # invoke this build.
1147
1148 # Unix only fix (os.path.expanduser not really reliable if
1149 # HOME is shadowed like this)
1150 import pwd
1151
1152 env['HOME'] = pwd.getpwuid(os.getuid()).pw_dir
1153
1154 # Wildy shooting in the dark to make sure rust-pyo3 use the right
1155 # python
1156 if not sys.executable:
1157 msg = "Cannot determine which Python to compile Rust for"
1158 raise RustCompilationError(msg)
1159 env['PYTHON_SYS_EXECUTABLE'] = sys.executable
1160 env['PYTHONEXECUTABLE'] = sys.executable
1161 env['PYTHON'] = sys.executable
1162 env['PYO3_PYTHON'] = sys.executable
1163
1164 cargocmd = ['cargo', 'rustc', '--release']
1165
1166 rust_features = env.get("HG_RUST_FEATURES")
1167 if rust_features:
1168 cargocmd.extend(('--features', rust_features))
1169
1170 cargocmd.append('--')
1171 if sys.platform == 'darwin':
1172 cargocmd.extend(
1173 ("-C", "link-arg=-undefined", "-C", "link-arg=dynamic_lookup")
1174 )
1175 try:
1176 subprocess.check_call(cargocmd, env=env, cwd=self.rustsrcdir)
1177 except FileNotFoundError:
1178 raise RustCompilationError("Cargo not found")
1179 except PermissionError:
1180 raise RustCompilationError(
1181 "Cargo found, but permission to execute it is denied"
1182 )
1183 except subprocess.CalledProcessError:
1184 raise RustCompilationError(
1185 "Cargo failed. Working directory: %r, "
1186 "command: %r, environment: %r"
1187 % (self.rustsrcdir, cargocmd, env)
1188 )
1189
1190
1191 class RustStandaloneExtension(RustExtension):
1192 def __init__(self, pydottedname, rustcrate, dylibname, **kw):
1193 RustExtension.__init__(
1194 self, pydottedname, [], dylibname, rustcrate, **kw
1195 )
1196 self.dylibname = dylibname
1197
1198 def build(self, target_dir):
1199 self.rustbuild()
1200 target = [target_dir]
1201 target.extend(self.name.split('.'))
1202 target[-1] += DYLIB_SUFFIX
1203 target = os.path.join(*target)
1204 os.makedirs(os.path.dirname(target), exist_ok=True)
1205 shutil.copy2(
1206 os.path.join(
1207 self.rusttargetdir, self.dylibname + self.rustdylibsuffix()
1208 ),
1209 target,
1210 )
1211
1212
1213 extmodules = [
1214 Extension(
1215 'mercurial.cext.base85',
1216 ['mercurial/cext/base85.c'],
1217 include_dirs=common_include_dirs,
1218 extra_compile_args=common_cflags,
1219 depends=common_depends,
1220 ),
1221 Extension(
1222 'mercurial.cext.bdiff',
1223 ['mercurial/bdiff.c', 'mercurial/cext/bdiff.c'] + xdiff_srcs,
1224 include_dirs=common_include_dirs,
1225 extra_compile_args=common_cflags,
1226 depends=common_depends + ['mercurial/bdiff.h'] + xdiff_headers,
1227 ),
1228 Extension(
1229 'mercurial.cext.mpatch',
1230 ['mercurial/mpatch.c', 'mercurial/cext/mpatch.c'],
1231 include_dirs=common_include_dirs,
1232 extra_compile_args=common_cflags,
1233 depends=common_depends,
1234 ),
1235 Extension(
1236 'mercurial.cext.parsers',
1237 [
1238 'mercurial/cext/charencode.c',
1239 'mercurial/cext/dirs.c',
1240 'mercurial/cext/manifest.c',
1241 'mercurial/cext/parsers.c',
1242 'mercurial/cext/pathencode.c',
1243 'mercurial/cext/revlog.c',
1244 ],
1245 include_dirs=common_include_dirs,
1246 extra_compile_args=common_cflags,
1247 depends=common_depends
1248 + [
1249 'mercurial/cext/charencode.h',
1250 'mercurial/cext/revlog.h',
1251 ],
1252 ),
1253 Extension(
1254 'mercurial.cext.osutil',
1255 ['mercurial/cext/osutil.c'],
1256 include_dirs=common_include_dirs,
1257 extra_compile_args=common_cflags + osutil_cflags,
1258 extra_link_args=osutil_ldflags,
1259 depends=common_depends,
1260 ),
1261 Extension(
1262 'mercurial.thirdparty.sha1dc',
1263 [
1264 'mercurial/thirdparty/sha1dc/cext.c',
1265 'mercurial/thirdparty/sha1dc/lib/sha1.c',
1266 'mercurial/thirdparty/sha1dc/lib/ubc_check.c',
1267 ],
1268 extra_compile_args=common_cflags,
1269 ),
1270 Extension(
1271 'hgext.fsmonitor.pywatchman.bser',
1272 ['hgext/fsmonitor/pywatchman/bser.c'],
1273 extra_compile_args=common_cflags,
1274 ),
1275 ]
1276
1277 if os.name != 'nt':
1278 extmodules += [
1279 RustStandaloneExtension(
1280 'mercurial.pyo3_rustext',
1281 'hg-pyo3',
1282 'librusthgpyo3',
1283 ),
1284 ]
1285
1286 sys.path.insert(0, 'contrib/python-zstandard')
1287 import setup_zstd
1288
1289 zstd = setup_zstd.get_c_extension(
1290 name='mercurial.zstd', root=os.path.abspath(os.path.dirname(__file__))
1291 )
1292 zstd.extra_compile_args += common_cflags
1293 extmodules.append(zstd)
1294
1295 try:
1296 from distutils import cygwinccompiler
1297
1298 # the -mno-cygwin option has been deprecated for years
1299 mingw32compilerclass = cygwinccompiler.Mingw32CCompiler
1300
1301 class HackedMingw32CCompiler(cygwinccompiler.Mingw32CCompiler):
1302 def __init__(self, *args, **kwargs):
1303 mingw32compilerclass.__init__(self, *args, **kwargs)
1304 for i in 'compiler compiler_so linker_exe linker_so'.split():
1305 try:
1306 getattr(self, i).remove('-mno-cygwin')
1307 except ValueError:
1308 pass
1309
1310 cygwinccompiler.Mingw32CCompiler = HackedMingw32CCompiler
1311 except ImportError:
1312 # the cygwinccompiler package is not available on some Python
1313 # distributions like the ones from the optware project for Synology
1314 # DiskStation boxes
1315 class HackedMingw32CCompiler:
1316 pass
1317
1318
1319 packagedata = {
1320 'mercurial': [
1321 'configitems.toml',
1322 'locale/*/LC_MESSAGES/hg.mo',
1323 'dummycert.pem',
1324 ],
1325 'mercurial.defaultrc': [
1326 '*.rc',
1327 ],
1328 'mercurial.helptext': [
1329 '*.txt',
1330 ],
1331 'mercurial.helptext.internals': [
1332 '*.txt',
1333 ],
1334 'mercurial.thirdparty.attr': [
1335 '*.pyi',
1336 'py.typed',
1337 ],
1338 'mercurial.cext': [
1339 '*.pyi',
1340 'py.typed',
1341 ],
1342 }
1343
1344
1345 def ordinarypath(p):
1346 return p and p[0] != '.' and p[-1] != '~'
1347
1348
1349 for root in ('templates',):
1350 for curdir, dirs, files in os.walk(os.path.join('mercurial', root)):
1351 packagename = curdir.replace(os.sep, '.')
1352 packagedata[packagename] = list(filter(ordinarypath, files))
1353
1354 extra = {}
1355
1356 py2exepackages = [
1357 'hgdemandimport',
1358 'hgext3rd',
1359 'hgext',
1360 'email',
1361 # implicitly imported per module policy
1362 # (cffi wouldn't be used as a frozen exe)
1363 'mercurial.cext',
1364 #'mercurial.cffi',
1365 'mercurial.pure',
1366 ]
1367
1368 py2exe_includes = []
1369
1370 py2exeexcludes = []
1371 py2exedllexcludes = ['crypt32.dll']
1372
1373 if py2exeloaded:
1374 extra['console'] = [
1375 {
1376 'script': 'hg',
1377 'copyright': 'Copyright (C) 2005-2026 Olivia Mackall and others',
1378 'product_version': version,
1379 }
1380 ]
1381 # Sub command of 'build' because 'py2exe' does not handle sub_commands.
1382 # Need to override hgbuild because it has a private copy of
1383 # build.sub_commands.
1384 hgbuild.sub_commands.insert(0, ('build_hgextindex', None))
1385 # put dlls in sub directory so that they won't pollute PATH
1386 extra['zipfile'] = 'lib/library.zip'
1387
1388 # We allow some configuration to be supplemented via environment
1389 # variables. This is better than setup.cfg files because it allows
1390 # supplementing configs instead of replacing them.
1391 extrapackages = os.environ.get('HG_PY2EXE_EXTRA_PACKAGES')
1392 if extrapackages:
1393 py2exepackages.extend(extrapackages.split(' '))
1394
1395 extra_includes = os.environ.get('HG_PY2EXE_EXTRA_INCLUDES')
1396 if extra_includes:
1397 py2exe_includes.extend(extra_includes.split(' '))
1398
1399 excludes = os.environ.get('HG_PY2EXE_EXTRA_EXCLUDES')
1400 if excludes:
1401 py2exeexcludes.extend(excludes.split(' '))
1402
1403 dllexcludes = os.environ.get('HG_PY2EXE_EXTRA_DLL_EXCLUDES')
1404 if dllexcludes:
1405 py2exedllexcludes.extend(dllexcludes.split(' '))
1406
1407 if os.environ.get('PYOXIDIZER'):
1408 hgbuild.sub_commands.insert(0, ('build_hgextindex', None))
1409
1410 setup(
1411 long_description=(
1412 'Mercurial is a distributed SCM tool written in Python.'
1413 ' It is used by a number of large projects that require'
1414 ' fast, reliable distributed revision control, such as '
1415 'Mozilla.'
1416 ),
1417 long_description_content_type='text/x-rst',
1418 scripts=scripts,
1419 packages=packages,
1420 ext_modules=extmodules,
1421 package_data=packagedata,
1422 cmdclass=cmdclass,
1423 distclass=hgdist,
1424 options={
1425 'py2exe': {
1426 'bundle_files': 3,
1427 'dll_excludes': py2exedllexcludes,
1428 'includes': py2exe_includes,
1429 'excludes': py2exeexcludes,
1430 'packages': py2exepackages,
1431 },
1432 'bdist_mpkg': {
1433 'zipdist': False,
1434 'license': 'COPYING',
1435 'readme': 'contrib/packaging/macosx/Readme.html',
1436 'welcome': 'contrib/packaging/macosx/Welcome.html',
1437 },
1438 },
1439 **extra,
1440 )