diff --git a/snakefmt/formatter.py b/snakefmt/formatter.py index 43345bc..562bbd4 100644 --- a/snakefmt/formatter.py +++ b/snakefmt/formatter.py @@ -143,7 +143,8 @@ def run_black_format_str( inside_nested_statement = ( self.syntax.code_indent is not None and self.syntax.code_indent > 0 ) - if inside_nested_statement and self.from_python: # i.e. after snakecode + # this checks if we are inside snakecode, within a nested if-else statement + if inside_nested_statement and self.from_python and self.in_global_context: # indent any comments and the first line tmpstring = "" for i, line in enumerate(string.splitlines(keepends=True)): diff --git a/tests/test_formatter.py b/tests/test_formatter.py index 6fee652..ed335e2 100644 --- a/tests/test_formatter.py +++ b/tests/test_formatter.py @@ -523,6 +523,22 @@ def test_nested_if_statements_with_comments_and_snakecode_inside2(self): formatter = setup_formatter(snakecode) assert formatter.get_formatted() == snakecode + def test_nested_if_statements_with_comments_and_snakecode_inside3(self): + """https://github.com/snakemake/snakefmt/pull/136#issuecomment-1132845522""" + snakecode = ( + "if True:\n\n" + f"{TAB * 1}rule with_run_directive:\n" + f"{TAB * 2}output:\n" + f'{TAB * 3}"test.txt",\n' + f"{TAB * 2}run:\n" + f"{TAB * 3}if True:\n" + f'{TAB * 4}print("this line is in the error")\n' + "\n\n" + f'{TAB * 1}print("the indenting on this line matters")\n' + ) + formatter = setup_formatter(snakecode) + assert formatter.get_formatted() == snakecode + def test_nested_if_statements_with_function_and_snakecode_inside(self): """https://github.com/snakemake/snakefmt/pull/136#issuecomment-1125130038""" snakecode = (