Debian Codegraph @

tests/hghave.py

raw
1 from __future__ import annotations
2
3 import os
4 import platform
5 import re
6 import shutil
7 import socket
8 import stat
9 import subprocess
10 import sys
11 import tempfile
12
13
14 # Provide a way for tests to easily trigger some exception in this file.
15 #
16 # This is used to test for error handling.
17 if os.environ.get('DEVEL_HGHAVE_CRASH', '0') == '1':
18 raise RuntimeError("planned test crash")
19
20 tempprefix = 'hg-hghave-'
21
22 checks = {
23 "true": (lambda: True, "yak shaving"),
24 "false": (lambda: False, "nail clipper"),
25 "known-bad-output": (lambda: True, "use for currently known bad output"),
26 "missing-correct-output": (lambda: False, "use for missing good output"),
27 }
28
29 try:
30 import msvcrt
31
32 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
33 msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY)
34 except ImportError:
35 pass
36
37 stdout = getattr(sys.stdout, 'buffer', sys.stdout)
38 stderr = getattr(sys.stderr, 'buffer', sys.stderr)
39
40
41 def _sys2bytes(p):
42 if p is None:
43 return p
44 return p.encode('utf-8')
45
46
47 def _bytes2sys(p):
48 if p is None:
49 return p
50 return p.decode('utf-8')
51
52
53 def has_cmd(cmd: str) -> bool:
54 """return True if there is an executable `cmd` in the PATH"""
55 return shutil.which(cmd, os.X_OK) is not None
56
57
58 def check(name, desc):
59 """Registers a check function for a feature."""
60
61 def decorator(func):
62 checks[name] = (func, desc)
63 return func
64
65 return decorator
66
67
68 def checkvers(name, desc, vers):
69 """Registers a check function for each of a series of versions.
70
71 vers can be a list or an iterator.
72
73 Produces a series of feature checks that have the form <name><vers> without
74 any punctuation (even if there's punctuation in 'vers'; i.e. this produces
75 'py38', not 'py3.8' or 'py-38')."""
76
77 def decorator(func):
78 def funcv(v):
79 def f():
80 return func(v)
81
82 return f
83
84 for v in vers:
85 assert isinstance(v, str)
86 f = funcv(v)
87 checks['%s%s' % (name, v.replace('.', ''))] = (f, desc % v)
88 return func
89
90 return decorator
91
92
93 def checkfeatures(features):
94 result = {
95 'error': [],
96 'missing': [],
97 'skipped': [],
98 }
99
100 for feature in features:
101 negate = feature.startswith('no-')
102 if negate:
103 feature = feature[3:]
104
105 if feature not in checks:
106 result['missing'].append(feature)
107 continue
108
109 check, desc = checks[feature]
110 try:
111 available = check()
112 except Exception as e:
113 result['error'].append('hghave check %s failed: %r' % (feature, e))
114 continue
115
116 if not negate and not available:
117 result['skipped'].append('missing feature: %s' % desc)
118 elif negate and available:
119 result['skipped'].append('system supports %s' % desc)
120
121 return result
122
123
124 def require(features):
125 """Require that features are available, exiting if not."""
126 result = checkfeatures(features)
127
128 for missing in result['missing']:
129 stderr.write(
130 ('skipped: unknown feature: %s\n' % missing).encode('utf-8')
131 )
132 for msg in result['skipped']:
133 stderr.write(('skipped: %s\n' % msg).encode('utf-8'))
134 for msg in result['error']:
135 stderr.write(('%s\n' % msg).encode('utf-8'))
136
137 if result['missing']:
138 sys.exit(2)
139
140 if result['skipped'] or result['error']:
141 sys.exit(1)
142
143
144 def environ():
145 # Tests on Windows have to fake USERPROFILE to point to the test area so
146 # that `~` is properly expanded on py3.8+. However, some tools like black
147 # make calls that need the real USERPROFILE in order to run `foo --version`.
148 env = os.environ
149 if os.name == 'nt':
150 env = os.environ.copy()
151 env['USERPROFILE'] = env['REALUSERPROFILE']
152 return env
153
154
155 def matchoutput(cmd, regexp: bytes, ignorestatus: bool = False):
156 """Return the match object if cmd executes successfully and its output
157 is matched by the supplied regular expression.
158 """
159 env = environ()
160 # make sure that strict-rhg mode does not interfer with hghave call
161 env['RHG_ON_UNSUPPORTED'] = 'fallback'
162
163 r = re.compile(regexp)
164 p = subprocess.Popen(
165 cmd,
166 shell=True,
167 stdout=subprocess.PIPE,
168 stderr=subprocess.STDOUT,
169 env=env,
170 )
171 s = p.communicate()[0]
172 ret = p.returncode
173 return (ignorestatus or not ret) and r.search(s)
174
175
176 @check("baz", "GNU Arch baz client")
177 def has_baz():
178 return matchoutput('baz --version 2>&1', br'baz Bazaar version')
179
180
181 @check("bzr", "Breezy library and executable version >= 3.1")
182 def has_bzr():
183 try:
184 # Test the Breezy python lib
185 import breezy
186 import breezy.bzr.bzrdir
187 import breezy.errors
188 import breezy.revision
189 import breezy.revisionspec
190
191 del breezy.revisionspec
192 if breezy.__doc__ is None or breezy.version_info[:2] < (3, 1):
193 return False
194 except (AttributeError, ImportError):
195 return False
196 # Test the executable
197 return matchoutput('brz --version 2>&1', br'Breezy \(brz\) ')
198
199
200 @check("chg", "running with chg")
201 def has_chg():
202 return 'CHG_INSTALLED_AS_HG' in os.environ
203
204
205 @check("rhg", "running with rhg as 'hg'")
206 def has_rhg():
207 return 'RHG_INSTALLED_AS_HG' in os.environ
208
209
210 @check("pyoxidizer", "running with pyoxidizer build as 'hg'")
211 def has_pyoxidizer():
212 return 'PYOXIDIZED_INSTALLED_AS_HG' in os.environ
213
214
215 @check(
216 "pyoxidizer-in-memory",
217 "running with pyoxidizer build as 'hg' with embedded resources",
218 )
219 def has_pyoxidizer_mem():
220 return 'PYOXIDIZED_IN_MEMORY_RSRC' in os.environ
221
222
223 @check(
224 "pyoxidizer-in-filesystem",
225 "running with pyoxidizer build as 'hg' with external resources",
226 )
227 def has_pyoxidizer_fs():
228 return 'PYOXIDIZED_FILESYSTEM_RSRC' in os.environ
229
230
231 @check("cvs", "cvs client/server")
232 def has_cvs():
233 re = br'Concurrent Versions System.*?server'
234 return matchoutput('cvs --version 2>&1', re) and not has_msys()
235
236
237 @check("cvs112", "cvs client/server 1.12.* (not cvsnt)")
238 def has_cvs112():
239 re = br'Concurrent Versions System \(CVS\) 1.12.*?server'
240 return matchoutput('cvs --version 2>&1', re) and not has_msys()
241
242
243 @check("cvsnt", "cvsnt client/server")
244 def has_cvsnt():
245 re = br'Concurrent Versions System \(CVSNT\) (\d+).(\d+).*\(client/server\)'
246 return matchoutput('cvsnt --version 2>&1', re)
247
248
249 @check("darcs", "darcs client")
250 def has_darcs():
251 return matchoutput('darcs --version', br'\b2\.([2-9]|\d{2})', True)
252
253
254 @check("mtn", "monotone client (>= 1.0)")
255 def has_mtn():
256 return matchoutput('mtn --version', br'monotone', True) and not matchoutput(
257 'mtn --version', br'monotone 0\.', True
258 )
259
260
261 @check("eol-in-paths", "end-of-lines in paths")
262 def has_eol_in_paths():
263 try:
264 fd, path = tempfile.mkstemp(dir='.', prefix=tempprefix, suffix='\n\r')
265 os.close(fd)
266 os.remove(path)
267 return True
268 except OSError:
269 return False
270
271
272 @check("execbit", "executable bit")
273 def has_executablebit():
274 try:
275 EXECFLAGS = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
276 fh, fn = tempfile.mkstemp(dir='.', prefix=tempprefix)
277 try:
278 os.close(fh)
279 m = os.stat(fn).st_mode & 0o777
280 new_file_has_exec = m & EXECFLAGS
281 os.chmod(fn, m ^ EXECFLAGS)
282 exec_flags_cannot_flip = (os.stat(fn).st_mode & 0o777) == m
283 finally:
284 os.unlink(fn)
285 except OSError:
286 # we don't care, the user probably won't be able to commit anyway
287 return False
288 return not (new_file_has_exec or exec_flags_cannot_flip)
289
290
291 @check("suidbit", "setuid and setgid bit")
292 def has_suidbit():
293 if (
294 getattr(os, "statvfs", None) is None
295 or getattr(os, "ST_NOSUID", None) is None
296 ):
297 return False
298 return bool(os.statvfs('.').f_flag & os.ST_NOSUID)
299
300
301 @check("icasefs", "case insensitive file system")
302 def has_icasefs():
303 # Stolen from mercurial.util
304 fd, path = tempfile.mkstemp(dir='.', prefix=tempprefix)
305 os.close(fd)
306 try:
307 s1 = os.stat(path)
308 d, b = os.path.split(path)
309 p2 = os.path.join(d, b.upper())
310 if path == p2:
311 p2 = os.path.join(d, b.lower())
312 try:
313 s2 = os.stat(p2)
314 return s2 == s1
315 except OSError:
316 return False
317 finally:
318 os.remove(path)
319
320
321 @check("fifo", "named pipes")
322 def has_fifo():
323 if getattr(os, "mkfifo", None) is None:
324 return False
325 name = tempfile.mktemp(dir='.', prefix=tempprefix)
326 try:
327 os.mkfifo(name)
328 os.unlink(name)
329 return True
330 except OSError:
331 return False
332
333
334 @check("killdaemons", 'killdaemons.py support')
335 def has_killdaemons():
336 return True
337
338
339 @check("cacheable", "cacheable filesystem")
340 def has_cacheable_fs():
341 from mercurial import util
342
343 fd, path = tempfile.mkstemp(dir='.', prefix=tempprefix)
344 os.close(fd)
345 try:
346 return util.cachestat(_sys2bytes(path)).cacheable()
347 finally:
348 os.remove(path)
349
350
351 @check("lsprof", "python lsprof module")
352 def has_lsprof():
353 try:
354 import _lsprof
355
356 del _lsprof # silence unused import warning
357 return True
358 except ImportError:
359 return False
360
361
362 def _gethgversion():
363 m = matchoutput('hg --version --quiet 2>&1', br'(\d+)\.(\d+)')
364 if not m:
365 return 0, 0
366 return int(m.group(1)), int(m.group(2))
367
368
369 _hgversion = None
370
371
372 def gethgversion():
373 global _hgversion
374 if _hgversion is None:
375 _hgversion = _gethgversion()
376 return _hgversion
377
378
379 @checkvers(
380 "hg", "Mercurial >= %s", ['%d.%d' % divmod(x, 10) for x in range(9, 99)]
381 )
382 def has_hg_range(v):
383 major, minor = v.split('.')[0:2]
384 return gethgversion() >= (int(major), int(minor))
385
386
387 @check("rust", "Using the Rust extensions")
388 def has_rust():
389 """Check is the mercurial currently running is using some rust code"""
390 cmd = 'hg debuginstall --quiet 2>&1'
391 match = br'checking module policy \(([^)]+)\)'
392 policy = matchoutput(cmd, match)
393 if not policy:
394 return False
395 return b'rust' in policy.group(1)
396
397
398 @check("hg08", "Mercurial >= 0.8")
399 def has_hg08():
400 if checks["hg09"][0]():
401 return True
402 return matchoutput('hg help annotate 2>&1', b'--date')
403
404
405 @check("hg07", "Mercurial >= 0.7")
406 def has_hg07():
407 if checks["hg08"][0]():
408 return True
409 return matchoutput(
410 'hg --version --quiet 2>&1', b'Mercurial Distributed SCM'
411 )
412
413
414 @check("hg06", "Mercurial >= 0.6")
415 def has_hg06():
416 if checks["hg07"][0]():
417 return True
418 return matchoutput('hg --version --quiet 2>&1', b'Mercurial version')
419
420
421 @check("gettext", "GNU Gettext (msgfmt)")
422 def has_gettext():
423 return matchoutput('msgfmt --version', br'GNU gettext-tools')
424
425
426 @check("git", "git command line client")
427 def has_git():
428 return matchoutput('git --version 2>&1', br'^git version')
429
430
431 def getgitversion():
432 m = matchoutput('git --version 2>&1', br'git version (\d+)\.(\d+)')
433 if not m:
434 return 0, 0
435 return int(m.group(1)), int(m.group(2))
436
437
438 @check("pygit2", "pygit2 Python library")
439 def has_pygit2():
440 try:
441 import pygit2
442
443 del pygit2 # silence unused import
444 return True
445 except ImportError:
446 return False
447
448
449 # https://github.com/git-lfs/lfs-test-server
450 @check("lfs-test-server", "git-lfs test server")
451 def has_lfsserver():
452 return has_cmd('lfs-test-server')
453
454
455 @checkvers("git", "git client (with ext::sh support) version >= %s", ('1.9',))
456 def has_git_range(v):
457 major, minor = v.split('.')[0:2]
458 return getgitversion() >= (int(major), int(minor))
459
460
461 @check("docutils", "Docutils text processing library")
462 def has_docutils():
463 try:
464 import docutils.core
465
466 del docutils.core # silence unused import
467 return True
468 except ImportError:
469 return False
470
471
472 def getsvnversion():
473 m = matchoutput('svn --version --quiet 2>&1', br'^(\d+)\.(\d+)')
474 if not m:
475 return 0, 0
476 return int(m.group(1)), int(m.group(2))
477
478
479 @checkvers("svn", "subversion client and admin tools >= %s", ('1.3', '1.5'))
480 def has_svn_range(v):
481 major, minor = v.split('.')[0:2]
482 return getsvnversion() >= (int(major), int(minor))
483
484
485 @check("svn", "subversion client and admin tools")
486 def has_svn():
487 return matchoutput('svn --version 2>&1', br'^svn, version') and matchoutput(
488 'svnadmin --version 2>&1', br'^svnadmin, version'
489 )
490
491
492 @check("svn-bindings", "subversion python bindings")
493 def has_svn_bindings():
494 try:
495 import svn.core
496
497 version = svn.core.SVN_VER_MAJOR, svn.core.SVN_VER_MINOR
498 if version < (1, 4):
499 return False
500 return True
501 except ImportError:
502 return False
503
504
505 @check("p4", "Perforce server and client")
506 def has_p4():
507 return matchoutput('p4 -V', br'Rev\. P4/') and matchoutput(
508 'p4d -V', br'Rev\. P4D/'
509 )
510
511
512 @check("symlink", "symbolic links")
513 def has_symlink():
514 # mercurial.windows.checklink() is a hard 'no' at the moment
515 if os.name == 'nt' or getattr(os, "symlink", None) is None:
516 return False
517 name = tempfile.mktemp(dir='.', prefix=tempprefix)
518 try:
519 os.symlink(".", name)
520 os.unlink(name)
521 return True
522 except (OSError, AttributeError):
523 return False
524
525
526 @check("hardlink", "hardlinks")
527 def has_hardlink():
528 from mercurial import util
529
530 fh, fn = tempfile.mkstemp(dir='.', prefix=tempprefix)
531 os.close(fh)
532 name = tempfile.mktemp(dir='.', prefix=tempprefix)
533 try:
534 util.oslink(_sys2bytes(fn), _sys2bytes(name))
535 os.unlink(name)
536 return True
537 except OSError:
538 return False
539 finally:
540 os.unlink(fn)
541
542
543 @check("hardlink-whitelisted", "hardlinks on whitelisted filesystems")
544 def has_hardlink_whitelisted():
545 from mercurial import util
546
547 try:
548 fstype = util.getfstype(b'.')
549 except OSError:
550 return False
551 return fstype in util._hardlinkfswhitelist
552
553
554 @check("rmcwd", "can remove current working directory")
555 def has_rmcwd():
556 ocwd = os.getcwd()
557 temp = tempfile.mkdtemp(dir='.', prefix=tempprefix)
558 try:
559 os.chdir(temp)
560 # On Linux, 'rmdir .' isn't allowed, but the other names are okay.
561 # On Solaris and Windows, the cwd can't be removed by any names.
562 os.rmdir(os.getcwd())
563 return True
564 except OSError:
565 return False
566 finally:
567 os.chdir(ocwd)
568 # clean up temp dir on platforms where cwd can't be removed
569 try:
570 os.rmdir(temp)
571 except OSError:
572 pass
573
574
575 @check("tla", "GNU Arch tla client")
576 def has_tla():
577 return matchoutput('tla --version 2>&1', br'The GNU Arch Revision')
578
579
580 @check("gpg", "gpg client")
581 def has_gpg():
582 return matchoutput('gpg --version 2>&1', br'GnuPG')
583
584
585 @check("gpg2", "gpg client v2")
586 def has_gpg2():
587 return matchoutput('gpg --version 2>&1', br'GnuPG[^0-9]+2\.')
588
589
590 @check("gpg21", "gpg client v2.1+")
591 def has_gpg21():
592 return matchoutput('gpg --version 2>&1', br'GnuPG[^0-9]+2\.(?!0)')
593
594
595 @check("unix-permissions", "unix-style permissions")
596 def has_unix_permissions():
597 d = tempfile.mkdtemp(dir='.', prefix=tempprefix)
598 try:
599 fname = os.path.join(d, 'foo')
600 for umask in (0o77, 0o07, 0o22):
601 os.umask(umask)
602 f = open(fname, 'w')
603 f.close()
604 mode = os.stat(fname).st_mode
605 os.unlink(fname)
606 if mode & 0o777 != ~umask & 0o666:
607 return False
608 return True
609 finally:
610 os.rmdir(d)
611
612
613 @check("unix-socket", "AF_UNIX socket family")
614 def has_unix_socket():
615 return getattr(socket, 'AF_UNIX', None) is not None
616
617
618 @check("root", "root permissions")
619 def has_root():
620 return getattr(os, 'geteuid', None) and os.geteuid() == 0
621
622
623 @check("pyflakes", "Pyflakes python linter")
624 def has_pyflakes():
625 return matchoutput("pyflakes --version", br"^\d+\.\d+\.\d+\b", True)
626
627
628 @check("pylint", "Pylint python linter")
629 def has_pylint():
630 return matchoutput("pylint --help", br"[Uu]sage:[ ]+pylint", True)
631
632
633 @check("clang-format", "clang-format C code formatter (11 <= ... < 19)")
634 def has_clang_format():
635 m = matchoutput('clang-format --version', br'clang-format version (\d+)')
636 # style changed somewhere between 10.x and 11.x and after 19.
637 if m:
638 major_version = int(m.group(1))
639 return 11 <= major_version < 19
640 # Assist Googler contributors, they have a centrally-maintained version of
641 # clang-format that is generally very fresh, but unlike most builds (both
642 # official and unofficial), it does *not* include a version number.
643 return matchoutput(
644 'clang-format --version', br'clang-format .*google3-trunk \([0-9a-f]+\)'
645 )
646
647
648 @check("jshint", "JSHint static code analysis tool")
649 def has_jshint():
650 return matchoutput("jshint --version 2>&1", br"jshint v")
651
652
653 @check("pygments", "Pygments source highlighting library")
654 def has_pygments():
655 try:
656 import pygments
657
658 del pygments # silence unused import warning
659 return True
660 except ImportError:
661 return False
662
663
664 def getpygmentsversion():
665 try:
666 import pygments
667
668 v = pygments.__version__
669
670 parts = v.split(".")
671 return int(parts[0]), int(parts[1])
672 except ImportError:
673 return 0, 0
674
675
676 @checkvers(
677 "pygments", "Pygments version >= %s", ('2.5', '2.11', '2.14', '2.19')
678 )
679 def has_pygments_range(v):
680 major, minor = v.split('.')[0:2]
681 return getpygmentsversion() >= (int(major), int(minor))
682
683
684 @check("outer-repo", "outer repo")
685 def has_outer_repo():
686 # failing for other reasons than 'no repo' imply that there is a repo
687 return not matchoutput('hg root 2>&1', br'abort: no repository found', True)
688
689
690 @check("ssl", "ssl module available")
691 def has_ssl():
692 try:
693 import ssl
694
695 del ssl
696 return True
697 except ImportError:
698 return False
699
700
701 @check("defaultcacertsloaded", "detected presence of loaded system CA certs")
702 def has_defaultcacertsloaded():
703 import ssl
704 from mercurial import sslutil, ui as uimod
705
706 ui = uimod.ui.load()
707 cafile = sslutil._defaultcacerts(ui)
708 ctx = ssl.create_default_context()
709 if cafile:
710 ctx.load_verify_locations(cafile=cafile)
711 else:
712 ctx.load_default_certs()
713
714 return len(ctx.get_ca_certs()) > 0
715
716
717 @check("tls1.2", "TLS 1.2 protocol support")
718 def has_tls1_2():
719 from mercurial import sslutil
720
721 return b'tls1.2' in sslutil.supportedprotocols
722
723
724 @check("tls1.3", "TLS 1.3 protocol support")
725 def has_tls1_3():
726 from mercurial import sslutil
727
728 return b'tls1.3' in sslutil.supportedprotocols
729
730
731 @check("windows", "Windows")
732 def has_windows():
733 return os.name == 'nt'
734
735
736 @check("windows10", "Windows 10")
737 def has_windows10():
738 # platform.win32_ver()[0] == '10' would be a better check, but doesn't
739 # return 11 on Windows 11 until Python 3.12(.7?).
740 if os.name != 'nt':
741 return False
742
743 vers = platform.win32_ver()[1].split('.')
744 if len(vers) == 3:
745 # Windows 11 build numbers start at 22000
746 return int(vers[2]) < 22000
747
748 return False
749
750
751 @check("system-sh", "system() uses sh")
752 def has_system_sh():
753 return os.name != 'nt'
754
755
756 @check("serve", "platform and python can manage 'hg serve -d'")
757 def has_serve():
758 return True
759
760
761 @check("setprocname", "whether osutil.setprocname is available or not")
762 def has_setprocname():
763 try:
764 from mercurial.utils import procutil
765
766 procutil.setprocname
767 return True
768 except AttributeError:
769 return False
770
771
772 @check("gui", "whether a gui environment is available or not")
773 def has_gui():
774 from mercurial.utils import procutil
775
776 return procutil.gui()
777
778
779 @check("test-repo", "running tests from repository")
780 def has_test_repo():
781 t = os.environ["TESTDIR"]
782 return os.path.isdir(os.path.join(t, "..", ".hg"))
783
784
785 @check("network-io", "whether tests are allowed to access 3rd party services")
786 def has_network_io():
787 t = os.environ.get("HGTESTS_ALLOW_NETIO")
788 return t == "1"
789
790
791 @check("curses", "terminfo compiler and curses module")
792 def has_curses():
793 try:
794 import curses
795
796 del curses
797
798 # Windows doesn't have a `tic` executable, but the windows_curses
799 # package is sufficient to run the tests without it.
800 if os.name == 'nt':
801 return True
802
803 return has_tic()
804
805 except (ImportError, AttributeError):
806 return False
807
808
809 @check("tic", "terminfo compiler")
810 def has_tic():
811 return has_cmd('tic')
812
813
814 @check("xz", "xz compression utility")
815 def has_xz():
816 return has_cmd('xz')
817
818
819 @check("msys", "Windows with MSYS")
820 def has_msys():
821 return os.getenv('MSYSTEM')
822
823
824 @check("aix", "AIX")
825 def has_aix():
826 return sys.platform.startswith("aix")
827
828
829 @check("osx", "OS X")
830 def has_osx():
831 return sys.platform == 'darwin'
832
833
834 @check("osxpackaging", "OS X packaging tools")
835 def has_osxpackaging():
836 try:
837 return (
838 matchoutput('pkgbuild', br'Usage: pkgbuild ', ignorestatus=True)
839 and matchoutput(
840 'productbuild', br'Usage: productbuild ', ignorestatus=True
841 )
842 and matchoutput('lsbom', br'Usage: lsbom', ignorestatus=True)
843 and matchoutput('xar --help', br'Usage: xar', ignorestatus=True)
844 )
845 except ImportError:
846 return False
847
848
849 @check('linuxormacos', 'Linux or MacOS')
850 def has_linuxormacos():
851 # This isn't a perfect test for MacOS. But it is sufficient for our needs.
852 return sys.platform.startswith(('linux', 'darwin'))
853
854
855 @check("docker", "docker support")
856 def has_docker():
857 pat = br'A self-sufficient runtime for'
858 if matchoutput('docker --help', pat):
859 if 'linux' not in sys.platform:
860 # TODO: in theory we should be able to test docker-based
861 # package creation on non-linux using boot2docker, but in
862 # practice that requires extra coordination to make sure
863 # $TESTTEMP is going to be visible at the same path to the
864 # boot2docker VM. If we figure out how to verify that, we
865 # can use the following instead of just saying False:
866 # return 'DOCKER_HOST' in os.environ
867 return False
868
869 return True
870 return False
871
872
873 @check("debhelper", "debian packaging tools")
874 def has_debhelper():
875 # Some versions of dpkg say `dpkg', some say 'dpkg' (` vs ' on the first
876 # quote), so just accept anything in that spot.
877 dpkg = matchoutput(
878 'dpkg --version', br"Debian .dpkg' package management program"
879 )
880 dh = matchoutput(
881 'dh --help', br'dh is a part of debhelper.', ignorestatus=True
882 )
883 dh_py2 = matchoutput(
884 'dh_python2 --help', br'other supported Python versions'
885 )
886 # debuild comes from the 'devscripts' package, though you might want
887 # the 'build-debs' package instead, which has a dependency on devscripts.
888 debuild = matchoutput(
889 'debuild --help', br'to run debian/rules with given parameter'
890 )
891 return dpkg and dh and dh_py2 and debuild
892
893
894 @check(
895 "debdeps", "debian build dependencies (run dpkg-checkbuilddeps in contrib/)"
896 )
897 def has_debdeps():
898 # just check exit status (ignoring output)
899 path = '%s/../contrib/packaging/debian/control' % os.environ['TESTDIR']
900 return matchoutput('dpkg-checkbuilddeps %s' % path, br'')
901
902
903 @check("demandimport", "demandimport enabled")
904 def has_demandimport():
905 # chg disables demandimport intentionally for performance wins.
906 return (not has_chg()) and os.environ.get('HGDEMANDIMPORT') != 'disable'
907
908
909 # Add "py36", "py37", ... as possible feature checks. Note that there's no
910 # punctuation here.
911 @checkvers(
912 "py",
913 "Python >= %s",
914 ('3.6', '3.7', '3.8', '3.9', '3.10', '3.11', '3.12', '3.13'),
915 )
916 def has_python_range(v):
917 major, minor = v.split('.')[0:2]
918 py_major, py_minor = sys.version_info.major, sys.version_info.minor
919
920 return (py_major, py_minor) >= (int(major), int(minor))
921
922
923 @check("py3", "running with Python 3.x")
924 def has_py3():
925 return 3 == sys.version_info[0]
926
927
928 @check("py3exe", "a Python 3.x interpreter is available")
929 def has_python3exe():
930 py = 'python3'
931 if os.name == 'nt':
932 py = 'py -3'
933 return matchoutput('%s -V' % py, br'^Python 3.(6|7|8|9|1\d)')
934
935
936 @check("pure", "running with pure Python code")
937 def has_pure():
938 return any(
939 [
940 os.environ.get("HGMODULEPOLICY") == "py",
941 os.environ.get("HGTEST_RUN_TESTS_PURE") == "--pure",
942 ]
943 )
944
945
946 @check("slow", "allow slow tests (use --allow-slow-tests)")
947 def has_slow():
948 return os.environ.get('HGTEST_SLOW') == 'slow'
949
950
951 @check("hypothesis", "Hypothesis automated test generation")
952 def has_hypothesis():
953 try:
954 import hypothesis
955
956 del hypothesis
957 return True
958 except ImportError:
959 return False
960
961
962 @check("unziplinks", "unzip(1) understands and extracts symlinks")
963 def unzip_understands_symlinks():
964 return matchoutput('unzip --help', br'Info-ZIP')
965
966
967 @check("zstd", "zstd Python module available")
968 def has_zstd():
969 return matchoutput(
970 'hg debuginstall',
971 br'checking available compression engines.*zstd',
972 )
973
974
975 @check("devfull", "/dev/full special file")
976 def has_dev_full():
977 return os.path.exists('/dev/full')
978
979
980 @check("ensurepip", "ensurepip module")
981 def has_ensurepip():
982 try:
983 import ensurepip
984
985 del ensurepip
986 return True
987 except ImportError:
988 return False
989
990
991 @check("virtualenv", "virtualenv support")
992 def has_virtualenv():
993 try:
994 import virtualenv
995
996 # --no-site-package became the default in 1.7 (Nov 2011), and the
997 # argument was removed in 20.0 (Feb 2020). Rather than make the
998 # script complicated, just ignore ancient versions.
999 return int(virtualenv.__version__.split('.')[0]) > 1
1000 except (AttributeError, ImportError, IndexError):
1001 return False
1002
1003
1004 @check("fsmonitor", "running tests with fsmonitor")
1005 def has_fsmonitor():
1006 return 'HGFSMONITOR_TESTS' in os.environ
1007
1008
1009 @check("fuzzywuzzy", "Fuzzy string matching library")
1010 def has_fuzzywuzzy():
1011 try:
1012 import fuzzywuzzy
1013
1014 del fuzzywuzzy
1015 return True
1016 except ImportError:
1017 return False
1018
1019
1020 @check("clang-libfuzzer", "clang new enough to include libfuzzer")
1021 def has_clang_libfuzzer():
1022 mat = matchoutput('clang --version', br'clang version (\d)')
1023 if mat:
1024 # libfuzzer is new in clang 6
1025 return int(mat.group(1)) > 5
1026 return False
1027
1028
1029 @check("clang-6.0", "clang 6.0 with version suffix (libfuzzer included)")
1030 def has_clang60():
1031 return matchoutput('clang-6.0 --version', br'clang version 6\.')
1032
1033
1034 @check("xdiff", "xdiff algorithm")
1035 def has_xdiff():
1036 try:
1037 from mercurial import policy
1038
1039 bdiff = policy.importmod('bdiff')
1040 return bdiff.xdiffblocks(b'', b'') == [(0, 0, 0, 0)]
1041 except (ImportError, AttributeError):
1042 return False
1043
1044
1045 @check('extraextensions', 'whether tests are running with extra extensions')
1046 def has_extraextensions():
1047 return 'HGTESTEXTRAEXTENSIONS' in os.environ
1048
1049
1050 @check('dirstate-v2', 'using the v2 format of .hg/dirstate')
1051 def has_dirstate_v2():
1052 # Keep this logic in sync with `new_repo_requirements()` in `mercurial/repo/creation.py`
1053 return matchoutput(
1054 'hg config format.use-dirstate-v2', b'(?i)1|yes|true|on|always'
1055 )
1056
1057
1058 @check('sqlite', 'sqlite3 module and matching cli is available')
1059 def has_sqlite():
1060 try:
1061 import sqlite3
1062
1063 version = sqlite3.sqlite_version_info
1064 except ImportError:
1065 return False
1066
1067 if version < (3, 8, 3):
1068 # WITH clause not supported
1069 return False
1070
1071 return matchoutput('sqlite3 -version', br'^3\.\d+')
1072
1073
1074 @check('vcr', 'vcr http mocking library (pytest-vcr)')
1075 def has_vcr():
1076 try:
1077 import vcr
1078
1079 del vcr
1080 return True
1081 except (ImportError, AttributeError):
1082 pass
1083 return False
1084
1085
1086 @check('emacs', 'GNU Emacs')
1087 def has_emacs():
1088 # Our emacs lisp uses `with-eval-after-load` which is new in emacs
1089 # 24.4, so we allow emacs 24.4, 24.5, and 25+ (24.5 was the last
1090 # 24 release)
1091 return matchoutput(
1092 'emacs --version', br'GNU Emacs (3\d|2(4.4|4.5|5|6|7|8|9))'
1093 )
1094
1095
1096 @check(
1097 'black', 'the black formatter for python (version set in pyproject.toml)'
1098 )
1099 def has_black():
1100 env = environ()
1101
1102 # The top level #require statements are evaluated from $TESTTMP, and won't
1103 # see the project level pyproject.toml unless executing from the project
1104 # directory.
1105 cwd = os.getcwd()
1106 if 'RUNTESTDIR' in env:
1107 cwd = os.path.realpath(f"{env['RUNTESTDIR']}/..")
1108
1109 try:
1110 p = subprocess.run(
1111 ['black', '--check', '-'],
1112 input=b"# test\n",
1113 cwd=cwd,
1114 env=env,
1115 )
1116 except FileNotFoundError:
1117 return False
1118
1119 return p.returncode == 0
1120
1121
1122 @check('pytype', 'the pytype type checker at version 2024.10.11')
1123 def has_pytype():
1124 pytypecmd = 'pytype --version'
1125 version = matchoutput(pytypecmd, b'[0-9a-b.]+')
1126 if not version:
1127 return False
1128 return version.group(0) == b"2024.10.11"
1129
1130
1131 @check("rustfmt", "rustfmt tool at version nightly-2024-07-16")
1132 def has_rustfmt():
1133 # We use Nightly's rustfmt due to current unstable config options.
1134 return matchoutput(
1135 '`rustup which --toolchain nightly-2024-07-16 rustfmt` --version',
1136 b'rustfmt',
1137 )
1138
1139
1140 @check("cargo", "cargo tool")
1141 def has_cargo():
1142 return matchoutput('`rustup which cargo` --version', b'cargo')
1143
1144
1145 @check("lzma", "python lzma module")
1146 def has_lzma():
1147 try:
1148 import _lzma
1149
1150 del _lzma
1151 return True
1152 except ImportError:
1153 return False
1154
1155
1156 @check("bash", "bash shell")
1157 def has_bash():
1158 return matchoutput("bash -c 'echo hi'", b'^hi$')
1159
1160
1161 @check("bigendian", "big-endian CPU")
1162 def has_bigendian():
1163 return sys.byteorder == 'big'
1164
1165
1166 @check("python-local-coerce", "Python use local coercion")
1167 def python_coercion():
1168 return matchoutput(
1169 "unset LC_ALL; unset LANG; LC_CTYPE= ;"
1170 " $PYTHON -c \"import os; print(os.environ.get('LC_CTYPE',"
1171 " '__NO_COERCES__'))\"",
1172 b'^C.UTF-8$',
1173 )