Ejemplo n.º 1
0
 def validate(self):
     """raise InvalidPointer on error. return self if there is no error"""
     requiredcount = 0
     for k, v in self.iteritems():
         if k in self._requiredre:
             if not self._requiredre[k].match(v):
                 raise InvalidPointer(
                     _('unexpected lfs pointer value: %s=%s') %
                     (k, stringutil.pprint(v)))
             requiredcount += 1
         elif not self._keyre.match(k):
             raise InvalidPointer(_('unexpected lfs pointer key: %s') % k)
         if not self._valuere.match(v):
             raise InvalidPointer(
                 _('unexpected lfs pointer value: %s=%s') %
                 (k, stringutil.pprint(v)))
     if len(self._requiredre) != requiredcount:
         miss = sorted(set(self._requiredre.keys()).difference(self.keys()))
         raise InvalidPointer(
             _('missing lfs pointer keys: %s') % ', '.join(miss))
     return self
Ejemplo n.º 2
0
 def printrevset(orig, repo, pats, opts):
     revs, filematcher = orig(repo, pats, opts)
     if opts.get(b'print_revset'):
         expr = logrevset(repo, pats, opts)
         if expr:
             tree = revsetlang.parse(expr)
             tree = revsetlang.analyze(tree)
         else:
             tree = []
         ui = repo.ui
         ui.write(b'%s\n' % stringutil.pprint(opts.get(b'rev', [])))
         ui.write(revsetlang.prettyformat(tree) + b'\n')
         ui.write(stringutil.prettyrepr(revs) + b'\n')
         revs = smartset.baseset()  # display no revisions
     return revs, filematcher
Ejemplo n.º 3
0
def debugformat(text, form, **kwargs):
    blocks, pruned = minirst.parse(text, **kwargs)
    if form == b'html':
        print("html format:")
        out = minirst.format(text, style=form, **kwargs)
    else:
        print("%d column format:" % form)
        out = minirst.format(text, width=form, **kwargs)

    print("-" * 70)
    print(out[:-1].decode('utf8'))
    if kwargs.get('keep'):
        print("-" * 70)
        print(stringutil.pprint(pruned).decode('utf8'))
    print("-" * 70)
    print()
Ejemplo n.º 4
0
def debugformat(text, form, **kwargs):
    if form == b'html':
        print("html format:")
        out = minirst.format(text, style=form, **kwargs)
    else:
        print("%d column format:" % form)
        out = minirst.format(text, width=form, **kwargs)

    print("-" * 70)
    if type(out) == tuple:
        print(out[0][:-1].decode('utf8'))
        print("-" * 70)
        print(stringutil.pprint(out[1]).decode('utf8'))
    else:
        print(out[:-1].decode('utf8'))
    print("-" * 70)
    print()
Ejemplo n.º 5
0
def test(auth, urls=None):
    print('CFG:', pycompat.sysstr(stringutil.pprint(auth, bprefix=True)))
    prefixes = set()
    for k in auth:
        prefixes.add(k.split('.', 1)[0])
    for p in prefixes:
        for name in ('.username', '.password'):
            if (p + name) not in auth:
                auth[p + name] = p
    auth = dict((k, v) for k, v in auth.items() if v is not None)

    ui = writeauth(auth)

    def _test(uri):
        print('URI:', uri)
        try:
            pm = url.passwordmgr(ui, urlreq.httppasswordmgrwithdefaultrealm())
            u, authinfo = util.url(uri).authinfo()
            if authinfo is not None:
                pm.add_password(*authinfo)
            print('    ', pm.find_user_password('test', u))
        except error.Abort:
            print('    ', 'abort')

    if not urls:
        urls = [
            'http://example.org/foo',
            'http://example.org/foo/bar',
            'http://example.org/bar',
            'https://example.org/foo',
            'https://example.org/foo/bar',
            'https://example.org/bar',
            'https://[email protected]/bar',
            'https://[email protected]/bar',
        ]
    for u in urls:
        _test(u)
Ejemplo n.º 6
0
    def annotate(self, rev, master=None, showpath=False, showlines=False):
        """incrementally update the cache so it includes revisions in the main
        branch till 'master'. and run annotate on 'rev', which may or may not be
        included in the main branch.

        if master is None, do not update linelog.

        the first value returned is the annotate result, it is [(node, linenum)]
        by default. [(node, linenum, path)] if showpath is True.

        if showlines is True, a second value will be returned, it is a list of
        corresponding line contents.
        """

        # the fast path test requires commit hash, convert rev number to hash,
        # so it may hit the fast path. note: in the "fctx" mode, the "annotate"
        # command could give us a revision number even if the user passes a
        # commit hash.
        if isinstance(rev, int):
            rev = node.hex(self.repo.changelog.node(rev))

        # fast path: if rev is in the main branch already
        directly, revfctx = self.canannotatedirectly(rev)
        if directly:
            if self.ui.debugflag:
                self.ui.debug(
                    'fastannotate: %s: using fast path '
                    '(resolved fctx: %s)\n' %
                    (self.path,
                     stringutil.pprint(util.safehasattr(revfctx, 'node'))))
            return self.annotatedirectly(revfctx, showpath, showlines)

        # resolve master
        masterfctx = None
        if master:
            try:
                masterfctx = self._resolvefctx(master,
                                               resolverev=True,
                                               adjustctx=True)
            except LookupError:  # master does not have the file
                pass
            else:
                if masterfctx in self.revmap:  # no need to update linelog
                    masterfctx = None

        #                  ... - @ <- rev (can be an arbitrary changeset,
        #                 /                not necessarily a descendant
        #      master -> o                 of master)
        #                |
        #     a merge -> o         'o': new changesets in the main branch
        #                |\        '#': revisions in the main branch that
        #                o *            exist in linelog / revmap
        #                | .       '*': changesets in side branches, or
        # last master -> # .            descendants of master
        #                | .
        #                # *       joint: '#', and is a parent of a '*'
        #                |/
        #     a joint -> # ^^^^ --- side branches
        #                |
        #                ^ --- main branch (in linelog)

        # these DFSes are similar to the traditional annotate algorithm.
        # we cannot really reuse the code for perf reason.

        # 1st DFS calculates merges, joint points, and needed.
        # "needed" is a simple reference counting dict to free items in
        # "hist", reducing its memory usage otherwise could be huge.
        initvisit = [revfctx]
        if masterfctx:
            if masterfctx.rev() is None:
                raise error.Abort(_('cannot update linelog to wdir()'),
                                  hint=_('set fastannotate.mainbranch'))
            initvisit.append(masterfctx)
        visit = initvisit[:]
        pcache = {}
        needed = {revfctx: 1}
        hist = {}  # {fctx: ([(llrev or fctx, linenum)], text)}
        while visit:
            f = visit.pop()
            if f in pcache or f in hist:
                continue
            if f in self.revmap:  # in the old main branch, it's a joint
                llrev = self.revmap.hsh2rev(f.node())
                self.linelog.annotate(llrev)
                result = self.linelog.annotateresult
                hist[f] = (result, f.data())
                continue
            pl = self._parentfunc(f)
            pcache[f] = pl
            for p in pl:
                needed[p] = needed.get(p, 0) + 1
                if p not in pcache:
                    visit.append(p)

        # 2nd (simple) DFS calculates new changesets in the main branch
        # ('o' nodes in # the above graph), so we know when to update linelog.
        newmainbranch = set()
        f = masterfctx
        while f and f not in self.revmap:
            newmainbranch.add(f)
            pl = pcache[f]
            if pl:
                f = pl[0]
            else:
                f = None
                break

        # f, if present, is the position where the last build stopped at, and
        # should be the "master" last time. check to see if we can continue
        # building the linelog incrementally. (we cannot if diverged)
        if masterfctx is not None:
            self._checklastmasterhead(f)

        if self.ui.debugflag:
            if newmainbranch:
                self.ui.debug('fastannotate: %s: %d new changesets in the main'
                              ' branch\n' % (self.path, len(newmainbranch)))
            elif not hist:  # no joints, no updates
                self.ui.debug('fastannotate: %s: linelog cannot help in '
                              'annotating this revision\n' % self.path)

        # prepare annotateresult so we can update linelog incrementally
        self.linelog.annotate(self.linelog.maxrev)

        # 3rd DFS does the actual annotate
        visit = initvisit[:]
        progress = self.ui.makeprogress(('building cache'),
                                        total=len(newmainbranch))
        while visit:
            f = visit[-1]
            if f in hist:
                visit.pop()
                continue

            ready = True
            pl = pcache[f]
            for p in pl:
                if p not in hist:
                    ready = False
                    visit.append(p)
            if not ready:
                continue

            visit.pop()
            blocks = None  # mdiff blocks, used for appending linelog
            ismainbranch = (f in newmainbranch)
            # curr is the same as the traditional annotate algorithm,
            # if we only care about linear history (do not follow merge),
            # then curr is not actually used.
            assert f not in hist
            curr = _decorate(f)
            for i, p in enumerate(pl):
                bs = list(self._diffblocks(hist[p][1], curr[1]))
                if i == 0 and ismainbranch:
                    blocks = bs
                curr = _pair(hist[p], curr, bs)
                if needed[p] == 1:
                    del hist[p]
                    del needed[p]
                else:
                    needed[p] -= 1

            hist[f] = curr
            del pcache[f]

            if ismainbranch:  # need to write to linelog
                progress.increment()
                bannotated = None
                if len(pl) == 2 and self.opts.followmerge:  # merge
                    bannotated = curr[0]
                if blocks is None:  # no parents, add an empty one
                    blocks = list(self._diffblocks('', curr[1]))
                self._appendrev(f, blocks, bannotated)
            elif showpath:  # not append linelog, but we need to record path
                self._node2path[f.node()] = f.path()

        progress.complete()

        result = [
            ((self.revmap.rev2hsh(fr) if isinstance(fr, int) else fr.node()),
             l) for fr, l in hist[revfctx][0]
        ]  # [(node, linenumber)]
        return self._refineannotateresult(result, revfctx, showpath, showlines)
Ejemplo n.º 7
0
def hashdiffopts(diffopts):
    diffoptstr = stringutil.pprint(
        sorted((k, getattr(diffopts, k)) for k in mdiff.diffopts.defaults))
    return node.hex(hashlib.sha1(diffoptstr).digest())[:6]
Ejemplo n.º 8
0
 def deserialize(cls, text):
     try:
         return cls(l.split(' ', 1) for l in text.splitlines()).validate()
     except ValueError:  # l.split returns 1 item instead of 2
         raise InvalidPointer(
             _('cannot parse git-lfs text: %s') % stringutil.pprint(text))
Ejemplo n.º 9
0

def unmangle(s):
    return b''.join(pycompat.bytechr(ord(c) - 1) for c in pycompat.bytestr(s))


def greet(repo, proto, name):
    return mangle(repo.greet(unmangle(name)))


wireprotov1server.commands[b'greet'] = (greet, b'name')

srv = serverrepo()
clt = clientpeer(srv, uimod.ui())


def printb(data, end=b'\n'):
    out = getattr(sys.stdout, 'buffer', sys.stdout)
    out.write(data + end)
    out.flush()


printb(clt.greet(b"Foobar"))

with clt.commandexecutor() as e:
    fgreet1 = e.callcommand(b'greet', {b'name': b'Fo, =;:<o'})
    fgreet2 = e.callcommand(b'greet', {b'name': b'Bar'})

printb(
    stringutil.pprint([f.result() for f in (fgreet1, fgreet2)], bprefix=True))
Ejemplo n.º 10
0
 def demoitems(section, items):
     ui.write(b'[%s]\n' % section)
     for k, v in sorted(items):
         if isinstance(v, bool):
             v = stringutil.pprint(v)
         ui.write(b'%s = %s\n' % (k, v))
Ejemplo n.º 11
0
import os
from mercurial import (
    dispatch,
    ui as uimod,
)
from mercurial.utils import (
    stringutil, )

# ensure errors aren't buffered
testui = uimod.ui()
testui.pushbuffer()
testui.write((b'buffered\n'))
testui.warn((b'warning\n'))
testui.write_err(b'error\n')
print(stringutil.pprint(testui.popbuffer(), bprefix=True).decode('ascii'))

# test dispatch.dispatch with the same ui object
hgrc = open(os.environ["HGRCPATH"], 'wb')
hgrc.write(b'[extensions]\n')
hgrc.write(b'color=\n')
hgrc.close()

ui_ = uimod.ui.load()
ui_.setconfig(b'ui', b'formatted', b'True')

# we're not interested in the output, so write that to devnull
ui_.fout = open(os.devnull, 'wb')


# call some arbitrary command just so we go through
Ejemplo n.º 12
0
def pprint(obj):
    return stringutil.pprint(obj).decode('ascii')