如何使用Python将更改应用于源文件? 我使用Clang编译器()的Python绑定重构C++代码。使用它,我分析AST并准备更改。最后,我列出了一系列类似于以下内容的操作: DELETE line 10 INSERT line 5 column 32: << "tofu" REPLACE from line 31 colum 6 to line 33 column 82 with: std::cout << "Thanks SO" ... 删除第10行 插入第5行第32列:

如何使用Python将更改应用于源文件? 我使用Clang编译器()的Python绑定重构C++代码。使用它,我分析AST并准备更改。最后,我列出了一系列类似于以下内容的操作: DELETE line 10 INSERT line 5 column 32: << "tofu" REPLACE from line 31 colum 6 to line 33 column 82 with: std::cout << "Thanks SO" ... 删除第10行 插入第5行第32列:,python,c++,refactoring,clang,abstract-syntax-tree,Python,C++,Refactoring,Clang,Abstract Syntax Tree,因此我推出了自己的。这段代码几乎肯定是有缺陷的,也不是很漂亮,但我发布它的目的是希望它能帮助别人,直到找到更好的解决方案 class PatchRecord(object): """ Record patches, validate them, order them, and apply them """ def __init__(self): # output of readlines for each patched file self.li

因此我推出了自己的。这段代码几乎肯定是有缺陷的,也不是很漂亮,但我发布它的目的是希望它能帮助别人,直到找到更好的解决方案

class PatchRecord(object):
    """ Record patches, validate them, order them, and apply them """

    def __init__(self):
        # output of readlines for each patched file
        self.lines = {}
        # list of patches for each patched file
        self.patches = {}

    class Patch(object):
        """ Abstract base class for editing operations """

        def __init__(self, filename, start, end):
            self.filename = filename
            self.start = start
            self.end = end

        def __repr__(self):
            return "{op}: {filename} {start}/{end} {what}".format(
                op=self.__class__.__name__.upper(),
                filename=self.filename,
                start=format_place(self.start),
                end=format_place(self.end),
                what=getattr(self, "what", ""))

        def apply(self, lines):
            print "Warning: applying no-op patch"

    class Delete(Patch):

        def __init__(self, filename, extent):
            super(PatchRecord.Delete, self).__init__(
                filename, extent.start, extent.end)
            print "DELETE: {file} {extent}".format(file=self.filename,
                                                   extent=format_extent(extent))

        def apply(self, lines):
            lines[self.start.line - 1:self.end.line] = [
                lines[self.start.line - 1][:self.start.column - 1] +
                lines[self.end.line - 1][self.end.column:]]

    class Insert(Patch):

        def __init__(self, filename, start, what):
            super(PatchRecord.Insert, self).__init__(filename, start, start)
            self.what = what
            print "INSERT {where} {what}".format(what=what, where=format_place(self.start))

        def apply(self, lines):
            line = lines[self.start.line - 1]
            lines[self.start.line - 1] = "%s%s%s" % (
                line[:self.start.column],
                self.what,
                line[self.start.column:])

    class Replace(Patch):

        def __init__(self, filename, extent, what):
            super(PatchRecord.Replace, self).__init__(
                filename, extent.start, extent.end)
            self.what = what
            print "REPLACE: {where} {what}".format(what=what,
                                                   where=format_extent(extent))

        def apply(self, lines):
            lines[self.start.line - 1:self.end.line] = [
                lines[self.start.line - 1][:self.start.column - 1] +
                self.what +
                lines[self.end.line - 1][self.end.column - 1:]]

    # Convenience functions for creating patches
    def delete(self, filename, extent):
        self.patches[filename] = self.patches.get(
            filename, []) + [self.Delete(filename, extent)]

    def insert(self, filename, where, what):
        self.patches[filename] = self.patches.get(
            filename, []) + [self.Insert(filename, where, what)]

    def replace(self, filename, extent, what):
        self.patches[filename] = self.patches.get(
            filename, []) + [self.Replace(filename, extent, what)]

    def _pos_to_tuple(self, position):
        """ Convert a source location to a tuple for use as a sorting key """
        return (position.line, position.column)

    def sort(self, filename):
        """ Sort patches by extent start """
        self.patches[filename].sort(key=lambda p: self._pos_to_tuple(p.start))

    def validate(self, filename):
        """Try to insure patches are consistent"""
        print "Checking patches for %s" % filename
        self.sort(filename)
        previous = self.patches[filename][0]
        for p in self.patches[filename][1:]:
            assert(self._pos_to_tuple(p.start) >
                   self._pos_to_tuple(previous.start))

    def _apply(self, filename):
        self.sort(filename)
        lines = self._getlines(filename)
        for p in reversed(self.patches[filename]):
            print p
            p.apply(lines)

    def _getlines(self, filename):
        """ Get source file lines for editing """
        if not filename in self.lines:
            with open(filename) as f:
                self.lines[filename] = f.readlines()
        return self.lines[filename]

    def apply(self):
        for filename in self.patches:
            self.validate(filename)
            self._apply(filename)
            # with open(filename+".patched","w") as output:
            with open(filename, "w") as output:
                output.write("".join(self._getlines(filename)))

只需创建一个
PatchRecord
对象,使用
create
replace
delete
方法添加更改,并在准备就绪时使用
apply
应用它们。

您展示的是一系列补丁;为什么你不能按顺序应用它们呢?[可能您正在为AST制作几个重叠的补丁?]在每次修改时只修改AST,然后将修改后的AST吐出来,这会更有用吗?这样就不会出现顺序错误的修补问题。您必须小心顺序,因为更改可能会使行号无效。我同意修改AST将是最好的选择,不幸的是cindex不支持它。如果您拥有的工具不能很好地完成工作,您可以选择其他工具。检查我的BIO为一个工具(DMS),它可以解析C++,构建和修改C++ AST(我们在编写更改时避免了愚蠢的补丁问题),然后重新生成有效的源代码。不过,它不是用Python编写的。它也不是C++的;DMS是一组DSL,它们相互协作以允许您指定转换。