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 @@ + + +