# Buggy code
def fix(force, paths, **kwargs):
    """Fix SQL files.

    PATH is the path to a sql file or directory to lint. This can be either a
    file ('path/to/file.sql'), a path ('directory/of/sql/files'), a single ('-')
    character to indicate reading from *stdin* or a dot/blank ('.'/' ') which will
    be interpreted like passing the current working directory as a path argument.
    """
    c = get_config(**kwargs)
    lnt = get_linter(c)
    verbose = c.get("verbose")

    config_string = format_config(lnt, verbose=verbose)
    if len(config_string) > 0:
        lnt.log(config_string)
    # Check that if fix is specified, that we have picked only a subset of rules
    if lnt.config.get("rule_whitelist") is None:
        lnt.log(
            (
                "The fix option is only available in combination"
                " with --rules. This is for your own safety!"
            )
        )
        sys.exit(1)

    # handle stdin case. should output formatted sql to stdout and nothing else.
    if ("-",) == paths:
        stdin = sys.stdin.read()
        result = lnt.lint_string_wrapped(
            stdin, fname="stdin", verbosity=verbose, fix=True
        )
        stdout = result.paths[0].files[0].fix_string()
        click.echo(stdout, nl=False)
        sys.exit()

    # Lint the paths (not with the fix argument at this stage), outputting as we go.
    lnt.log("==== finding violations ====")
    try:
        result = lnt.lint_paths(paths, verbosity=verbose)
    except IOError:
        click.echo(
            colorize(
                "The path(s) {0!r} could not be accessed. Check it/they exist(s).".format(
                    paths
                ),
                "red",
            )
        )
        sys.exit(1)

    if result.num_violations() > 0:
        click.echo("==== fixing violations ====")
        click.echo("{0} violations found".format(result.num_violations()))
        if force:
            click.echo("FORCE MODE: Attempting fixes...")
            result = lnt.lint_paths(paths, fix=True)
            click.echo("Persisting Changes...")
            result.persist_changes()
            click.echo("Done. Please check your files to confirm.")
        else:
            click.echo(
                "Are you sure you wish to attempt to fix these? [Y/n] ", nl=False
            )
            c = click.getchar().lower()
            click.echo("...")
            if c == "y":
                click.echo("Attempting fixes...")
                result = lnt.lint_paths(paths, fix=True)
                click.echo("Persisting Changes...")
                result.persist_changes(verbosity=verbose)
                click.echo("Done. Please check your files to confirm.")
            elif c == "n":
                click.echo("Aborting...")
            else:
                click.echo("Invalid input :(")
                click.echo("Aborting...")
    else:
        click.echo("==== no violations found ====")
    sys.exit(0)


# 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 fix(force, paths, **kwargs):
    """Fix SQL files.

    PATH is the path to a sql file or directory to lint. This can be either a
    file ('path/to/file.sql'), a path ('directory/of/sql/files'), a single ('-')
    character to indicate reading from *stdin* or a dot/blank ('.'/' ') which will
    be interpreted like passing the current working directory as a path argument.
    """
    c = get_config(**kwargs)
    lnt = get_linter(c)
    verbose = c.get("verbose")

    config_string = format_config(lnt, verbose=verbose)
    if len(config_string) > 0:
        lnt.log(config_string)
    # Check that if fix is specified, that we have picked only a subset of rules
    if lnt.config.get("rule_whitelist") is None:
        lnt.log(
            (
                "The fix option is only available in combination"
                " with --rules. This is for your own safety!"
            )
        )
        sys.exit(1)

    # handle stdin case. should output formatted sql to stdout and nothing else.
    if ("-",) == paths:
        stdin = sys.stdin.read()
        result = lnt.lint_string_wrapped(
            stdin, fname="stdin", verbosity=verbose, fix=True
        )
        stdout = result.paths[0].files[0].fix_string()
        click.echo(stdout, nl=False)
        sys.exit()

    # Lint the paths (not with the fix argument at this stage), outputting as we go.
    lnt.log("==== finding violations ====")
    try:
        result = lnt.lint_paths(paths, verbosity=verbose)
    except IOError:
        click.echo(
            colorize(
                "The path(s) {0!r} could not be accessed. Check it/they exist(s).".format(
                    paths
                ),
                "red",
            )
        )
        sys.exit(1)

    # NB: We filter to linting violations here, because they're
    # the only ones which can be potentially fixed.
    if result.num_violations(types=SQLLintError) > 0:
        click.echo("==== fixing violations ====")
        click.echo(
            "{0} linting violations found".format(
                result.num_violations(types=SQLLintError)
            )
        )
        if force:
            click.echo("FORCE MODE: Attempting fixes...")
            success = do_fixes(lnt, paths, types=SQLLintError)
            if not success:
                sys.exit(1)
        else:
            click.echo(
                "Are you sure you wish to attempt to fix these? [Y/n] ", nl=False
            )
            c = click.getchar().lower()
            click.echo("...")
            if c == "y":
                click.echo("Attempting fixes...")
                success = do_fixes(lnt, paths)
                if not success:
                    sys.exit(1)
            elif c == "n":
                click.echo("Aborting...")
            else:
                click.echo("Invalid input :(")
                click.echo("Aborting...")
    else:
        click.echo("==== no linting violations found ====")
    sys.exit(0)