1from ..i18n import _
2from .. import error
3
4
5def get_checker(ui, revlog_name=b'changelog'):
6    """Get a function that checks file handle position is as expected.
7
8    This is used to ensure that files haven't been modified outside of our
9    knowledge (such as on a networked filesystem, if `hg debuglocks` was used,
10    or writes to .hg that ignored locks happened).
11
12    Due to revlogs supporting a concept of buffered, delayed, or diverted
13    writes, we're allowing the files to be shorter than expected (the data may
14    not have been written yet), but they can't be longer.
15
16    Please note that this check is not perfect; it can't detect all cases (there
17    may be false-negatives/false-OKs), but it should never claim there's an
18    issue when there isn't (false-positives/false-failures).
19    """
20
21    vpos = ui.config(b'debug', b'revlog.verifyposition.' + revlog_name)
22    # Avoid any `fh.tell` cost if this isn't enabled.
23    if not vpos or vpos not in [b'log', b'warn', b'fail']:
24        return None
25
26    def _checker(fh, fn, expected):
27        if fh.tell() <= expected:
28            return
29
30        msg = _(b'%s: file cursor at position %d, expected %d')
31        # Always log if we're going to warn or fail.
32        ui.log(b'debug', msg + b'\n', fn, fh.tell(), expected)
33        if vpos == b'warn':
34            ui.warn((msg + b'\n') % (fn, fh.tell(), expected))
35        elif vpos == b'fail':
36            raise error.RevlogError(msg % (fn, fh.tell(), expected))
37
38    return _checker
39