Ejemplo n.º 1
0
 def _log(self, ui, event, msg, opts):
     default = ui.configdate(b'devel', b'default-date')
     date = dateutil.datestr(default, ui.config(b'blackbox',
                                                b'date-format'))
     user = procutil.getuser()
     pid = b'%d' % procutil.getpid()
     changed = b''
     ctx = self._repo[None]
     parents = ctx.parents()
     rev = b'+'.join([hex(p.node()) for p in parents])
     if ui.configbool(b'blackbox', b'dirty') and ctx.dirty(
             missing=True, merge=False, branch=False):
         changed = b'+'
     if ui.configbool(b'blackbox', b'logsource'):
         src = b' [%s]' % event
     else:
         src = b''
     try:
         fmt = b'%s %s @%s%s (%s)%s> %s'
         args = (date, user, rev, changed, pid, src, msg)
         with loggingutil.openlogfile(
                 ui,
                 self._repo.vfs,
                 name=b'blackbox.log',
                 maxfiles=self._maxfiles,
                 maxsize=self._maxsize,
         ) as fp:
             fp.write(fmt % args)
     except (IOError, OSError) as err:
         # deactivate this to avoid failed logging again
         self._trackedevents.clear()
         ui.debug(b'warning: cannot write to blackbox.log: %s\n' %
                  encoding.strtolocal(err.strerror))
         return
     _lastlogger.logger = self
Ejemplo n.º 2
0
def _getorcreateinfinitepushlogger(op):
    logger = op.records['infinitepushlogger']
    if not logger:
        ui = op.repo.ui
        try:
            username = procutil.getuser()
        except Exception:
            username = '******'
        # Generate random request id to be able to find all logged entries
        # for the same request. Since requestid is pseudo-generated it may
        # not be unique, but we assume that (hostname, username, requestid)
        # is unique.
        random.seed()
        requestid = random.randint(0, 2000000000)
        hostname = socket.gethostname()
        logger = functools.partial(ui.log,
                                   'infinitepush',
                                   user=username,
                                   requestid=requestid,
                                   hostname=hostname,
                                   reponame=ui.config('infinitepush',
                                                      'reponame'))
        op.records.add('infinitepushlogger', logger)
    else:
        logger = logger[0]
    return logger
Ejemplo n.º 3
0
def hook(ui, repo, hooktype, node=None, source=None, **kwargs):

    ensureenabled(ui)

    if hooktype not in ['pretxnchangegroup', 'pretxncommit', 'prepushkey']:
        raise error.Abort(
            _('config error - hook type "%s" cannot stop '
              'incoming changesets, commits, nor bookmarks') % hooktype)
    if (hooktype == 'pretxnchangegroup'
            and source not in ui.configlist('acl', 'sources')):
        ui.debug('acl: changes have source "%s" - skipping\n' % source)
        return

    user = None
    if source == 'serve' and r'url' in kwargs:
        url = kwargs[r'url'].split(':')
        if url[0] == 'remote' and url[1].startswith('http'):
            user = urlreq.unquote(url[3])

    if user is None:
        user = procutil.getuser()

    ui.debug('acl: checking access for user "%s"\n' % user)

    if hooktype == 'prepushkey':
        _pkhook(ui, repo, hooktype, node, source, user, **kwargs)
    else:
        _txnhook(ui, repo, hooktype, node, source, user, **kwargs)
Ejemplo n.º 4
0
        def log(self, event, *msg, **opts):
            global lastui
            super(blackboxui, self).log(event, *msg, **opts)

            if not '*' in self.track and not event in self.track:
                return

            if self._bbvfs:
                ui = self
            else:
                # certain ui instances exist outside the context of
                # a repo, so just default to the last blackbox that
                # was seen.
                ui = lastui

            if not ui:
                return
            vfs = ui._bbvfs
            if not vfs:
                return

            repo = getattr(ui, '_bbrepo', None)
            if not lastui or repo:
                lastui = ui
            if getattr(ui, '_bbinlog', False):
                # recursion and failure guard
                return
            ui._bbinlog = True
            default = self.configdate('devel', 'default-date')
            date = dateutil.datestr(default, '%Y/%m/%d %H:%M:%S')
            user = procutil.getuser()
            pid = '%d' % procutil.getpid()
            formattedmsg = msg[0] % msg[1:]
            rev = '(unknown)'
            changed = ''
            if repo:
                ctx = repo[None]
                parents = ctx.parents()
                rev = ('+'.join([hex(p.node()) for p in parents]))
                if (ui.configbool('blackbox', 'dirty') and ctx.dirty(
                        missing=True, merge=False, branch=False)):
                    changed = '+'
            if ui.configbool('blackbox', 'logsource'):
                src = ' [%s]' % event
            else:
                src = ''
            try:
                fmt = '%s %s @%s%s (%s)%s> %s'
                args = (date, user, rev, changed, pid, src, formattedmsg)
                with _openlogfile(ui, vfs) as fp:
                    fp.write(fmt % args)
            except (IOError, OSError) as err:
                self.debug('warning: cannot write to blackbox.log: %s\n' %
                           encoding.strtolocal(err.strerror))
                # do not restore _bbinlog intentionally to avoid failed
                # logging again
            else:
                ui._bbinlog = False
Ejemplo n.º 5
0
def hook(ui, repo, hooktype, node=None, source=None, **kwargs):

    ensureenabled(ui)

    if hooktype not in ['pretxnchangegroup', 'pretxncommit']:
        raise error.Abort(_('config error - hook type "%s" cannot stop '
                           'incoming changesets nor commits') % hooktype)
    if (hooktype == 'pretxnchangegroup' and
        source not in ui.configlist('acl', 'sources')):
        ui.debug('acl: changes have source "%s" - skipping\n' % source)
        return

    user = None
    if source == 'serve' and r'url' in kwargs:
        url = kwargs[r'url'].split(':')
        if url[0] == 'remote' and url[1].startswith('http'):
            user = urlreq.unquote(url[3])

    if user is None:
        user = procutil.getuser()

    ui.debug('acl: checking access for user "%s"\n' % user)

    # deprecated config: acl.config
    cfg = ui.config('acl', 'config')
    if cfg:
        ui.readconfig(cfg, sections=['acl.groups', 'acl.allow.branches',
            'acl.deny.branches', 'acl.allow', 'acl.deny'])

    allowbranches = buildmatch(ui, None, user, 'acl.allow.branches')
    denybranches = buildmatch(ui, None, user, 'acl.deny.branches')
    allow = buildmatch(ui, repo, user, 'acl.allow')
    deny = buildmatch(ui, repo, user, 'acl.deny')

    for rev in xrange(repo[node].rev(), len(repo)):
        ctx = repo[rev]
        branch = ctx.branch()
        if denybranches and denybranches(branch):
            raise error.Abort(_('acl: user "%s" denied on branch "%s"'
                               ' (changeset "%s")')
                               % (user, branch, ctx))
        if allowbranches and not allowbranches(branch):
            raise error.Abort(_('acl: user "%s" not allowed on branch "%s"'
                               ' (changeset "%s")')
                               % (user, branch, ctx))
        ui.debug('acl: branch access granted: "%s" on branch "%s"\n'
        % (ctx, branch))

        for f in ctx.files():
            if deny and deny(f):
                raise error.Abort(_('acl: user "%s" denied on "%s"'
                ' (changeset "%s")') % (user, f, ctx))
            if allow and not allow(f):
                raise error.Abort(_('acl: user "%s" not allowed on "%s"'
                ' (changeset "%s")') % (user, f, ctx))
        ui.debug('acl: path access granted: "%s"\n' % ctx)
Ejemplo n.º 6
0
    def __init__(self, repo):
        self.user = procutil.getuser()
        self.ui = repo.ui
        self.vfs = repo.vfs

        # is this working copy using a shared storage?
        self.sharedfeatures = self.sharedvfs = None
        if repo.shared():
            features = _readsharedfeatures(repo)
            sharedrepo = hg.sharedreposource(repo)
            if sharedrepo is not None and b'journal' in features:
                self.sharedvfs = sharedrepo.vfs
                self.sharedfeatures = features
Ejemplo n.º 7
0
def hook(ui, repo, hooktype, node=None, **kwargs):
    def warn(message):
        if node:
            ui.warn(message)

    def write(message):
        if node:
            ui.write(message)

    url = ui.config("httphooks", 'url')
    if not url:
        warn('httphooks.url is null')
        return -2
    try:
        changesets = list()
        if node and repo:
            for rev in xrange(repo[node].rev(), len(repo)):
                item = repo[rev]
                change = createCommitInfo(item, 2)

                changesets.append(change)
        data = {
            'Commits': changesets,
            'HookType': hooktype,
            'UserName': procutil.getuser()
        }
        #write('{}\n'.format(json.dumps(data)))
        resp = requests.post(url, json=data)
        #write('{}\n'.format(resp.text))
        result = resp.json()
        if result['success']:
            if result['message']:
                write('{}\n'.format(result['message']))
            return 0
        if result['message']:
            warn('{}\n'.format(result['message']))
            return 1
    except Exception as ee:
        warn('Exception: {}\n'.format(ee))
    return -1