Example #1
0
            parent_class = match["parent_class"]
            var_decl = re.compile(VAR_DECL_FMT % locals(), re.VERBOSE)
            _, var_decl_match = self.find_line(var_decl)
            expanded_parent_class = \
                var_decl_match.get('expanded_parent_class') if var_decl_match \
                else None
            args = {
                'leading_space': match['leading_space'],
                'parent_class': expanded_parent_class or parent_class,
            }
            self.insert_range(start, [e % args for e in EXTENDS_FMT])


class StreamEditorInjectContructor(StreamEditor):
    table = [
        [[WGEN_FUNCTION, ACCEPT], ],
    ]

    def apply_match(self, i, dict_matches):
        self.insert_range(dict_matches["start"], CONSTRUCTOR_FMT)


if __name__ == '__main__':
    StreamEditors = [
        StreamEditorInjectNamespace,
        StreamEditorInjectContructor,
        StreamEditorInjectExtends,
    ]
    for streamEditor in StreamEditors:
        call_main(streamEditor)
Example #2
0
from sed.engine.sed_regex import COMMENT_OPEN, COMMENT_CLOSE, BLANK_LINE, ALL


# Find consecutive jsdoc comments
#   /**
#   ...
#    */
#   /**
#   ...
#    */
# -----
# delete intermediate end and start
class StreamEditorCommentMerge(StreamEditor):
    table = [
        [[COMMENT_OPEN, NEXT], ],
        [[COMMENT_CLOSE, NEXT], ],
        # Allow a new comment or a blank line, but bail otherwise
        [[COMMENT_OPEN, NEXT], [BLANK_LINE, REPEAT], [ALL, REJECT], ],
        [[COMMENT_CLOSE, ACCEPT], ],
    ]

    def apply_match(self, i, dict_matches):
        end, matches = dict_matches["end"], dict_matches["matches"]
        if not (end is None):
            delete_start = matches[1]['line_no']
            delete_end = matches[2]['line_no']
            self.delete_range((delete_start, delete_end))

if __name__ == '__main__':
    call_main(StreamEditorCommentMerge)
Example #3
0
    ]

    def apply_match(self, i, dict_matches):
        start, end, matches = \
            dict_matches["start"], dict_matches["end"], dict_matches["matches"]
        if not (end is None):
            decl = matches[0]["decl"]
            extend = matches[0]["extend"]
            events = matches[1:-1]
            pairs = [(event["selector"], event["function"]) for event in events]
            new_lines = build_newlines(decl, pairs)
            new_event = "\t\t%s: _.extend(%s)," % (decl, extend)
            initialize, _ = self.find_line(INITIALIZE_MATCH)
            if initialize is not None:
                if start < initialize:
                    self.append_range(initialize, new_lines)
                    self.replace_range((start, end + 1), [new_event])
                else:
                    self.replace_range((start, end + 1), [new_event])
                    self.append_range(initialize, new_lines)
                self.entab()
            else:
                stderr.write("*** %s: missing initialize\n" % self.filename)
        else:
            stderr.write("%s: match started at %d\n" % (self.filename, start),
                         matches)


if __name__ == '__main__':
    call_main(StreamEditorExtendEventsDecl)
Example #4
0
from sed.engine import (
    StreamEditor,
    call_main,
    ACCEPT
)
from sed.engine.sed_regex import FUNCTION_HEADER

FMT = """%(leading_space)s'%(function_header)s' : """ \
      """function (%(arg_list)s) %(rest)s"""


# Match all functions in the class
# -----
# Quote the function name of all functions not already quoted
class StreamEditorQuoteFunctions(StreamEditor):
    table = [
        [[FUNCTION_HEADER, ACCEPT], ],
    ]

    def apply_match(self, i, dict_matches):
        end, matches = dict_matches["end"], dict_matches["matches"]
        if (end is not None):
            for match in matches:
                line_no = match["line_no"]
                self.replace_range((line_no, line_no + 1), [FMT % match])


if __name__ == '__main__':
    call_main(StreamEditorQuoteFunctions)
PRIVATE_DELEGATE_EVENTS_REGEX = re.compile(
    r"""
    ^
    \s+
    _delegateEvents
    \s:\s
    function\s+\(events\)
    \s+
    \{
""",
    re.VERBOSE,
)

BACKBONE_PATCH = ["\t\t\tBackbone.View.prototype.delegateEvents.call(this, events);", "\t\t\treturn;"]


class StreamEditorRevertDelegateEvents(StreamEditor):
    table = [[[PRIVATE_DELEGATE_EVENTS_REGEX, ACCEPT]]]

    def apply_match(self, i, dict_matches):
        self.append_range(dict_matches["start"], BACKBONE_PATCH)
        self.entab()


if __name__ == "__main__":
    # import os.path
    # path = os.path.expandvars(VIEW)
    # call_main([path], StreamEditorRevertDelegateEvents)
    call_main(StreamEditorRevertDelegateEvents)
Example #6
0
def main():
    """ Main entry point"""
    return call_main(StreamEditorAutoPylint)
    if not sum([parens, brackets, braces]):
        return ACCEPT
    elif matches['matches']:
        return REPEAT
    else:
        return NEXT


class StreamEditorRewriteAppGet(StreamEditor):
    table = [
        [[APP_GET, test_function], ], 
        [[ANY, test_function], ],
    ]

    def apply_match(self, i, dict_matches):
        matches = dict_matches['matches']
        first = matches[0]
        leading = first['leading_space']
        tabs = len(leading) / 4
        prefix = '\t' * (tabs + 1)
        content = [first['content'][1:]] + [m['content'] for m in matches[1:]]
        result = [leading + first['assign'] + first['app_get'] + '('] + \
            [prefix + c for c in content]
        loc = (dict_matches["start"], dict_matches["end"] + 1)
        self.replace_range(loc, result)
        self.entab()


if __name__ == '__main__':
    call_main(StreamEditorRewriteAppGet)
Example #8
0
    """
    Stream editor for multi-line docstrings
    """
    table = [
        [[FN_DECL_FMT, NEXT], ],
        [[DOCSTRING_START, NEXT], [ANY, REJECT], ],
        [[DOCSTRING_END, ACCEPT], [CONTENT, REPEAT], ],
    ]

    def __init__(self, filename, verbose=False):
        StreamEditorDocstring.__init__(self, filename, verbose)


class StreamEditorDocstringSingle(StreamEditorDocstring):
    """
    Stream editor for single line docstrings
    """
    table = [
        [[FN_DECL_FMT, NEXT], ],
        [[DOCSTRING_FMT, ACCEPT], [ANY, REJECT]],
    ]

    def __init__(self, filename, verbose=False):
        StreamEditorDocstring.__init__(self, filename, verbose)


if __name__ == '__main__':
    editors = (StreamEditorDocstringSingle, StreamEditorDocstringMulti, )
    for editor in editors:
        call_main(editor)
#!/usr/bin/env python

from sed.engine import (
    StreamEditor,
    call_main,
    ACCEPT
)
from sed.engine.sed_regex import FUNCTION_HEADER, PRIVATE_FMT


# Match all functions in the class
# -----
# Quote the function name of all functions not already quoted
class StreamEditorInjectPrivate(StreamEditor):
    table = [
        [[FUNCTION_HEADER, ACCEPT], ],
    ]

    def apply_match(self, i, dict_matches):
        for match in dict_matches["matches"]:
            function_header = match["function_header"]
            if function_header.startswith('_') or function_header.endswith('_'):
                line_no = match["line_no"]
                self.insert_range(line_no, [p % match for p in PRIVATE_FMT])

if __name__ == '__main__':
    call_main(StreamEditorInjectPrivate)
Example #10
0
class StreamEditorModifyEventsWithinMethod(StreamEditor):
    table = [
        [[FUNCTION_HEADER, NEXT], ],
        [[VAR_DECL, NEXT], [END_DECL, REJECT], ],
        [[SELECTOR, 2], [END_VAR_DECL, NEXT], ],
        [[VAR_DECL, 2], [END_DECL, ACCEPT], ],
    ]

    def apply_match(self, i, dict_matches):
        end, matches = dict_matches["end"], dict_matches["matches"]
        assert not (end is None)
        # Discard function header and closing end_decl
        events = matches[1:-1]
        # var_decl and end_decl must be balanced
        var_starts = [i for i, e in enumerate(events) if 'var_decl' in e]
        var_ends = [i for i, e in enumerate(events) if 'end_decl' in e]
        assert len(var_starts) == len(var_ends)
        for v_start, v_end in zip(var_starts, var_ends):
            var_events = events[v_start + 1: v_end]
            if var_events:
                new_lines = build_pairs([
                    (ve["selector"], ve["function"])
                    for ve in var_events])
                loc = (var_events[0]["line_no"], \
                    var_events[-1]["line_no"] + 1)
                self.replace_range(loc, new_lines)
                self.entab()

if __name__ == '__main__':
    call_main(StreamEditorModifyEventsWithinMethod)
Example #11
0
                                                 self.lines[start:end]):
                matching = constraint_d["constraint_name"]
                src = start + constraint_i
                self.lines[src] = self.lines[src].replace(
                    matching, new_constraint_name)

            # Change segment name
            column_names = ["counter"]
            underscore_column_names = ",".join(column_names)
            comma_column_names = ",".join(column_names)
            new_segment_name = "[PS_{0}_DA]([{1}])".format(
                underscore_column_names, comma_column_names)
            old_segment_name = re.compile(
                r"""^.*\s+ON\s+(?P<segment>\[PRIMARY\])""")
            for (segment_i,
                 segment_d) in self.find_line(old_segment_name,
                                              self.lines[start:end]):
                matching = segment_d["segment"]
                src = start + segment_i
                self.lines[src] = self.lines[src].replace(
                    matching, new_segment_name)

            # Trim off unrelated stuff from file
            file_end = len(self.lines)
            self.delete_range((end + 1, file_end - 1))
            self.delete_range((0, start - 1))


if __name__ == '__main__':
    call_main(StreamEditorEDWTables)
Example #12
0
from sed.engine import StreamEditor, call_main, ACCEPT, REPEAT, NEXT, ANY

# goog.require('wgen.assess.lib');
GOOG_REQUIRE = re.compile(
    r"""
    ^
    goog.require
    \(
    ['"]
    (?P<class>[\w\d_\$\.]+)
    ['"]
    \)
    ;
""",
    re.VERBOSE,
)


class StreamEditorSortGoogRequires(StreamEditor):
    table = [[[GOOG_REQUIRE, NEXT]], [[GOOG_REQUIRE, REPEAT], [ANY, ACCEPT]]]

    def apply_match(self, i, dict_matches):
        start, end = dict_matches["start"], dict_matches["end"]
        if not (end is None):
            self.sort_range((start, end - 1))


if __name__ == "__main__":
    call_main(StreamEditorSortGoogRequires)
Example #13
0
# replace original events with {}
# move hard-coded events to initialize
class StreamEditorMoveEvents(StreamEditor):
    table = [[[EVENT_DECL, NEXT]], [[SELECTOR, NEXT], [END_DECL, ACCEPT]]]

    def apply_match(self, i, dict_matches):
        start, end, matches = dict_matches["start"], dict_matches["end"], dict_matches["matches"]
        if not (end is None):
            decl = matches[0]["decl"]
            events = matches[1:-1]
            pairs = [(event["selector"], event["function"]) for event in events]
            new_lines = build_newlines(decl, pairs)
            new_event = "\t\t%s: {}," % decl
            initialize, _ = self.find_line(INITIALIZE_MATCH)
            if initialize is not None:
                if start < initialize:
                    self.append_range(initialize, new_lines)
                    self.replace_range((start, end + 1), [new_event])
                else:
                    self.replace_range((start, end + 1), [new_event])
                    self.append_range(initialize, new_lines)
                self.entab()
            else:
                stderr.write("*** %s: Missing initialize method\n" % self.filename)
        else:
            stderr.write("%s: match started at %d\n" % (self.filename, start), matches)


if __name__ == "__main__":
    call_main(StreamEditorMoveEvents)
    \s+
    \},
''', re.VERBOSE)


class StreamEditorInjectDelegateEvents(StreamEditor):
    table = [
        [[DELEGATE_EVENTS_REGEX, NEXT], ],
        [[END_DECL, ACCEPT], ],
    ]

    def apply_match(self, i, dict_matches):
        start, end = dict_matches["start"], dict_matches["end"]
        assert start <= end

        j, _ = self.find_line(BACKBONE_DELEGATE_EVENTS_REGEX)
        if j is not None:
            assert start <= j <= end
            self.replace_range((j, j + 1), [DELEGATE_EVENTS_PATCH])

        k, _ = self.find_line(PRIVATE_DELEGATE_EVENTS_REGEX)
        if k is None:
            self.insert_range(start, [PRIVATE_DELEGATE_EVENTS])


if __name__ == '__main__':
    #import os.path
    #path = os.path.expandvars(VIEW)
    #call_main([path], StreamEditorInjectDelegateEvents)
    call_main(StreamEditorInjectDelegateEvents)