From 494ddb4caf38732ab3645eaf515560e39fd01f39 Mon Sep 17 00:00:00 2001 From: Ash Berlin-Taylor Date: Fri, 25 Apr 2025 20:01:08 +0100 Subject: [PATCH] Fix `--insert-license-after-regex` to work beyond first line There was a logic bug where `index` wasn't incremenetd, so we would search through the file for the regex, but index was still 0 so the index always got put after line 0. --- pre_commit_hooks/insert_license.py | 13 +++++++------ tests/insert_license_test.py | 9 +++++++++ tests/resources/module_with_license.php | 2 ++ tests/resources/module_without_license.php | 2 ++ 4 files changed, 20 insertions(+), 6 deletions(-) diff --git a/pre_commit_hooks/insert_license.py b/pre_commit_hooks/insert_license.py index f9acc84..b644943 100644 --- a/pre_commit_hooks/insert_license.py +++ b/pre_commit_hooks/insert_license.py @@ -328,7 +328,7 @@ def license_not_found( # pylint: disable=too-many-arguments """ if not remove_header: index = 0 - for line in src_file_content: + for index, line in enumerate(src_file_content): stripped_line = line.strip() # Special treatment for user provided regex, # or shebang, file encoding directive, @@ -339,13 +339,14 @@ def license_not_found( # pylint: disable=too-many-arguments index += 1 # Skip matched line break # And insert after that line. elif ( - stripped_line.startswith("#!") - or stripped_line.startswith("# -*- coding") - or stripped_line == "" + not stripped_line.startswith("#!") + and not stripped_line.startswith("# -*- coding") + and not stripped_line == "" ): - index += 1 - else: break + else: + # We got all the way to the end without hitting `break`, reset it to line 0 + index = 0 src_file_content = ( src_file_content[:index] + license_info.prefixed_license diff --git a/tests/insert_license_test.py b/tests/insert_license_test.py index c7a161c..ad059db 100644 --- a/tests/insert_license_test.py +++ b/tests/insert_license_test.py @@ -190,6 +190,15 @@ def _convert_line_ending(file_path, new_line_endings): True, ["--insert-license-after-regex", "^<\\?php$"], ), + ( + "module_without_license.py", + "#", + "module_with_license.py", + "", + True, + # Test that when the regex is not found, the license is put at the first line + ["--insert-license-after-regex", "^<\\?php$"], + ), ( "module_without_license.py", "#", diff --git a/tests/resources/module_with_license.php b/tests/resources/module_with_license.php index 8bf07eb..3ffa6cf 100644 --- a/tests/resources/module_with_license.php +++ b/tests/resources/module_with_license.php @@ -1,3 +1,5 @@ + + +