Exemplo n.º 1
0
    def run(self):
        self.repo.dirstate.invalidate()
        extract = lambda x, y: dict(zip(x, map(y.get, x)))
        stopts = extract(('unknown', 'ignored', 'clean'), self.opts)
        patchecked = {}
        try:
            if self.pats:
                if self.opts.get('checkall'):
                    # quickop sets this flag to pre-check even !?IC files
                    precheckfn = lambda x: True
                else:
                    # status and commit only pre-check MAR files
                    precheckfn = lambda x: x < 4
                m = scmutil.match(self.repo[None], self.pats)
                self.repo.bfstatus = True
                self.repo.lfstatus = True
                status = self.repo.status(match=m, **stopts)
                self.repo.bfstatus = False
                self.repo.lfstatus = False
                # Record all matched files as initially checked
                for i, stat in enumerate(StatusType.preferredOrder):
                    if stat == 'S':
                        continue
                    val = statusTypes[stat]
                    if self.opts[val.name]:
                        d = dict([(fn, precheckfn(i)) for fn in status[i]])
                        patchecked.update(d)
                wctx = context.workingctx(self.repo, changes=status)
                self.patchecked = patchecked
            elif self.pctx:
                self.repo.bfstatus = True
                self.repo.lfstatus = True
                status = self.repo.status(node1=self.pctx.p1().node(),
                                          **stopts)
                self.repo.bfstatus = False
                self.repo.lfstatus = False
                wctx = context.workingctx(self.repo, changes=status)
            else:
                wctx = self.repo[None]
                self.repo.bfstatus = True
                self.repo.lfstatus = True
                wctx.status(**stopts)
                self.repo.bfstatus = False
                self.repo.lfstatus = False
            self.wctx = wctx

            wctx.dirtySubrepos = []
            for s in wctx.substate:
                if wctx.sub(s).dirty():
                    wctx.dirtySubrepos.append(s)
        except EnvironmentError, e:
            self.showMessage.emit(hglib.tounicode(str(e)))
Exemplo n.º 2
0
    def run(self):
        self.repo.dirstate.invalidate()
        extract = lambda x, y: dict(zip(x, map(y.get, x)))
        stopts = extract(('unknown', 'ignored', 'clean'), self.opts)
        patchecked = {}
        try:
            if self.pats:
                if self.opts.get('checkall'):
                    # quickop sets this flag to pre-check even !?IC files
                    precheckfn = lambda x: True
                else:
                    # status and commit only pre-check MAR files
                    precheckfn = lambda x: x < 4
                m = hglib.match(self.repo[None], self.pats)
                self.repo.bfstatus = True
                self.repo.lfstatus = True
                status = self.repo.status(match=m, **stopts)
                self.repo.bfstatus = False
                self.repo.lfstatus = False
                # Record all matched files as initially checked
                for i, stat in enumerate(StatusType.preferredOrder):
                    if stat == 'S':
                        continue
                    val = statusTypes[stat]
                    if self.opts[val.name]:
                        d = dict([(fn, precheckfn(i)) for fn in status[i]])
                        patchecked.update(d)
                wctx = context.workingctx(self.repo, changes=status)
                self.patchecked = patchecked
            elif self.pctx:
                self.repo.bfstatus = True
                self.repo.lfstatus = True
                status = self.repo.status(node1=self.pctx.p1().node(), **stopts)
                self.repo.bfstatus = False
                self.repo.lfstatus = False
                wctx = context.workingctx(self.repo, changes=status)
            else:
                wctx = self.repo[None]
                self.repo.bfstatus = True
                self.repo.lfstatus = True
                wctx.status(**stopts)
                self.repo.bfstatus = False
                self.repo.lfstatus = False
            self.wctx = wctx

            wctx.dirtySubrepos = []
            for s in wctx.substate:
                if wctx.sub(s).dirty():
                    wctx.dirtySubrepos.append(s)
        except EnvironmentError, e:
            self.showMessage.emit(hglib.tounicode(str(e)))
Exemplo n.º 3
0
def do_check_style(hgui, repo, *files, **args):
    """check files for proper m5 style guidelines"""
    from mercurial import mdiff, util

    auto = args.get('auto', False)
    if auto:
        auto = 'f'
    ui = MercurialUI(hgui, hgui.verbose, auto)

    if files:
        files = frozenset(files)

    def skip(name):
        return files and name in files

    def prompt(name, func, regions=all_regions):
        result = ui.prompt("(a)bort, (i)gnore, or (f)ix?", 'aif', 'a')
        if result == 'a':
            return True
        elif result == 'f':
            func(repo.wjoin(name), regions)

        return False

    modified, added, removed, deleted, unknown, ignore, clean = repo.status()

    whitespace = Whitespace(ui)
    sorted_includes = SortedIncludes(ui)
    for fname in added:
        if skip(fname):
            continue

        fpath = joinpath(repo.root, fname)

        if whitespace.apply(fpath, prompt):
            return True

        if sorted_includes.apply(fpath, prompt):
            return True

    try:
        wctx = repo.workingctx()
    except:
        from mercurial import context
        wctx = context.workingctx(repo)

    for fname in modified:
        if skip(fname):
            continue

        fpath = joinpath(repo.root, fname)
        regions = modregions(wctx, fname)

        if whitespace.apply(fpath, prompt, regions):
            return True

        if sorted_includes.apply(fpath, prompt, regions):
            return True

    return False
Exemplo n.º 4
0
def _modified_regions(repo, patterns, **kwargs):
    opt_all = kwargs.get('all', False)
    opt_no_ignore = kwargs.get('no_ignore', False)

    # Import the match (repository file name matching helper)
    # function. Different versions of Mercurial keep it in different
    # modules and implement them differently.
    try:
        from mercurial import scmutil
        m = scmutil.match(repo[None], patterns, kwargs)
    except ImportError:
        from mercurial import cmdutil
        m = cmdutil.match(repo, patterns, kwargs)

    modified, added, removed, deleted, unknown, ignore, clean = \
        repo.status(match=m, clean=opt_all)

    if not opt_all:
        try:
            wctx = repo.workingctx()
        except:
            from mercurial import context
            wctx = context.workingctx(repo)

        files = [ (fn, all_regions) for fn in added ] + \
            [ (fn,  modregions(wctx, fn)) for fn in modified ]
    else:
        files = [(fn, all_regions) for fn in added + modified + clean]

    for fname, mod_regions in files:
        if opt_no_ignore or not check_ignores(fname):
            yield fname, mod_regions
Exemplo n.º 5
0
def _modified_regions(repo, patterns, **kwargs):
    opt_all = kwargs.get('all', False)
    opt_no_ignore = kwargs.get('no_ignore', False)

    # Import the match (repository file name matching helper)
    # function. Different versions of Mercurial keep it in different
    # modules and implement them differently.
    try:
        from mercurial import scmutil
        m = scmutil.match(repo[None], patterns, kwargs)
    except ImportError:
        from mercurial import cmdutil
        m = cmdutil.match(repo, patterns, kwargs)

    modified, added, removed, deleted, unknown, ignore, clean = \
        repo.status(match=m, clean=opt_all)

    if not opt_all:
        try:
            wctx = repo.workingctx()
        except:
            from mercurial import context
            wctx = context.workingctx(repo)

        files = [ (fn, all_regions) for fn in added ] + \
            [ (fn,  modregions(wctx, fn)) for fn in modified ]
    else:
        files = [ (fn, all_regions) for fn in added + modified + clean ]

    for fname, mod_regions in files:
        if opt_no_ignore or not check_ignores(fname):
            yield fname, mod_regions
Exemplo n.º 6
0
def do_check_style(hgui, repo, *files, **args):
    """check files for proper m5 style guidelines"""
    from mercurial import mdiff, util

    auto = args.get('auto', False)
    if auto:
        auto = 'f'
    ui = MercurialUI(hgui, hgui.verbose, auto)

    if files:
        files = frozenset(files)

    def skip(name):
        return files and name in files

    def prompt(name, func, regions=all_regions):
        result = ui.prompt("(a)bort, (i)gnore, or (f)ix?", 'aif', 'a')
        if result == 'a':
            return True
        elif result == 'f':
            func(repo.wjoin(name), regions)

        return False

    modified, added, removed, deleted, unknown, ignore, clean = repo.status()

    whitespace = Whitespace(ui)
    sorted_includes = SortedIncludes(ui)
    for fname in added:
        if skip(fname):
            continue

        fpath = joinpath(repo.root, fname)

        if whitespace.apply(fpath, prompt):
            return True

        if sorted_includes.apply(fpath, prompt):
            return True

    try:
        wctx = repo.workingctx()
    except:
        from mercurial import context
        wctx = context.workingctx(repo)

    for fname in modified:
        if skip(fname):
            continue

        fpath = joinpath(repo.root, fname)
        regions = modregions(wctx, fname)

        if whitespace.apply(fpath, prompt, regions):
            return True

        if sorted_includes.apply(fpath, prompt, regions):
            return True

    return False
Exemplo n.º 7
0
def push_to_try(ui, repo, server, message=None):

    nodate = ui.configbool('push-to-try', 'nodate')

    if not message or 'try:' not in message:
        ui.status("STOP! A commit message with try syntax is required.\n")
        return

    cctx = context.workingctx(repo)
    status = repo.status()

    if status.modified + status.added + status.removed:
        ui.status('The following will be pushed to %s:\n' % server)
        # TODO: Achieve this by re-using the status call above to avoid the
        # cost of running it twice.
        commands.status(ui, repo)

    preserve_ctx = preservefilectx(cctx)

    def mk_memfilectx(repo, memctx, path):
        if path not in status.removed:
            return preserve_ctx(repo, memctx, path)
        return None

    # Invent a temporary commit with our message.
    ui.status("Creating temporary commit for remote...\n")
    mctx = context.memctx(repo,
                          repo.dirstate.parents(),
                          message,
                          cctx.files(),
                          mk_memfilectx,
                          date="0 0" if nodate else None)

    # These messages are expected when we abort our transaction, but aren't
    # helpful to a user and may be misleading so we surpress them here.
    filtered_phrases = {_("transaction abort!\n"), _("rollback completed\n")}

    def filtered_warn(*msgs, **opts):
        if msgs:
            filtered = [m for m in msgs if m not in filtered_phrases]
        if filtered:
            ui.warn(*filtered, **opts)

    lock = tr = None
    try:
        lock = repo.lock()
        tr = repo.transaction('push-to-try', report=filtered_warn)
        m = mctx.commit()
        # Push to try.
        commands.push(ui, repo, server, force=True, rev=[repo[m].rev()])
        ui.status('push complete\n')
        # And rollback to the previous state.
        tr.abort()
    finally:
        if tr:
            tr.release()
        if lock:
            lock.release()
        ui.status("temporary commit removed, repository restored\n")
Exemplo n.º 8
0
def push_to_try(ui, repo, server, message=None):

    nodate = ui.configbool('push-to-try', 'nodate')

    if not message or 'try:' not in message:
        ui.status("STOP! A commit message with try syntax is required.\n")
        return

    cctx = context.workingctx(repo)
    status = repo.status()

    if status.modified + status.added + status.removed:
        ui.status('The following will be pushed to %s:\n' % server)
        # TODO: Achieve this by re-using the status call above to avoid the
        # cost of running it twice.
        commands.status(ui, repo)

    preserve_ctx = preservefilectx(cctx)
    def mk_memfilectx(repo, memctx, path):
        if path not in status.removed:
            return preserve_ctx(repo, memctx, path)
        return None

    # Invent a temporary commit with our message.
    ui.status("Creating temporary commit for remote...\n")
    mctx = context.memctx(repo,
                          repo.dirstate.parents(),
                          message,
                          cctx.files(),
                          mk_memfilectx,
                          date="0 0" if nodate else None)

    # These messages are expected when we abort our transaction, but aren't
    # helpful to a user and may be misleading so we surpress them here.
    filtered_phrases = {_("transaction abort!\n"),
                        _("rollback completed\n")}
    def filtered_warn(*msgs, **opts):
        if msgs:
            filtered = [m for m in msgs if m not in filtered_phrases]
        if filtered:
            ui.warn(*filtered, **opts)

    lock = tr = None
    try:
        lock = repo.lock()
        tr = repo.transaction('push-to-try', report=filtered_warn)
        m = mctx.commit()
        # Push to try.
        commands.push(ui, repo, server, force=True, rev=[repo[m].rev()])
        ui.status('push complete\n')
        # And rollback to the previous state.
        tr.abort()
    finally:
        if tr:
            tr.release()
        if lock:
            lock.release()
        ui.status("temporary commit removed, repository restored\n")
Exemplo n.º 9
0
    def _getctx(self, changeid=None):
        """\
        Returns working context by default
        """
        # XXX attribute selection could use some work.

        if changeid is _cwd:
            ctx = context.workingctx(self._repo)
            return ctx
        else:
            return Storage._getctx(self, changeid)
Exemplo n.º 10
0
    def workingctx(self, worklist=False):
        '''Return a workingctx object representing the working copy.

        If worklist is true, return a workingctx object created based
        on the status of files in the workspace's worklist.'''

        wl = WorkList(self)

        if worklist and wl:
            return context.workingctx(self.repo, changes=wl.status())
        else:
            return self.repo.changectx(None)
Exemplo n.º 11
0
    def workingctx(self, worklist=False):
        '''Return a workingctx object representing the working copy.

        If worklist is true, return a workingctx object created based
        on the status of files in the workspace's worklist.'''

        wl = WorkList(self)

        if worklist and wl:
            return context.workingctx(self.repo, changes=wl.status())
        else:
            return self.repo.changectx(None)
Exemplo n.º 12
0
    def __getattr__(self, attr):
        if attr in ('prompt', 'write'):
            return getattr(self.ui, attr)

        if attr == 'wctx':
            try:
                wctx = repo.workingctx()
            except:
                from mercurial import context
                wctx = context.workingctx(repo)
            self.wctx = wctx
            return wctx

        raise AttributeError
Exemplo n.º 13
0
    def __getattr__(self, attr):
        if attr in ('prompt', 'write'):
            return getattr(self.ui, attr)

        if attr == 'wctx':
            try:
                wctx = repo.workingctx()
            except:
                from mercurial import context
                wctx = context.workingctx(repo)
            self.wctx = wctx
            return wctx

        raise AttributeError
Exemplo n.º 14
0
def describe(ui, repo, **opts):
    """show most recent tag

    Finds the most recent tag reachable from the current revision.
     
    If the current revision has been tagged, only the tag is
    printed:
     
      v1.2.3
     
    Otherwise the long form is printed which includes the tag, the
    number of commits after the tag, and the node of the current
    changeset:

      v1.2.3-8-2789c05b6c3b
     
    If the closest, tagged revision has multiple tags, each is
    printed on a separate line unless the --single-tag option is
    used, in which case an error is raised.

    If multiple revisions are equally reachable from the root and
    one is on the current branch, it is chosen.  Otherwise each tag
    from each revision is printed on a separate line unless the
    --single-rev option is used, in which case an error is raised.

    If the --prefer-branch option is used, the closest tag on the
    current branch will override closer tags that are reachable but
    not on the same branch.  In the example below, tag A is
    normally chosen since it is closer to the root than B (3
    commits vs 4 commits).  However, if --prefer-branch is used, B
    will be chosen because it is on the the same branch.

            o-A-o
           /     \\
        o-o-B-o-o-o-o <-- root

    The --require-branch option requires the tag to be on the same
    branch.  This is similar to the --prefer-branch option but raises an
    error if no tags are found on the current branch.
    """
    if not repo.local():
        raise util.Abort(_("must be a local repository"))

    if opts['rev']:
        ctx = context.changectx(repo, opts['rev'])
    else:
        ctx = context.workingctx(repo).parents()[0]

    tags, count = _find_closest_tag(ui, repo, ctx, opts)

    uselong = opts['long'] or (count != 0 and not opts['short'])

    if uselong:
        hexfunc = (opts['full'] or ui.debugflag) and hex or short
        node = hexfunc(ctx.node())
        sep = opts['spaces'] and ' ' or '-'
        count = str(count)

        for tag in tags:
            ui.write("%s\n" % sep.join([tag, count, node]))

    else:
        for tag in tags:
            ui.write("%s\n" % tag)
Exemplo n.º 15
0
def do_check_style(hgui, repo, *pats, **opts):
    """check files for proper m5 style guidelines

    Without an argument, checks all modified and added files for gem5
    coding style violations. A list of files can be specified to limit
    the checker to a subset of the repository. The style rules are
    normally applied on a diff of the repository state (i.e., added
    files are checked in their entirety while only modifications of
    modified files are checked).

    The --all option can be specified to include clean files and check
    modified files in their entirety.
    """
    from mercurial import mdiff, util

    opt_fix_white = opts.get('fix_white', False)
    opt_all = opts.get('all', False)
    opt_no_ignore = opts.get('no_ignore', False)
    ui = MercurialUI(hgui, hgui.verbose, opt_fix_white)

    def prompt(name, func, regions=all_regions):
        result = ui.prompt("(a)bort, (i)gnore, or (f)ix?", 'aif', 'a')
        if result == 'a':
            return True
        elif result == 'f':
            func(repo.wjoin(name), regions)

        return False


    # Import the match (repository file name matching helper)
    # function. Different versions of Mercurial keep it in different
    # modules and implement them differently.
    try:
        from mercurial import scmutil
        m = scmutil.match(repo[None], pats, opts)
    except ImportError:
        from mercurial import cmdutil
        m = cmdutil.match(repo, pats, opts)

    modified, added, removed, deleted, unknown, ignore, clean = \
        repo.status(match=m, clean=opt_all)
    if not opt_all:
        try:
            wctx = repo.workingctx()
        except:
            from mercurial import context
            wctx = context.workingctx(repo)

        files = [ (fn, all_regions) for fn in added ] + \
            [ (fn,  modregions(wctx, fn)) for fn in modified ]
    else:
        files = [ (fn, all_regions) for fn in added + modified + clean ]

    whitespace = Whitespace(ui)
    sorted_includes = SortedIncludes(ui)
    for fname, mod_regions in files:
        if not opt_no_ignore and check_ignores(fname):
            continue

        fpath = joinpath(repo.root, fname)

        if whitespace.apply(fpath, prompt, mod_regions):
            return True

        if sorted_includes.apply(fpath, prompt, mod_regions):
            return True

    return False
Exemplo n.º 16
0
def do_check_whitespace(ui, repo, *files, **args):
    """check files for proper m5 style guidelines"""
    from mercurial import mdiff, util

    if files:
        files = frozenset(files)

    def skip(name):
        return files and name in files

    def prompt(name, fixonly=None):
        if args.get('auto', False):
            result = 'f'
        else:
            while True:
                result = ui.prompt("(a)bort, (i)gnore, or (f)ix?", default='a')
                if result in 'aif':
                    break

        if result == 'a':
            return True
        elif result == 'f':
            fixwhite(repo.wjoin(name), args['tabsize'], fixonly)

        return False

    modified, added, removed, deleted, unknown, ignore, clean = repo.status()

    for fname in added:
        if skip(fname):
            continue

        ok = True
        for line, num in checkwhite(repo.wjoin(fname)):
            ui.write("invalid whitespace in %s:%d\n" % (fname, num))
            if ui.verbose:
                ui.write(">>%s<<\n" % line[-1])
            ok = False

        if not ok:
            if prompt(fname):
                return True

    try:
        wctx = repo.workingctx()
    except:
        from mercurial import context
        wctx = context.workingctx(repo)

    for fname in modified:
        if skip(fname):
            continue

        if not whitespace_file(fname):
            continue

        fctx = wctx.filectx(fname)
        pctx = fctx.parents()

        file_data = fctx.data()
        lines = mdiff.splitnewlines(file_data)
        if len(pctx) in (1, 2):
            mod_lines = modified_lines(pctx[0].data(), file_data, len(lines))
            if len(pctx) == 2:
                m2 = modified_lines(pctx[1].data(), file_data, len(lines))
                # only the lines that are new in both
                mod_lines = mod_lines & m2
        else:
            mod_lines = xrange(0, len(lines))

        fixonly = set()
        for i, line in enumerate(lines):
            if i not in mod_lines:
                continue

            if checkwhite_line(line):
                continue

            ui.write("invalid whitespace: %s:%d\n" % (fname, i + 1))
            if ui.verbose:
                ui.write(">>%s<<\n" % line[:-1])
            fixonly.add(i)

        if fixonly:
            if prompt(fname, fixonly):
                return True
Exemplo n.º 17
0
def hook(ui, repo, hooktype, node=None, source=None, **kwargs):
    # read config parameters
    master = ui.config('hgbuildbot', 'master')
    if master:
        branchtype = ui.config('hgbuildbot', 'branchtype')
        branch = ui.config('hgbuildbot', 'branch')
        fork = ui.configbool('hgbuildbot', 'fork', False)
        # notify also has this setting
        stripcount = int(ui.config('notify','strip') or ui.config('hgbuildbot','strip',3))
        category = ui.config('hgbuildbot', 'category', None)
        project = ui.config('hgbuildbot', 'project', '')
    else:
        ui.write("* You must add a [hgbuildbot] section to .hg/hgrc in "
                 "order to use buildbot hook\n")
        return

    if hooktype != "changegroup":
        ui.status("hgbuildbot: hooktype %s not supported.\n" % hooktype)
        return

    if fork:
        child_pid = os.fork()
        if child_pid == 0:
            #child
            pass
        else:
            #parent
            ui.status("Notifying buildbot...\n")
            return

    # only import inside the fork if forked
    from buildbot.clients import sendchange
    from twisted.internet import defer, reactor

    if branch is None:
        if branchtype is not None:
            if branchtype == 'dirname':
                branch = os.path.basename(repo.root)
            if branchtype == 'inrepo':
                branch = workingctx(repo).branch()

    s = sendchange.Sender(master, None)
    d = defer.Deferred()
    reactor.callLater(0, d.callback, None)
    # process changesets
    def _send(res, c):
        if not fork:
            ui.status("rev %s sent\n" % c['revision'])
        return s.send(c['branch'], c['revision'], c['comments'],
                      c['files'], c['username'], category=category,
                      repository=repository, project=project)

    try:    # first try Mercurial 1.1+ api
        start = repo[node].rev()
        end = len(repo)
    except TypeError:   # else fall back to old api
        start = repo.changelog.rev(bin(node))
        end = repo.changelog.count()

    repository = strip(repo.root, stripcount)

    for rev in xrange(start, end):
        # send changeset
        node = repo.changelog.node(rev)
        manifest, user, (time, timezone), files, desc, extra = repo.changelog.read(node)
        parents = filter(lambda p: not p == nullid, repo.changelog.parents(node))
        if branchtype == 'inrepo':
            branch = extra['branch']
        # merges don't always contain files, but at least one file is required by buildbot
        if len(parents) > 1 and not files:
            files = ["merge"]
        change = {
            'master': master,
            'username': user,
            'revision': hex(node),
            'comments': desc,
            'files': files,
            'branch': branch
        }
        d.addCallback(_send, change)

    d.addCallbacks(s.printSuccess, s.printFailure)
    d.addBoth(s.stop)
    s.run()

    if fork:
        os._exit(os.EX_OK)
    else:
        return
Exemplo n.º 18
0
def push_to_try(ui, repo, server, message=None):

    nodate = ui.configbool(b'push-to-try', b'nodate')

    if not server:
        if b'try' in ui.paths:
            server = b'try'
        else:
            server = b'ssh://hg.mozilla.org/try'

    if not message:
        ui.status(b"STOP! A commit message is required.\n")
        return

    cctx = context.workingctx(repo)
    if b'try_task_config.json' not in cctx and b'try:' not in message:
        ui.status(b"STOP! Either try_task_config.json must be added or the commit "
                  b"message must contain try syntax.\n")
        return

    if b'try_task_config.json' in cctx:
        data = repo.wvfs.tryread(b'try_task_config.json')
        try:
            # data could be an empty string if tryread failed, which will
            # produce a ValueError here.
            data = json.loads(data)
        except ValueError as e:
            ui.status(b"Error reading try_task_config.json: could not decode as JSON\n")
            return

    # Invent a temporary commit with our message.
    ui.status(b"Creating temporary commit for remote...\n")
    status = repo.status()
    if status.modified + status.added + status.removed:
        # TODO: Achieve this by re-using the status call above to avoid the
        # cost of running it twice.
        commands.status(ui, repo)

    preserve_ctx = preservefilectx(cctx)
    def mk_memfilectx(repo, memctx, path):
        if path not in status.removed:
            return preserve_ctx(repo, memctx, path)
        return None

    mctx = context.memctx(repo,
                          repo.dirstate.parents(),
                          message,
                          cctx.files(),
                          mk_memfilectx,
                          date=b"0 0" if nodate else None)

    # These messages are expected when we abort our transaction, but aren't
    # helpful to a user and may be misleading so we surpress them here.
    filtered_phrases = {_(b"transaction abort!\n"),
                        _(b"rollback completed\n")}
    def filtered_warn(*msgs, **opts):
        if msgs:
            filtered = [m for m in msgs if m not in filtered_phrases]
        if filtered:
            ui.warn(*filtered, **opts)

    lock = tr = None
    try:
        lock = repo.lock()
        tr = repo.transaction(b'push-to-try', report=filtered_warn)
        m = mctx.commit()
        # Push to try.
        commands.push(ui, repo, server, force=True, rev=[repo[m].rev()])
        ui.status(b'push complete\n')
        # And rollback to the previous state.
        tr.abort()
    finally:
        if tr:
            tr.release()
        if lock:
            lock.release()
        ui.status(b"temporary commit removed, repository restored\n")
Exemplo n.º 19
0
def hook(ui, repo, hooktype, node=None, source=None, **kwargs):
    # read config parameters
    master = ui.config('hgbuildbot', 'master')
    if master:
        branchtype = ui.config('hgbuildbot', 'branchtype')
        branch = ui.config('hgbuildbot', 'branch')
        fork = ui.configbool('hgbuildbot', 'fork', False)
        # notify also has this setting
        stripcount = int(
            ui.config('notify', 'strip')
            or ui.config('hgbuildbot', 'strip', 3))
        category = ui.config('hgbuildbot', 'category', None)
        project = ui.config('hgbuildbot', 'project', '')
    else:
        ui.write("* You must add a [hgbuildbot] section to .hg/hgrc in "
                 "order to use buildbot hook\n")
        return

    if hooktype != "changegroup":
        ui.status("hgbuildbot: hooktype %s not supported.\n" % hooktype)
        return

    if fork:
        child_pid = os.fork()
        if child_pid == 0:
            #child
            pass
        else:
            #parent
            ui.status("Notifying buildbot...\n")
            return

    # only import inside the fork if forked
    from buildbot.clients import sendchange
    from twisted.internet import defer, reactor

    if branch is None:
        if branchtype is not None:
            if branchtype == 'dirname':
                branch = os.path.basename(repo.root)
            if branchtype == 'inrepo':
                branch = workingctx(repo).branch()

    s = sendchange.Sender(master, None)
    d = defer.Deferred()
    reactor.callLater(0, d.callback, None)

    # process changesets
    def _send(res, c):
        if not fork:
            ui.status("rev %s sent\n" % c['revision'])
        return s.send(c['branch'],
                      c['revision'],
                      c['comments'],
                      c['files'],
                      c['username'],
                      category=category,
                      repository=repository,
                      project=project)

    try:  # first try Mercurial 1.1+ api
        start = repo[node].rev()
        end = len(repo)
    except TypeError:  # else fall back to old api
        start = repo.changelog.rev(bin(node))
        end = repo.changelog.count()

    repository = strip(repo.root, stripcount)

    for rev in xrange(start, end):
        # send changeset
        node = repo.changelog.node(rev)
        manifest, user, (
            time, timezone), files, desc, extra = repo.changelog.read(node)
        parents = filter(lambda p: not p == nullid,
                         repo.changelog.parents(node))
        if branchtype == 'inrepo':
            branch = extra['branch']
        # merges don't always contain files, but at least one file is required by buildbot
        if len(parents) > 1 and not files:
            files = ["merge"]
        change = {
            'master': master,
            'username': user,
            'revision': hex(node),
            'comments': desc,
            'files': files,
            'branch': branch
        }
        d.addCallback(_send, change)

    d.addCallbacks(s.printSuccess, s.printFailure)
    d.addBoth(s.stop)
    s.run()

    if fork:
        os._exit(os.EX_OK)
    else:
        return
Exemplo n.º 20
0
Arquivo: style.py Projeto: hassahma/m5
def do_check_whitespace(ui, repo, *files, **args):
    """check files for proper m5 style guidelines"""
    from mercurial import mdiff, util

    if files:
        files = frozenset(files)

    def skip(name):
        return files and name in files

    def prompt(name, fixonly=None):
        if args.get('auto', False):
            result = 'f'
        else:
            while True:
                result = ui.prompt("(a)bort, (i)gnore, or (f)ix?", default='a')
                if result in 'aif':
                    break

        if result == 'a':
            return True
        elif result == 'f':
            fixwhite(repo.wjoin(name), args['tabsize'], fixonly)

        return False

    modified, added, removed, deleted, unknown, ignore, clean = repo.status()

    for fname in added:
        if skip(fname):
            continue

        ok = True
        for line,num in checkwhite(repo.wjoin(fname)):
            ui.write("invalid whitespace in %s:%d\n" % (fname, num))
            if ui.verbose:
                ui.write(">>%s<<\n" % line[-1])
            ok = False

        if not ok:
            if prompt(fname):
                return True

    try:
        wctx = repo.workingctx()
    except:
        from mercurial import context
        wctx = context.workingctx(repo)

    for fname in modified:
        if skip(fname):
            continue

        if not whitespace_file(fname):
            continue

        fctx = wctx.filectx(fname)
        pctx = fctx.parents()

        file_data = fctx.data()
        lines = mdiff.splitnewlines(file_data)
        if len(pctx) in (1, 2):
            mod_lines = modified_lines(pctx[0].data(), file_data, len(lines))
            if len(pctx) == 2:
                m2 = modified_lines(pctx[1].data(), file_data, len(lines))
                # only the lines that are new in both
                mod_lines = mod_lines & m2
        else:
            mod_lines = xrange(0, len(lines))

        fixonly = set()
        for i,line in enumerate(lines):
            if i not in mod_lines:
                continue

            if checkwhite_line(line):
                continue

            ui.write("invalid whitespace: %s:%d\n" % (fname, i+1))
            if ui.verbose:
                ui.write(">>%s<<\n" % line[:-1])
            fixonly.add(i)

        if fixonly:
            if prompt(fname, fixonly):
                return True
Exemplo n.º 21
0
def do_check_style(hgui, repo, *files, **args):
    """check files for proper m5 style guidelines"""
    from mercurial import mdiff, util

    auto = args.get('auto', False)
    if auto:
        auto = 'f'
    ui = MercurialUI(hgui, hgui.verbose, auto)

    if files:
        files = frozenset(files)

    def skip(name):
        # We never want to handle symlinks, so always skip them: If the location
        # pointed to is a directory, skip it. If the location is a file inside
        # the gem5 directory, it will be checked as a file, so symlink can be
        # skipped. If the location is a file outside gem5, we don't want to
        # check it anyway.
        if os.path.islink(name):
            return True
        return files and name in files

    def prompt(name, func, regions=all_regions):
        result = ui.prompt("(a)bort, (i)gnore, or (f)ix?", 'aif', 'a')
        if result == 'a':
            return True
        elif result == 'f':
            func(repo.wjoin(name), regions)

        return False

    modified, added, removed, deleted, unknown, ignore, clean = repo.status()

    whitespace = Whitespace(ui)
    sorted_includes = SortedIncludes(ui)
    for fname in added:
        if skip(fname):
            continue

        fpath = joinpath(repo.root, fname)

        if whitespace.apply(fpath, prompt):
            return True

        if sorted_includes.apply(fpath, prompt):
            return True

    try:
        wctx = repo.workingctx()
    except:
        from mercurial import context
        wctx = context.workingctx(repo)

    for fname in modified:
        if skip(fname):
            continue

        fpath = joinpath(repo.root, fname)
        regions = modregions(wctx, fname)

        if whitespace.apply(fpath, prompt, regions):
            return True

        if sorted_includes.apply(fpath, prompt, regions):
            return True

    return False
Exemplo n.º 22
0
def hook(ui, repo, hooktype, node=None, source=None, **kwargs):
    # read config parameters
    master = ui.config('hgbuildbot', 'master')
    if master:
        branchtype = ui.config('hgbuildbot', 'branchtype')
        branch = ui.config('hgbuildbot', 'branch')
    else:
        ui.write("* You must add a [hgbuildbot] section to .hg/hgrc in "
                 "order to use buildbot hook\n")
        return

    if branch is None:
        if branchtype is not None:
            if branchtype == 'dirname':
                branch = os.path.basename(os.getcwd())
            if branchtype == 'inrepo':
                branch = workingctx(repo).branch()

    if hooktype == 'changegroup':
        s = sendchange.Sender(master, None)
        d = defer.Deferred()
        reactor.callLater(0, d.callback, None)

        # process changesets
        def _send(res, c):
            ui.status("rev %s sent\n" % c['revision'])
            return s.send(c['branch'], c['revision'], c['comments'],
                          c['files'], c['username'])

        try:  # first try Mercurial 1.1+ api
            start = repo[node].rev()
            end = len(repo)
        except TypeError:  # else fall back to old api
            start = repo.changelog.rev(bin(node))
            end = repo.changelog.count()

        for rev in xrange(start, end):
            # send changeset
            node = repo.changelog.node(rev)
            manifest, user, (
                time, timezone), files, desc, extra = repo.changelog.read(node)
            parents = filter(lambda p: not p == nullid,
                             repo.changelog.parents(node))
            if branchtype == 'inrepo':
                branch = extra['branch']
            # merges don't always contain files, but at least one file is required by buildbot
            if len(parents) > 1 and not files:
                files = ["merge"]
            change = {
                'master': master,
                'username': user,
                'revision': hex(node),
                'comments': desc,
                'files': files,
                'branch': branch
            }
            d.addCallback(_send, change)

        d.addCallbacks(s.printSuccess, s.printFailure)
        d.addBoth(s.stop)
        s.run()
    else:
        ui.status(_('hgbuildbot: hook %s not supported\n') % hooktype)
    return
Exemplo n.º 23
0
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.

from mercurial import (
    changelog,
    context,
    hg,
    ui,
)

changelog_add = changelog.changelog.add

def add(self, manifest, files, desc, transaction, p1, p2,
        user, date=None, extra=None, p1copies=None, p2copies=None):
    files = ['foo', 'bar']
    return changelog_add(self, manifest, files, desc, transaction, p1, p2,
        user, date=date, extra=extra)

changelog.changelog.add = add


if __name__ == '__main__':
    ui = ui.ui()
    repo = hg.repository(ui)
    default_date = '0 0'
    cctx = context.workingctx(repo, 'corrupted', 'foo', default_date,
        {'rebase_source': '0123456789012345678901234567890123456789'})
    repo.commitctx(cctx)
Exemplo n.º 24
0
def hook(ui, repo, hooktype, node=None, source=None, **kwargs):
    # read config parameters
    baseurl = ui.config("hgbuildbot", "baseurl", "")
    master = ui.config("hgbuildbot", "master")
    if master:
        branchtype = ui.config("hgbuildbot", "branchtype")
        branch = ui.config("hgbuildbot", "branch")
        fork = ui.configbool("hgbuildbot", "fork", False)
        # notify also has this setting
        stripcount = int(ui.config("notify", "strip") or ui.config("hgbuildbot", "strip", 3))
        category = ui.config("hgbuildbot", "category", None)
        project = ui.config("hgbuildbot", "project", "")
        auth = ui.config("hgbuildbot", "auth", None)
    else:
        ui.write("* You must add a [hgbuildbot] section to .hg/hgrc in " "order to use buildbot hook\n")
        return

    if hooktype != "changegroup":
        ui.status("hgbuildbot: hooktype %s not supported.\n" % hooktype)
        return

    if fork:
        child_pid = os.fork()
        if child_pid == 0:
            # child
            pass
        else:
            # parent
            ui.status("Notifying buildbot...\n")
            return

    # only import inside the fork if forked
    from buildbot.clients import sendchange
    from twisted.internet import defer, reactor

    if branch is None:
        if branchtype is not None:
            if branchtype == "dirname":
                branch = os.path.basename(repo.root)
            if branchtype == "inrepo":
                branch = workingctx(repo).branch()

    if not auth:
        auth = "change:changepw"
    auth = auth.split(":", 1)

    s = sendchange.Sender(master, auth=auth)
    d = defer.Deferred()
    reactor.callLater(0, d.callback, None)
    # process changesets
    def _send(res, c):
        if not fork:
            ui.status("rev %s sent\n" % c["revision"])
        return s.send(
            c["branch"],
            c["revision"],
            c["comments"],
            c["files"],
            c["username"],
            category=category,
            repository=repository,
            project=project,
            vc="hg",
            properties=c["properties"],
        )

    try:  # first try Mercurial 1.1+ api
        start = repo[node].rev()
        end = len(repo)
    except TypeError:  # else fall back to old api
        start = repo.changelog.rev(bin(node))
        end = repo.changelog.count()

    repository = strip(repo.root, stripcount)
    repository = baseurl + repository

    for rev in xrange(start, end):
        # send changeset
        node = repo.changelog.node(rev)
        manifest, user, (time, timezone), files, desc, extra = repo.changelog.read(node)
        parents = filter(lambda p: not p == nullid, repo.changelog.parents(node))
        if branchtype == "inrepo":
            branch = extra["branch"]
        is_merge = len(parents) > 1
        # merges don't always contain files, but at least one file is required by buildbot
        if is_merge and not files:
            files = ["merge"]
        properties = {"is_merge": is_merge}
        if branch:
            branch = fromlocal(branch)
        change = {
            "master": master,
            "username": fromlocal(user),
            "revision": hex(node),
            "comments": fromlocal(desc),
            "files": files,
            "branch": branch,
            "properties": properties,
        }
        d.addCallback(_send, change)

    def _printSuccess(res):
        ui.status(s.getSuccessString(res) + "\n")

    def _printFailure(why):
        ui.warn(s.getFailureString(why) + "\n")

    d.addCallbacks(_printSuccess, _printFailure)
    d.addBoth(lambda _: reactor.stop())
    reactor.run()

    if fork:
        os._exit(os.EX_OK)
    else:
        return
Exemplo n.º 25
0
def hook(ui, repo, hooktype, node=None, source=None, **kwargs):
    # read config parameters
    master = ui.config('hgbuildbot', 'master')
    if master:
        branchtype = ui.config('hgbuildbot', 'branchtype')
        branch = ui.config('hgbuildbot', 'branch')
    else:
        ui.write("* You must add a [hgbuildbot] section to .hg/hgrc in "
                 "order to use buildbot hook\n")
        return

    if branch is None:
        if branchtype is not None:
            if branchtype == 'dirname':
                branch = os.path.basename(os.getcwd())
            if branchtype == 'inrepo':
                branch = workingctx(repo).branch()

    if hooktype == 'changegroup':
        s = sendchange.Sender(master, None)
        d = defer.Deferred()
        reactor.callLater(0, d.callback, None)
        # process changesets
        def _send(res, c):
            ui.status("rev %s sent\n" % c['revision'])
            return s.send(c['branch'], c['revision'], c['comments'],
                          c['files'], c['username'])

        try:    # first try Mercurial 1.1+ api
            start = repo[node].rev()
            end = len(repo)
        except TypeError:   # else fall back to old api
            start = repo.changelog.rev(bin(node))
            end = repo.changelog.count()

        for rev in xrange(start, end):
            # send changeset
            node = repo.changelog.node(rev)
            manifest, user, (time, timezone), files, desc, extra = repo.changelog.read(node)
            parents = filter(lambda p: not p == nullid, repo.changelog.parents(node))
            if branchtype == 'inrepo':
                branch = extra['branch']
            # merges don't always contain files, but at least one file is required by buildbot
            if len(parents) > 1 and not files:
                files = ["merge"]
            change = {
                'master': master,
                'username': user,
                'revision': hex(node),
                'comments': desc,
                'files': files,
                'branch': branch
            }
            d.addCallback(_send, change)

        d.addCallbacks(s.printSuccess, s.printFailure)
        d.addBoth(s.stop)
        s.run()
    else:
        ui.status(_('hgbuildbot: hook %s not supported\n') % hooktype)
    return
Exemplo n.º 26
0
def do_check_style(hgui, repo, *pats, **opts):
    """check files for proper m5 style guidelines

    Without an argument, checks all modified and added files for gem5
    coding style violations. A list of files can be specified to limit
    the checker to a subset of the repository. The style rules are
    normally applied on a diff of the repository state (i.e., added
    files are checked in their entirety while only modifications of
    modified files are checked).

    The --all option can be specified to include clean files and check
    modified files in their entirety.
    """
    from mercurial import mdiff, util

    opt_fix_white = opts.get('fix_white', False)
    opt_all = opts.get('all', False)
    opt_no_ignore = opts.get('no_ignore', False)
    ui = MercurialUI(hgui, hgui.verbose, opt_fix_white)

    def prompt(name, func, regions=all_regions):
        result = ui.prompt("(a)bort, (i)gnore, or (f)ix?", 'aif', 'a')
        if result == 'a':
            return True
        elif result == 'f':
            func(repo.wjoin(name), regions)

        return False

    # Import the match (repository file name matching helper)
    # function. Different versions of Mercurial keep it in different
    # modules and implement them differently.
    try:
        from mercurial import scmutil
        m = scmutil.match(repo[None], pats, opts)
    except ImportError:
        from mercurial import cmdutil
        m = cmdutil.match(repo, pats, opts)

    modified, added, removed, deleted, unknown, ignore, clean = \
        repo.status(match=m, clean=opt_all)
    if not opt_all:
        try:
            wctx = repo.workingctx()
        except:
            from mercurial import context
            wctx = context.workingctx(repo)

        files = [ (fn, all_regions) for fn in added ] + \
            [ (fn,  modregions(wctx, fn)) for fn in modified ]
    else:
        files = [(fn, all_regions) for fn in added + modified + clean]

    whitespace = Whitespace(ui)
    sorted_includes = SortedIncludes(ui)
    for fname, mod_regions in files:
        if not opt_no_ignore and check_ignores(fname):
            continue

        fpath = joinpath(repo.root, fname)

        if whitespace.apply(fpath, prompt, mod_regions):
            return True

        if sorted_includes.apply(fpath, prompt, mod_regions):
            return True

    return False
Exemplo n.º 27
0
def do_check_style(hgui, repo, *files, **args):
    """check files for proper m5 style guidelines"""
    from mercurial import mdiff, util

    auto = args.get('auto', False)
    if auto:
        auto = 'f'
    ui = MercurialUI(hgui, hgui.verbose, auto)

    if files:
        files = frozenset(files)

    def skip(name):
        # We never want to handle symlinks, so always skip them: If the location
        # pointed to is a directory, skip it. If the location is a file inside
        # the gem5 directory, it will be checked as a file, so symlink can be
        # skipped. If the location is a file outside gem5, we don't want to
        # check it anyway.
        if os.path.islink(name):
            return True
        return files and name in files

    def prompt(name, func, regions=all_regions):
        result = ui.prompt("(a)bort, (i)gnore, or (f)ix?", 'aif', 'a')
        if result == 'a':
            return True
        elif result == 'f':
            func(repo.wjoin(name), regions)

        return False

    modified, added, removed, deleted, unknown, ignore, clean = repo.status()

    whitespace = Whitespace(ui)
    sorted_includes = SortedIncludes(ui)
    for fname in added:
        if skip(fname):
            continue

        fpath = joinpath(repo.root, fname)

        if whitespace.apply(fpath, prompt):
            return True

        if sorted_includes.apply(fpath, prompt):
            return True

    try:
        wctx = repo.workingctx()
    except:
        from mercurial import context
        wctx = context.workingctx(repo)

    for fname in modified:
        if skip(fname):
            continue

        fpath = joinpath(repo.root, fname)
        regions = modregions(wctx, fname)

        if whitespace.apply(fpath, prompt, regions):
            return True

        if sorted_includes.apply(fpath, prompt, regions):
            return True

    return False
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.

from mercurial import (
    changelog,
    context,
    hg,
    ui,
)

changelog_add = changelog.changelog.add

def add(self, manifest, files, desc, transaction, p1, p2,
        user, date=None, extra=None):
    files = ['foo', 'bar']
    return changelog_add(self, manifest, files, desc, transaction, p1, p2,
        user, date, extra)

changelog.changelog.add = add


if __name__ == '__main__':
    ui = ui.ui()
    repo = hg.repository(ui)
    default_date = '0 0'
    cctx = context.workingctx(repo, 'corrupted', 'foo', default_date,
        {'rebase_source': '0123456789012345678901234567890123456789'})
    repo.commitctx(cctx)