# Buggy code
def realign(self):
    """Realign the positions in this segment.

    Returns:
        a copy of this class with the pos_markers realigned.

    Note: this is used mostly during fixes.

    Realign is recursive. We will assume that the pos_marker of THIS segment is
    truthful, and that during recursion it will have been set by the parent.

    This function will align the pos marker if it's direct children, we then
    recurse to realign their children.

    """
    seg_buffer = []
    todo_buffer = list(self.segments)
    running_pos = self.pos_marker

    while True:
        if len(todo_buffer) == 0:
            # We're done.
            break
        else:
            # Get the first off the buffer
            seg = todo_buffer.pop(0)

            # Is it a meta segment?
            if seg.is_meta:
                # If so, just carry on.
                seg_buffer.append(seg)
                continue

            # We'll preserve statement indexes so we should keep track of that.
            # When recreating, we use the DELTA of the index so that's what matter...
            idx = seg.pos_marker.statement_index - running_pos.statement_index
            if len(seg.segments) > 0:
                # It's a compound segment, so keep track of it's children
                child_segs = seg.segments
                # Create a new segment of the same type with the new position
                seg = seg.__class__(segments=child_segs, pos_marker=running_pos)
                # Realign the children of that class
                seg = seg.realign()
            else:
                # It's a raw segment...
                # Create a new segment of the same type with the new position
                seg = seg.__class__(raw=seg.raw, pos_marker=running_pos)
            # Update the running position with the content of that segment
            running_pos = running_pos.advance_by(raw=seg.raw, idx=idx)
            # Add the buffer to my new segment
            seg_buffer.append(seg)

    # Create a new version of this class with the new details
    return self.__class__(segments=tuple(seg_buffer), pos_marker=self.pos_marker)


# Traceback (TypeError)
$ sqlfluff fix --rules L001 forecastservice\sql\get_phasing_v2.sql
==== finding violations ====
== [forecastservice\sql\get_phasing_v2.sql] FAIL
L:   0 | P:   0 | ???? | Failure in Jinja templating: 'first_mon' is undefined. Have you configured your variables?
L:   7 | P:   1 | ???? | Unable to lex characters: ''{% if regi'...'
==== fixing violations ====
2 violations found
Are you sure you wish to attempt to fix these? [Y/n] ...
Attempting fixes...
Persisting Changes...
Traceback (most recent call last):
File "C:\Users\alan\dev\tails-analytics-forecastservice\env\Scripts\sqlfluff-script.py", line 11, in <module>
load_entry_point('sqlfluff==0.2.4', 'console_scripts', 'sqlfluff')()
File "c:\users\alan\dev\tails-analytics-forecastservice\env\lib\site-packages\click\core.py", line 764, in __call__
return self.main(*args, **kwargs)
File "c:\users\alan\dev\tails-analytics-forecastservice\env\lib\site-packages\click\core.py", line 717, in main
rv = self.invoke(ctx)
File "c:\users\alan\dev\tails-analytics-forecastservice\env\lib\site-packages\click\core.py", line 1137, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\alan\dev\tails-analytics-forecastservice\env\lib\site-packages\click\core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:\users\alan\dev\tails-analytics-forecastservice\env\lib\site-packages\click\core.py", line 555, in invoke
return callback(*args, **kwargs)
File "c:\users\alan\dev\tails-analytics-forecastservice\env\lib\site-packages\sqlfluff\cli\commands.py", line 197, in fix
result.persist_changes(verbosity=verbose)
File "c:\users\alan\dev\tails-analytics-forecastservice\env\lib\site-packages\sqlfluff\linter.py", line 327, in persist_changes
return self.combine_dicts(*[path.persist_changes(verbosity=verbosity) for path in self.paths])
File "c:\users\alan\dev\tails-analytics-forecastservice\env\lib\site-packages\sqlfluff\linter.py", line 327, in <listcomp>
return self.combine_dicts(*[path.persist_changes(verbosity=verbosity) for path in self.paths])
File "c:\users\alan\dev\tails-analytics-forecastservice\env\lib\site-packages\sqlfluff\linter.py", line 253, in persist_changes
return {file.path: file.persist_tree(verbosity=verbosity) for file in self.files}
File "c:\users\alan\dev\tails-analytics-forecastservice\env\lib\site-packages\sqlfluff\linter.py", line 253, in <dictcomp>
return {file.path: file.persist_tree(verbosity=verbosity) for file in self.files}
File "c:\users\alan\dev\tails-analytics-forecastservice\env\lib\site-packages\sqlfluff\linter.py", line 61, in persist_tree
diff_templ_codes = diff_templ.get_opcodes()
File "C:\Users\alan\AppData\Local\Programs\Python\Python36\lib\difflib.py", line 550, in get_opcodes
for ai, bj, size in self.get_matching_blocks():
File "C:\Users\alan\AppData\Local\Programs\Python\Python36\lib\difflib.py", line 467, in get_matching_blocks
la, lb = len(self.a), len(self.b)
TypeError: object of type 'NoneType' has no len()

# Fixed code
def realign(self):
    """Realign the positions in this segment.

    Returns:
        a copy of this class with the pos_markers realigned.

    Note: this is used mostly during fixes.

    Realign is recursive. We will assume that the pos_marker of THIS segment is
    truthful, and that during recursion it will have been set by the parent.

    This function will align the pos marker if it's direct children, we then
    recurse to realign their children.

    """
    seg_buffer = []
    todo_buffer = list(self.segments)
    running_pos = self.pos_marker

    while True:
        if len(todo_buffer) == 0:
            # We're done.
            break
        else:
            # Get the first off the buffer
            seg = todo_buffer.pop(0)

            # We'll preserve statement indexes so we should keep track of that.
            # When recreating, we use the DELTA of the index so that's what matter...
            idx = seg.pos_marker.statement_index - running_pos.statement_index
            if seg.is_meta:
                # It's a meta segment, just update the position
                seg = seg.__class__(pos_marker=running_pos)
            elif len(seg.segments) > 0:
                # It's a compound segment, so keep track of it's children
                child_segs = seg.segments
                # Create a new segment of the same type with the new position
                seg = seg.__class__(segments=child_segs, pos_marker=running_pos)
                # Realign the children of that class
                seg = seg.realign()
            else:
                # It's a raw segment...
                # Create a new segment of the same type with the new position
                seg = seg.__class__(raw=seg.raw, pos_marker=running_pos)
            # Update the running position with the content of that segment
            running_pos = running_pos.advance_by(raw=seg.raw, idx=idx)
            # Add the buffer to my new segment
            seg_buffer.append(seg)

    # Create a new version of this class with the new details
    return self.__class__(segments=tuple(seg_buffer), pos_marker=self.pos_marker)