Beispiel #1
0
 def getMsg(self, stub, name, typ, opts):
     if not name:
         raise s_exc.BadSyntaxError(mesg='Action requires a name')
     args = {typ: name}
     admin = opts.pop('admin', None)
     if admin and typ == 'user':
         msg = s_tufo.tufo(':'.join([stub, 'admin']),
                           **args)
         return msg
     role = opts.pop('role', None)
     if role and typ == 'user':
         args['role'] = role
         msg = s_tufo.tufo(':'.join([stub, 'urole']),
                           **args)
         return msg
     rulefo = self.formRulefo(opts)
     if rulefo is None:
         msg = s_tufo.tufo(':'.join([stub, typ]),
                           **args)
         return msg
     mod = self.modmap.get(typ)
     if not mod:  # pragma: no cover
         raise s_exc.BadSyntaxError(mesg='Unknown type encountered',
                                    type=typ)
     args['rule'] = rulefo
     msg = s_tufo.tufo(':'.join([stub, mod]),
                       **args)
     return msg
Beispiel #2
0
def parse_string(text, off, trim=True):

    if text[off] not in ('"', "'"): # lulz...
        raise s_exc.BadSyntaxError(expected='String Literal', at=off)

    quot = text[off]

    if trim:
        _, off = nom(text, off, whites)

    off += 1
    vals = []
    while text[off] != quot:

        c = text[off]

        off += 1
        if c == '\\':
            c = text[off]
            off += 1

        vals.append(c)

    off += 1

    if trim:
        _, off = nom(text, off, whites)

    return ''.join(vals), off
Beispiel #3
0
def parse_list(text, off=0, trim=True):
    '''
    Parse a list (likely for comp type) coming from a command line input.

    The string elements within the list may optionally be quoted.
    '''

    if not nextchar(text, off, '('):
        raise s_exc.BadSyntaxError(at=off, mesg='expected open paren for list')

    off += 1

    valus = []
    while off < len(text):

        _, off = nom(text, off, whites)

        valu, off = parse_valu(text, off)

        _, off = nom(text, off, whites)

        # check for foo=bar kw tuple syntax
        if nextchar(text, off, '='):

            _, off = nom(text, off + 1, whites)

            vval, off = parse_valu(text, off)

            _, off = nom(text, off, whites)

            valu = (valu, vval)

        valus.append(valu)

        _, off = nom_whitespace(text, off)

        if nextchar(text, off, ')'):
            return valus, off + 1

        if not nextchar(text, off, ','):
            raise s_exc.BadSyntaxError(at=off, text=text, mesg='expected comma in list')

        off += 1

    raise s_exc.BadSyntaxError(at=off, mesg='unexpected and of text during list')
Beispiel #4
0
 def formRulefo(self, opts):
     rtype = opts.pop('rule', None)
     if not rtype:
         return None
     form = opts.get('form')
     prop = opts.get('prop')
     tag = opts.get('tag')
     if tag:
         if form or prop:
             raise s_exc.BadSyntaxError(mesg='Cannot form rulefo with tag and (form OR prop)')
         else:
             return s_tufo.tufo(rtype, tag=tag)
     if form and prop:
         return s_tufo.tufo(rtype, form=form, prop=prop)
     if form and not prop:
         return s_tufo.tufo(rtype, form=form)
     raise s_exc.BadSyntaxError(mesg='Unable to form rulefo',
                                prop=prop, form=form, tag=tag, rule=rtype)
Beispiel #5
0
 def exit(self, status=0, message=None):
     '''
     Argparse expects exit() to be a terminal function and not return.
     As such, this function must raise an exception which will be caught
     by Cmd.hasValidOpts.
     '''
     self.exited = True
     if message is not None:
         self.mesgs.extend(message.split('\n'))
     raise s_exc.BadSyntaxError(mesg=message, prog=self.prog, status=status)
Beispiel #6
0
def parse_int(text, off, trim=True):

    _, off = nom(text, off, whites)

    neg = False
    if nextchar(text, off, '-'):
        neg = True
        _, off = nom(text, off + 1, whites)

    valu = None
    if nextstr(text, off, '0x'):
        valu, off = nom(text, off + 2, hexset)
        if not valu:
            raise s_exc.BadSyntaxError(at=off, mesg='0x expected hex')
        valu = int(valu, 16)

    elif nextstr(text, off, '0b'):
        valu, off = nom(text, off + 2, binset)
        if not valu:
            raise s_exc.BadSyntaxError(at=off, mesg='0b expected bits')
        valu = int(valu, 2)

    else:

        valu, off = nom(text, off, decset)
        if not valu:
            raise s_exc.BadSyntaxError(at=off, mesg='expected digits')

        if not nextchar(text, off, '.'):
            valu = int(valu)

        else:
            frac, off = nom(text, off + 1, decset)
            valu = float('%s.%s' % (valu, frac))

    if neg:
        valu = -valu

    return valu, off
Beispiel #7
0
def parse_float(text, off, trim=True):

    _, off = nom(text, off, whites)

    valu = ''
    if nextchar(text, off, '-'):
        valu += '-'
        _, off = nom(text, off + 1, whites)

    digs, off = nom(text, off, decset)
    if not digs:
        raise s_exc.BadSyntaxError(at=off, mesg='expected digits')

    valu += digs

    if nextchar(text, off, '.'):
        frac, off = nom(text, off + 1, decset)
        if not frac:
            raise s_exc.BadSyntaxError(at=off, mesg='expected .<digits>')

        valu = valu + '.' + frac

    return float(valu), off
Beispiel #8
0
def parse_cmd_kwarg(text, off=0):
    '''
    Parse a foo:bar=<valu> kwarg into (prop,valu),off
    '''
    _, off = nom(text, off, whites)

    prop, off = nom(text, off, varset)

    _, off = nom(text, off, whites)

    if not nextchar(text, off, '='):
        raise s_exc.BadSyntaxError(expected='= for kwarg ' + prop, at=off)

    _, off = nom(text, off + 1, whites)

    valu, off = parse_cmd_string(text, off)
    return (prop, valu), off
Beispiel #9
0
    def runCmdOpts(self, opts):
        core = self.getCmdItem()  # type: s_auth.AuthMixin

        act = opts.pop('act')
        typ = opts.pop('type')
        name = opts.pop('name', None)
        astub = 'auth:add'
        dstub = 'auth:del'

        # Form our mesg
        if act == 'get':
            if name:
                mesg = s_tufo.tufo('auth:req:%s' % typ,
                                   **{self.typmap.get(typ): name})
            else:
                mesg = ('auth:get:%s' % self.getmap.get(typ),
                        {})
        elif act == 'add':
            mesg = self.getMsg(astub, name, typ, opts)
        elif act == 'del':
            mesg = self.getMsg(dstub, name, typ, opts)
        else:  # pragma: no cover
            raise s_exc.BadSyntaxError(mesg='Unknown action provided',
                                       act=act)

        # Execute remote call
        isok, retn = core.authReact(mesg)
        retn = s_common.reqok(isok, retn)

        # Format output
        if opts.get('json'):
            outp = json.dumps(retn, indent=2, sort_keys=True)
        else:
            width, _ = shutil.get_terminal_size((120, 24))
            if width == 0:
                # In CI we may not have a tty available.
                width = 120
            outp = pprint.pformat(retn, width=width)
        self.printf(outp)
        return retn
Beispiel #10
0
    async def execStormCmd(self, runt, genr):

        minvalu = None
        minitem = None

        pname = self.opts.propname
        prop = None
        if not pname.startswith((':', '.')):
            # Are we a full prop name?
            prop = runt.snap.core.model.prop(pname)
            if prop is None or prop.isform:
                mesg = f'{self.name} argument requires a relative secondary ' \
                    f'property name or a full path to the secondary property.'
                raise s_exc.BadSyntaxError(mesg=mesg, valu=pname)

        if prop:
            name = prop.name
            form = prop.form
        else:
            form = None
            name = pname.strip(':')

        async for node, path in genr:

            if form and node.form is not form:
                continue

            valu = node.get(name)
            if valu is None:
                continue

            if minvalu is None or valu < minvalu:
                minvalu = valu
                minitem = (node, path)

        if minitem:
            yield minitem
Beispiel #11
0
    def getCmdOpts(self, text):
        '''
        Use the _cmd_syntax def to split/parse/normalize the cmd line.

        Args:
            text (str): Command to process.

        Notes:
            This is implemented independent of argparse (et al) due to the
            need for syntax aware argument splitting. Also, allows different
            split per command type

        Returns:
            dict: An opts dictionary.
        '''
        off = 0

        _, off = s_syntax.nom(text, off, s_syntax.whites)

        name, off = s_syntax.meh(text, off, s_syntax.whites)

        _, off = s_syntax.nom(text, off, s_syntax.whites)

        opts = {}

        args = collections.deque([synt for synt in self._cmd_syntax if not synt[0].startswith('-')])

        switches = {synt[0]: synt for synt in self._cmd_syntax if synt[0].startswith('-')}

        # populate defaults and lists
        for synt in self._cmd_syntax:
            snam = synt[0].strip('-')

            defval = synt[1].get('defval')
            if defval is not None:
                opts[snam] = defval

            if synt[1].get('type') in ('list', 'kwlist'):
                opts[snam] = []

        def atswitch(t, o):
            # check if we are at a recognized switch.  if not
            # assume the data is part of regular arguments.
            if not text.startswith('-', o):
                return None, o

            name, x = s_syntax.meh(t, o, s_syntax.whites)
            swit = switches.get(name)
            if swit is None:
                return None, o

            return swit, x

        while off < len(text):

            _, off = s_syntax.nom(text, off, s_syntax.whites)

            swit, off = atswitch(text, off)
            if swit is not None:

                styp = swit[1].get('type', 'flag')
                snam = swit[0].strip('-')

                if styp == 'valu':
                    valu, off = s_syntax.parse_cmd_string(text, off)
                    opts[snam] = valu

                elif styp == 'list':
                    valu, off = s_syntax.parse_cmd_string(text, off)
                    if not isinstance(valu, list):
                        valu = valu.split(',')
                    opts[snam].extend(valu)

                elif styp == 'enum':
                    vals = swit[1].get('enum:vals')
                    valu, off = s_syntax.parse_cmd_string(text, off)
                    if valu not in vals:
                        raise s_exc.BadSyntaxError(mesg='%s (%s)' % (swit[0], '|'.join(vals)),
                                                   text=text)

                    opts[snam] = valu

                else:
                    opts[snam] = True

                continue

            if not args:
                raise s_exc.BadSyntaxError(mesg='trailing text: [%s]' % (text[off:],),
                                           text=text)

            synt = args.popleft()
            styp = synt[1].get('type', 'valu')

            # a glob type eats the remainder of the string
            if styp == 'glob':
                opts[synt[0]] = text[off:]
                break

            # eat the remainder of the string as separate vals
            if styp == 'list':
                valu = []

                while off < len(text):
                    item, off = s_syntax.parse_cmd_string(text, off)
                    valu.append(item)

                opts[synt[0]] = valu
                break

            if styp == 'kwlist':
                kwlist, off = s_syntax.parse_cmd_kwlist(text, off)
                opts[snam] = kwlist
                break

            valu, off = s_syntax.parse_cmd_string(text, off)
            opts[synt[0]] = valu

        return opts