1from __future__ import absolute_import
2
3import array
4import errno
5import fcntl
6import os
7import sys
8
9from .pycompat import getattr
10from . import (
11    encoding,
12    pycompat,
13    util,
14)
15
16# BSD 'more' escapes ANSI color sequences by default. This can be disabled by
17# $MORE variable, but there's no compatible option with Linux 'more'. Given
18# OS X is widely used and most modern Unix systems would have 'less', setting
19# 'less' as the default seems reasonable.
20fallbackpager = b'less'
21
22
23def _rcfiles(path):
24    rcs = [os.path.join(path, b'hgrc')]
25    rcdir = os.path.join(path, b'hgrc.d')
26    try:
27        rcs.extend(
28            [
29                os.path.join(rcdir, f)
30                for f, kind in sorted(util.listdir(rcdir))
31                if f.endswith(b".rc")
32            ]
33        )
34    except OSError:
35        pass
36    return rcs
37
38
39def systemrcpath():
40    path = []
41    if pycompat.sysplatform == b'plan9':
42        root = b'lib/mercurial'
43    else:
44        root = b'etc/mercurial'
45    # old mod_python does not set sys.argv
46    if len(getattr(sys, 'argv', [])) > 0:
47        p = os.path.dirname(os.path.dirname(pycompat.sysargv[0]))
48        if p != b'/':
49            path.extend(_rcfiles(os.path.join(p, root)))
50    path.extend(_rcfiles(b'/' + root))
51    return path
52
53
54def userrcpath():
55    if pycompat.sysplatform == b'plan9':
56        return [encoding.environ[b'home'] + b'/lib/hgrc']
57    elif pycompat.isdarwin:
58        return [os.path.expanduser(b'~/.hgrc')]
59    else:
60        confighome = encoding.environ.get(b'XDG_CONFIG_HOME')
61        if confighome is None or not os.path.isabs(confighome):
62            confighome = os.path.expanduser(b'~/.config')
63
64        return [
65            os.path.expanduser(b'~/.hgrc'),
66            os.path.join(confighome, b'hg', b'hgrc'),
67        ]
68
69
70def termsize(ui):
71    try:
72        import termios
73
74        TIOCGWINSZ = termios.TIOCGWINSZ  # unavailable on IRIX (issue3449)
75    except (AttributeError, ImportError):
76        return 80, 24
77
78    for dev in (ui.ferr, ui.fout, ui.fin):
79        try:
80            try:
81                fd = dev.fileno()
82            except AttributeError:
83                continue
84            if not os.isatty(fd):
85                continue
86            arri = fcntl.ioctl(fd, TIOCGWINSZ, b'\0' * 8)
87            height, width = array.array('h', arri)[:2]
88            if width > 0 and height > 0:
89                return width, height
90        except ValueError:
91            pass
92        except IOError as e:
93            if e[0] == errno.EINVAL:  # pytype: disable=unsupported-operands
94                pass
95            else:
96                raise
97    return 80, 24
98