view lineend.py @ 63:a96f824d1a24

use searchString
author catherine@Elli.myhome.westell.com
date Sat, 21 Jun 2008 19:46:33 -0400
parents 95e239c87010
children a0f7702f2a4b
line wrap: on
line source

import pyparsing, sys, doctest

intgr = pyparsing.Optional(pyparsing.Word(pyparsing.nums))
terminators = [pyparsing.Literal(';') + intgr,
               pyparsing.Literal('\\t') + intgr]
complete_pattern = reduce(lambda x, y: x ^ y, terminators)
#complete_pattern = (pyparsing.Literal(';') + intgr) ^ (pyparsing.Literal('\\t') + intgr)
complete_pattern.ignore(pyparsing.sglQuotedString)
complete_pattern.ignore(pyparsing.dblQuotedString)

redirect_pattern = pyparsing.oneOf('< >') + pyparsing.restOfLine
redirect_pattern.ignore(pyparsing.sglQuotedString)
redirect_pattern.ignore(pyparsing.dblQuotedString)

pipe_pattern = pyparsing.Literal('|') + pyparsing.restOfLine
pipe_pattern.ignore(pyparsing.sglQuotedString)
pipe_pattern.ignore(pyparsing.dblQuotedString)

def parse(txt, mustBeTerminated=False):
    """
    >>> sorted(parse('select * from dual;', True).items())
    [('inputFrom', None), ('outputTo', None), ('pipeTo', None), ('terminator', [';'])]
    >>> sorted(parse('select * from dual E', True).items())
    [('inputFrom', None), ('outputTo', None), ('pipeTo', None), ('terminator', None)]
    >>> sorted(parse('select * from', True).items())
    [('inputFrom', None), ('outputTo', None), ('pipeTo', None), ('terminator', None)]
    >>> sorted(parse('select * from dual; > result.txt', True).items())
    [('inputFrom', None), ('outputTo', 'result.txt'), ('pipeTo', None), ('terminator', [';'])]
    >>> sorted(parse("select * from dual where val = 'x > y'", True).items())
    [('inputFrom', None), ('outputTo', None), ('pipeTo', None), ('terminator', None)]
    >>> sorted(parse('select * from dual; | wc -c', True).items())
    [('inputFrom', None), ('outputTo', None), ('pipeTo', ' wc -c'), ('terminator', [';'])]
    >>> sorted(parse('select * from dual; | sort > sorted.txt', True).items())
    [('inputFrom', None), ('outputTo', None), ('pipeTo', 'sort > sorted.txt'), ('terminator', [';'])]    
    """
    result = {'inputFrom': None, 'outputTo': None, 'pipeTo': None, 'terminator': None}
    found = complete_pattern.searchString(txt)
    if found:
        result['terminator'] = found[0][:]
    found = redirect_pattern.searchString(txt)
    if found:
        if found[0][0] == '>':
            result['outputTo'] = found[0][1].strip()
        else:
            result['inputFrom'] = found[0][1].strip()
    found = pipe_pattern.searchString(txt)
    if found:
        result['pipeTo'] = found[0][1].strip()

    return result
    
if __name__ == '__main__':
    doctest.testmod()