This instance will be upgraded to Heptapod 0.21.0rc2 on 2021-04-16 at 11:00 UTC+2 (a few minutes of down time)

helpers.py 19.1 KB
Newer Older
1
"""Helper functions or classes imported from test case"""
Yuya Nishihara's avatar
Yuya Nishihara committed
2 3 4 5 6 7 8 9

from __future__ import absolute_import

import os
import re
import sys
import tempfile
import time
10
from collections import defaultdict
11 12 13 14

from mercurial import (
    pycompat,
)
Yuya Nishihara's avatar
Yuya Nishihara committed
15

16
from nose import tools
Yuya Nishihara's avatar
Yuya Nishihara committed
17 18 19 20 21 22 23 24

from tortoisehg.hgqt.qtcore import (
    QTextCodec,
)

from mercurial import (
    dispatch,
    encoding as encodingmod,
25
    error,
26
    pycompat,
Yuya Nishihara's avatar
Yuya Nishihara committed
27 28
)

29
from tortoisehg.util import hglib
30 31 32 33

def mktmpdir(prefix):
    """Create temporary directory under HGTMP"""
    return tempfile.mkdtemp('', prefix, os.environ['HGTMP'])
34

35 36 37 38 39
def guessmtimedelay(dir):
    """Guess resolution of mtime to return delay necessary to notice change"""
    fd, path = tempfile.mkstemp(prefix='mtime-', dir=dir)
    try:
        lastmtime = os.fstat(fd).st_mtime
40
        for _i in pycompat.xrange(2):
41 42 43 44 45 46 47 48 49 50 51 52 53 54
            time.sleep(0.01)
            os.utime(path, None)
            mtime = os.fstat(fd).st_mtime
            if lastmtime >= mtime:
                if os.name == 'nt':
                    return 2  # assume fat
                else:
                    return 1  # assume ext3
            lastmtime = mtime
        return 0  # ext4, ufs, ntfs, ...
    finally:
        os.close(fd)
        os.unlink(path)

55 56 57 58 59 60 61
class EncodingPatcher(object):
    """Temporarily change locale encoding"""

    def __init__(self, encoding, fallbackencoding=None):
        self._newencoding = encoding
        self._newfallbackencoding = fallbackencoding or encoding
        self._patched = False
62

63 64 65
    def patch(self):
        if self._patched:
            raise Exception('encoding already patched')
66 67 68
        self._origenvencoding = os.environ.get('HGENCODING')
        self._origencoding = encodingmod.encoding
        self._origfallbackencoding = encodingmod.fallbackencoding
69 70
        self._orighglibencoding = hglib._encoding
        self._orighglibfallbackencoding = hglib._fallbackencoding
71 72 73 74 75
        self._origqtextcodec = QTextCodec.codecForLocale()

        os.environ['HGENCODING'] = self._newencoding
        encodingmod.encoding = self._newencoding
        encodingmod.fallbackencoding = self._newfallbackencoding
76 77
        hglib._encoding = self._newencoding
        hglib._fallbackencoding = self._newfallbackencoding
78 79
        QTextCodec.setCodecForLocale(
            QTextCodec.codecForName(self._newencoding))
80
        self._patched = True
81

82 83 84
    def restore(self):
        if not self._patched:
            raise Exception('encoding not patched')
85 86 87 88
        if self._origenvencoding is not None:
            os.environ['HGENCODING'] = self._origenvencoding
        encodingmod.encoding = self._origencoding
        encodingmod.fallbackencoding = self._origfallbackencoding
89 90
        hglib._encoding = self._orighglibencoding
        hglib._fallbackencoding = self._orighglibfallbackencoding
91
        QTextCodec.setCodecForLocale(self._origqtextcodec)
92
        self._patched = False
93

94 95 96 97 98 99 100 101 102 103 104
def patchencoding(encoding, fallbackencoding=None):
    """Change locale encoding and return object to restore"""
    patcher = EncodingPatcher(encoding, fallbackencoding)
    patcher.patch()
    return patcher

# TODO: make this usable for unittest.TestCase?
def with_encoding(encoding, fallbackencoding=None):
    """Decorator for test function to change locale encoding temporarily"""
    patcher = EncodingPatcher(encoding, fallbackencoding)
    return tools.with_setup(patcher.patch, patcher.restore)
105 106 107 108 109 110

class HgClient(object):
    """Mercurial client to set up fixture repository

    >>> hg = HgClient('/tmp/foo')
    >>> def dummydispatch(args):
111
    ...     print(' '.join(['hg'] + list(args)))
112
    >>> hg._dispatch = dummydispatch
113 114 115 116 117 118
    >>> if os.name == 'nt':
    ...     hg.path = hg.path[2:].replace(os.sep, '/')
    ...     _wjoin = hg.wjoin
    ...     def wjoin(path):
    ...         return _wjoin(path).replace(os.sep, '/')
    ...     hg.wjoin = wjoin
119 120 121 122 123 124 125 126

    >>> hg.init()
    hg init /tmp/foo/
    >>> hg.add('bar')
    hg add --cwd /tmp/foo bar
    >>> hg.commit('-m', 'add bar')
    hg commit --cwd /tmp/foo -m add bar

127
    >>> hg.wjoin(b'bar/baz')
128
    '/tmp/foo/bar/baz'
129
    >>> hg.wjoin(b'/absolute/path')
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
    Traceback (most recent call last):
      ...
    ValueError: not a relative path: /absolute/path
    """

    def __init__(self, path):
        self.path = os.path.abspath(path)

    def init(self, dest=None):
        """Create a new repository"""
        return self._dispatch(('init', self.wjoin(dest or '')))

    def __getattr__(self, name):
        """Return accessor for arbitrary Mercurial command"""
        def cmd(*args):
            return self._dispatch((name, '--cwd', self.path) + args)
146
        cmd.__name__ = name
147 148 149 150 151
        return cmd

    def _dispatch(self, args):
        # TODO: use hglib in order to avoid pollution of global space?
        origwd = os.getcwd()
152
        ui = hglib.loadui()
153
        ui.setconfig(b'ui', b'strict', True)
154 155
        ui.fout = pycompat.bytesio()
        ui.ferr = pycompat.bytesio()
156 157
        args = list(args)
        req = dispatch.request(args, ui=ui)
158 159 160 161 162 163 164 165 166 167 168 169 170 171
        if hasattr(req, 'earlyoptions'):
            try:
                # hg>=4.5: parse early options at once
                options = dispatch._earlyparseopts(ui, args)
            except (AttributeError, TypeError):
                # hg>=4.4.2: early options must be kept in args
                options = {
                    'config': dispatch._earlygetopt(['--config'], args[:]),
                    'debugger': None,
                }
            req.earlyoptions.update(options)
            dispatch._parseconfig(ui, req.earlyoptions['config'])
        else:
            # hg<4.4.2: early options must be stripped
172
            dispatch._parseconfig(ui, dispatch._earlygetopt(['--config'], args))
173 174 175 176 177 178 179 180 181
        try:
            result = dispatch._dispatch(req) or 0
            return result, ui.fout.getvalue(), ui.ferr.getvalue()
        finally:
            os.chdir(origwd)

    def ftouch(self, *paths):
        """Create empty file inside the repository"""
        for e in paths:
182
            self.fwrite(e, '')
183

184 185 186 187 188
    def _fwrite(self, path, content, flag):
        fullpath = self.wjoin(path)
        if not os.path.exists(os.path.dirname(fullpath)):
            os.makedirs(os.path.dirname(fullpath))
        f = open(fullpath, flag)
189 190 191 192 193
        try:
            f.write(content)
        finally:
            f.close()

194 195 196 197
    def fwrite(self, path, content):
        """Write the given content to file"""
        self._fwrite(path, content, 'wb')

198 199
    def fappend(self, path, content):
        """Append the given content to file"""
200
        self._fwrite(path, content, 'ab')
201 202 203 204 205 206 207 208 209 210 211 212 213

    def fread(self, path):
        """Read content of file"""
        f = open(self.wjoin(path), 'rb')
        try:
            return f.read()
        finally:
            f.close()

    def wjoin(self, path):
        if path.startswith('/'):
            raise ValueError('not a relative path: %s' % path)
        return os.path.join(self.path, path)
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255


class InvalidGraph(Exception):
    def __init__(self, lines, lineno, msg):
        graph = []
        for i, line in enumerate(lines):
            if i == lineno:
                graph.append(line + ' << [NG]')
            else:
                graph.append(line)
        graphtext = '\n'.join(reversed(graph))
        Exception.__init__(self, 'Invalid graph:\n' + graphtext + '\n' + msg)
        self.lines = list(reversed(lines))
        self.errorline = len(lines) - 1 - lineno
        self.innermessage = msg


class InvalidGraphLine(Exception):
    pass


class GraphBuilder(object):
    _re_graphline = re.compile(r"""^
                (?P<graph>[ o0-9|/\\+\-]*)       #graph
                (\s*\[(?P<params>[^#]+)\]\s*)?   #params
                (\#(?P<comment>.*))?             #comment
                $""", re.VERBOSE)

    _re_branchparams = re.compile(r"""
                ([0-9a-z_/:\-]+)                    # key
                \s*=\s*                             # =
                (?:"([^"]*)"|'([^']*)'|([^\s='"]*)) # value
                """, re.I | re.VERBOSE)

    DUMMYFILE = '.dummy'

    def __init__(self, path, textgraph):
        textgraph = textgraph.strip('\n')
        self.lines = [l.rstrip() for l in reversed(textgraph.split('\n'))]
        self.hg = HgClient(path)
        self.hg.init()
        self.hg.fappend('.hgignore', 'syntax: glob\n*.orig\n')
256 257 258
        # to use "hg debugobsolete" and suppress "obsolete feature not enabled"
        self.hg.fappend('.hg/hgrc',
                        '[experimental]\nevolution.createmarkers = 1\n')
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
        self._branchmap = {}

    def build(self):
        revs = defaultdict(list)
        prevline = ''
        tip = -1
        for i, line in enumerate(self.lines):
            try:
                m = self._re_graphline.match(line)
                if not m:
                    raise InvalidGraphLine('parse error')
                line = m.group('graph')
                if not line:
                    continue
                params = m.group('params')
                revs, tip = self._processline(line, params, prevline, revs, tip)
                prevline = line
276
            except InvalidGraphLine as ex:
277 278
                raise InvalidGraph(self.lines, i, str(ex)), \
                        None, sys.exc_info()[2]
279
            except error.Abort as ex:
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
                raise InvalidGraph(self.lines, i, "[Abort] %s" % ex), \
                        None, sys.exc_info()[2]

    @classmethod
    def _parseparams(cls, text):
        """
        parse branch parameters.
        return dict which may contain 'branch', 'user', and 'files'

        >>> _parseparams = GraphBuilder._parseparams
        >>> _parseparams('')
        {}
        >>> # branch
        >>> _parseparams('branch=foo')
        {'branch': 'foo'}
        >>> _parseparams('user=alice')
        {'user': 'alice'}
        >>> _parseparams('merge=local')
        {'merge': 'local'}
299 300
        >>> _parseparams('source=0')
        {'source': '0'}
301 302 303 304
        >>> _parseparams('files=foo/bar')
        {'files': ['foo/bar']}
        >>> _parseparams('files="foo,bar, baz"')
        {'files': ['foo', 'bar', 'baz']}
305 306
        >>> _parseparams('files="foo=>bar,baz=>"')
        {'files': ['foo=>bar', 'baz=>']}
307 308 309 310 311 312 313 314
        >>> ret = _parseparams('user=alice branch=foo files=bar')
        >>> sorted(ret.items())
        [('branch', 'foo'), ('files', ['bar']), ('user', 'alice')]
        """
        ret = {}
        if text:
            for k, v1, v2, v3 in cls._re_branchparams.findall(text):
                v = v1 or v2 or v3
315 316
                if k in ('files', 'precs'):
                    ret[k] = re.split(r',\s*', v)
317
                elif k in ('branch', 'user', 'merge', 'source'):
318
                    ret[k] = v
319 320
                else:
                    raise InvalidGraphLine('undefined param: %s' % k)
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
        return ret

    def _findhorizontaledgeroot(self, line, edgeend):
        """
        search index of horizontal edge root from revmark
          | +---o   horizontal edge root means '+' of left fig.
          | | |     revmark means 'o' of left fig.
        """
        roots = [i for (i, c) in enumerate(line) if c == '+']
        if len(roots) > 0:
            if len(roots) > 2:
                raise InvalidGraphLine('invalid horizontal edge')

            indices = roots + [edgeend]
            l, r = min(indices), max(indices)
336 337
            if any((l < i < r) != (c == '-') for (i, c) in enumerate(line)
                   if i not in indices):
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
                raise InvalidGraphLine('invalid horizontal edge')

        return roots

    def _processline(self, line, params, prevline, revs, tip):
        """process one line"""
        next_revs = defaultdict(list)
        committed = False

        iscommit = lambda c: c in 'o0123456789'

        visitededges = set()
        for i, c in sorted(enumerate(line), key=lambda x: iscommit(x[1])):
            parents = []
            if c in '|+-' or iscommit(c):
                parents += revs[i]
                visitededges.add(i)
                if 0 < i and i - 1 < len(prevline) and prevline[i - 1] == '/':
                    parents += revs[i - 1]
                    visitededges.add(i - 1)
                if i < len(prevline) - 1 and prevline[i + 1] == '\\':
                    parents += revs[i + 1]
                    visitededges.add(i + 1)

                if iscommit(c):
                    if committed:
                        raise InvalidGraphLine('2 or more rev in same line')
                    for root in self._findhorizontaledgeroot(line, i):
                        parents += next_revs[root]
                        visitededges.add(root)
                    if len(parents) > 2:
                        raise InvalidGraphLine('too many parents')

                    params = GraphBuilder._parseparams(params)
372
                    precs = params.pop('precs', [])
373 374 375 376
                    if params.get('source') is not None:
                        tip = self._graft(tip, parents, **params)
                    else:
                        tip = self._commit(tip, parents, **params)
377
                    parents = [tip]
378 379
                    if precs:
                        self._prune(precs, succ=[tip])
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
                    committed = True

            elif c == '/':
                parents += revs[i - 1]
                visitededges.add(i - 1)
                if i < len(prevline) and prevline[i] == '\\':
                    parents += revs[i]
                    visitededges.add(i)

            elif c == '\\':
                parents += revs[i + 1]
                visitededges.add(i + 1)
                if i < len(prevline) and prevline[i] == '/':
                    parents += revs[i]
                    visitededges.add(i)

            else:
                continue

            if not parents and c != '-' and tip >= 0:
                raise InvalidGraphLine('isolated edge')

            next_revs[i] = parents

        if (set(i for (i, c) in enumerate(prevline) if c in r'|\/')
            - visitededges):
            raise InvalidGraphLine('isolated edge')

        return next_revs, tip


    def _sortparents(self, parents, rev, branch):
        """move same branch parent first if branch specified explicitly"""
        bm = self._branchmap
        if branch:
            bm[rev] = branch
            parents.sort(key=lambda p: bm[p] != branch)
        else:
            if parents:
                bm[rev] = self._branchmap[parents[0]]
            else:
                bm[rev] = 'default'

423 424 425 426
    def _runcmd(self, cmd, *args):
            ret, fout, ferr = cmd(*args)
            if ret != 0:
                raise InvalidGraphLine(
427
                        '\n'.join(['failed to %s' % cmd.__name__, fout, ferr]))
428 429 430 431 432 433 434 435

    def _resolveall(self, p1, p2):
        unresolved = [x[2:] for x in self.hg.resolve('-l')[1].split('\n')
                      if x.startswith('U ')]
        for path in unresolved:
            self.hg.fwrite(path, '@%d+@%d' % (p1, p2))
        self._runcmd(self.hg.resolve, '-ma')

436
    def _commit(self, tip, parents, branch=None, user=None, files=None,
437 438
                merge=None, source=None):
        assert(source is None)
439 440
        if merge:
            if len(parents) < 2:
441 442
                raise InvalidGraphLine('`merge` can be specified to'
                                       ' merged or grafted revision')
443 444 445 446 447 448 449 450 451
            if merge not in ('local', 'other'):
                raise InvalidGraphLine(
                        'value of `merge` must be "local" or "other"')
        hg = self.hg

        nextrev = tip + 1
        self._sortparents(parents, nextrev, branch)

        if parents and tip != parents[0]:
452
            self._runcmd(hg.update, '-Cr', str(parents[0]))
453
        if branch:
454
            self._runcmd(hg.branch, branch, '-f')
455 456 457 458
        if len(parents) > 1:
            tool = 'internal:' + (merge or 'merge')
            ret = hg.merge('-r', str(parents[1]), '-t', tool)[0]
            if ret:
459
                self._resolveall(*parents)
460 461 462 463 464 465 466 467
        else:
            # change DUMMYFILE every commit
            hg.fwrite(self.DUMMYFILE, '@%d' % nextrev)
        if files:
            for path in files:
                if path == self.DUMMYFILE:
                    raise InvalidGraphLine(
                            'file:%s is used internally' % self.DUMMYFILE)
468 469 470 471 472 473 474 475
                paths = path.split('=>', 1)
                if len(paths) == 1:
                    hg.fwrite(path, '@%d' % nextrev)
                elif paths[1]:
                    hg.ftouch(paths[1])  # ensure leading directory existence
                    hg.move(paths[0], paths[1], '-f')
                else:
                    hg.remove(paths[0], '-f')
476 477

        user = user or 'alice'
478
        self._runcmd(hg.commit, '-Am', 'commit #%d' % nextrev, '-u', user)
479 480
        return nextrev

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
    def _graft(self, tip, parents, branch=None, user=None, files=None,
               merge=None, source=None):
        assert(source is not None)
        if merge and merge not in ('local', 'other'):
            raise InvalidGraphLine(
                    'value of `merge` must be "local" or "other"')
        try:
            if not (0 <= int(source) <= tip):
                raise InvalidGraphLine('`source` must point past revision')
        except ValueError:
            raise InvalidGraphLine('`source` must be integer')
        if files or branch:
            raise InvalidGraphLine('`files` and `branch` cannot be specified'
                                   ' with `source`')
        if len(parents) != 1:
            raise InvalidGraphLine('grafted revision must have only one parent')

        hg = self.hg

        nextrev = tip + 1
        self._branchmap[nextrev] = self._branchmap[parents[0]]

        if tip != parents[0]:
            self._runcmd(hg.update, '-Cr', str(parents[0]))
        tool = 'internal:' + (merge or 'merge')
        if user:
            uargs = ['-u', user]
        else:
            uargs = []
        try:
511
            ret = hg.graft('-r', source, '-t', tool, *uargs)[0]
512
        except error.Abort:
513 514
            ret = 1
        if ret:
515 516 517 518
            self._resolveall(parents[0], int(source))
            self._runcmd(hg.graft, '-c', *uargs)

        return nextrev
519

520 521 522 523 524 525 526 527 528 529 530
    def _getnodeids(self, revs):
        out = self.hg.log('--template', '{node}\n',
                          '-r', ' or '.join(str(r) for r in revs))[1]
        return out.splitlines()

    def _prune(self, revs, succ=None):
        if succ:
            succ = self._getnodeids(succ)
        for n in self._getnodeids(revs):
            self._runcmd(self.hg.debugobsolete, n, *succ)

531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
def buildgraph(path, textgraph):
    """create test repostory with dag specified by graphlog like format

    Example:
        buildgraph('./testrepo', r'''
            o   # string after '#' is treated as comment
            |   #
            4   # <- revno can be used instead of 'o' if revno <= 9
            |   #
            o   # <- if 2 parents exist, one under '|' is treated as p1.
            |\  #
            o | # some parameters can be specified by below format
            | o [branch=test user=bob files='foo,bar']
            |/
            o
            ''')

    Revision parameters:
      branch    branch name. if not specified, use branch of p1
      user      author. if not specified, use 'alice'
      files     files to be modified in the revision
      merge     'local' or 'other'. can be specified to merged revision only
553
      precs     revisions to be superseded by it (needs obsolete._enabled)
554 555
    """
    GraphBuilder(path, textgraph).build()