Skip to content

Commit

Permalink
Finally fixed all issues, so testcase works, this should finally clea…
Browse files Browse the repository at this point in the history
…nup as expected
  • Loading branch information
y0urself committed Dec 20, 2023
1 parent 2d8a80d commit 1766dfb
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 24 deletions.
26 changes: 8 additions & 18 deletions pontos/updateheader/updateheader.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,12 +145,12 @@ def _remove_outdated_lines(
splitted_lines = content.splitlines()
i = 0
for line in splitted_lines[:20]:
if i > 3 and re.match(r"^(([#*]|//) ?)", line):
if i > 3 and re.match(r"^(([#*]|//) ?$)", line):
splitted_lines.pop(i)
i = i - 1
continue
for regex in cleanup_regexes:
if regex.match(line):
("match")
changed = True
splitted_lines.pop(i)
i = i - 1
Expand All @@ -168,16 +168,12 @@ def _update_file(
parsed_args: Namespace,
term: Terminal,
cleanup_regexes: Optional[List[re.Pattern]] = None,
old_company_copyright_regex: Optional[re.Pattern] = None,
) -> int:
"""Function to update the given file.
Checks if header exists. If not it adds an
header to that file, else it checks if year
is up to date
"""
cleanup = False
if cleanup_regexes and old_company_copyright_regex:
cleanup = True

if parsed_args.changed:
try:
Expand All @@ -200,10 +196,6 @@ def _update_file(
found, copyright_match = _find_copyright(
line=line, copyright_regex=copyright_regex
)
if cleanup and not found:
found, copyright_match = _find_copyright(
line=line, copyright_regex=old_company_copyright_regex # type: ignore # noqa: E501
)
i = i - 1
# header not found, add header
if i == 0 and not found:
Expand Down Expand Up @@ -242,7 +234,7 @@ def _update_file(
copyright_term = (
f"SPDX-FileCopyrightText: "
f'{copyright_match["creation_year"]}'
f'-{parsed_args.year} {copyright_match["company"]}'
f"-{parsed_args.year} {parsed_args.company}"
)
new_line = re.sub(copyright_regex, copyright_term, line)
fp_write = fp.tell() - len(line) # save position to insert
Expand Down Expand Up @@ -420,12 +412,14 @@ def _compile_outdated_regex() -> List[re.Pattern]:
return regexes


def _compile_copyright_regex(company: str) -> re.Pattern:
def _compile_copyright_regex(company: Union[str, List[str]]) -> re.Pattern:
"""prepare the copyright regex"""
c_str = r"(SPDX-FileCopyrightText:|[Cc]opyright)"
d_str = r"(19[0-9]{2}|20[0-9]{2})"

return re.compile(rf"{c_str}.*? {d_str}?-? ?{d_str}? ({company})")
if isinstance(company, str):
return re.compile(rf"{c_str}.*? {d_str}?-? ?{d_str}? ({company})")

Check warning on line 421 in pontos/updateheader/updateheader.py

View check run for this annotation

Codecov / codecov/patch

pontos/updateheader/updateheader.py#L421

Added line #L421 was not covered by tests
return re.compile(rf"{c_str}.*? {d_str}?-? ?{d_str}? ({'|'.join(company)})")


def main() -> None:
Expand Down Expand Up @@ -467,10 +461,7 @@ def main() -> None:
sys.exit(1)

copyright_regex: re.Pattern = _compile_copyright_regex(
company=parsed_args.company
)
old_company_copyright_regex: re.Pattern = _compile_copyright_regex(
company=OLD_COMPANY
company=[parsed_args.company, OLD_COMPANY]
)

cleanup_regexes: Optional[List[re.Pattern]] = None
Expand All @@ -488,7 +479,6 @@ def main() -> None:
parsed_args=parsed_args,
term=term,
cleanup_regexes=cleanup_regexes,
old_company_copyright_regex=old_company_copyright_regex,
)
except (FileNotFoundError, UnicodeDecodeError, ValueError):
continue
Expand Down
73 changes: 67 additions & 6 deletions tests/updateheader/test_header.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@
from unittest.mock import patch

from pontos.terminal.terminal import ConsoleTerminal
from pontos.testing import temp_file
from pontos.updateheader.updateheader import OLD_COMPANY
from pontos.updateheader.updateheader import _add_header as add_header
from pontos.updateheader.updateheader import _compile_copyright_regex
from pontos.updateheader.updateheader import (
_compile_outdated_regex as compile_outdated_regex,
)
Expand Down Expand Up @@ -535,6 +538,11 @@ def test_main_never_happen(self, argparser_mock, mock_stdout):
ret,
)


class UpdateHeaderCleanupTestCase(TestCase):
def setUp(self) -> None:
self.compiled_regexes = compile_outdated_regex()

def test_remove_outdated_lines(self):
test_content = """* This program is free software: you can redistribute it and/or modify
*it under the terms of the GNU Affero General Public License as
Expand All @@ -547,10 +555,8 @@ def test_remove_outdated_lines(self):
# version 2 as published by the Free Software Foundation.
This program is free software: you can redistribute it and/or modify""" # noqa: E501

compiled_regexes = compile_outdated_regex()

new_content = remove_outdated_lines(
content=test_content, cleanup_regexes=compiled_regexes
content=test_content, cleanup_regexes=self.compiled_regexes
)
self.assertEqual(new_content, "\n")

Expand All @@ -566,9 +572,64 @@ def test_remove_outdated_lines2(self):
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.""" # noqa: E501

compiled_regexes = compile_outdated_regex()

new_content = remove_outdated_lines(
content=test_content, cleanup_regexes=compiled_regexes
content=test_content, cleanup_regexes=self.compiled_regexes
)
self.assertEqual(new_content, "\n")

def test_cleanup_file(self):
test_content = """# Copyright (C) 2021-2022 Greenbone Networks GmbH
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import foo
import bar
foo.baz(bar.boing)
""" # noqa: E501

expected_content = f"""# SPDX-FileCopyrightText: 2021-{str(datetime.datetime.now().year)} Greenbone AG
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
import foo
import bar
foo.baz(bar.boing)
""" # noqa: E501

with temp_file(content=test_content, name="foo.py") as tmp:
args = Namespace()
args.company = "Greenbone AG"
args.year = str(datetime.datetime.now().year)
args.changed = False
args.license_id = "GPL-3.0-or-later"
args.verbose = 0
args.cleanup = True

update_file(
file=tmp,
copyright_regex=_compile_copyright_regex(
["Greenbone AG", OLD_COMPANY]
),
parsed_args=args,
term=Terminal(),
cleanup_regexes=self.compiled_regexes,
)

new_content = tmp.read_text(encoding="utf-8")
self.assertEqual(expected_content, new_content)

0 comments on commit 1766dfb

Please sign in to comment.