From de35de34cd707a1d2496d7a923ad46077277a8a5 Mon Sep 17 00:00:00 2001 From: truePhilipp Date: Fri, 10 May 2024 10:31:06 +0000 Subject: [PATCH] correctly rename non .html files when only converting one file --- README.md | 2 ++ html_to_django/converter.py | 3 ++- tests/tests_converter.py | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4f5c8bc..cd9da9a 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,8 @@ TODO: pip install instructions ```bash html_to_django [-h] [-r] path ``` +`path` can either be a path to a file or a folder. When a file is passed only the file itself will be converted. When a folder is passed, all files ending in .html will be replaced. This searches through the folder recursivley. + Use `-r` to replace the original files, instead of creating new ones. By default, new ones are created in place next to the existing files, with the extension `.n.html`. diff --git a/html_to_django/converter.py b/html_to_django/converter.py index 3ddf0ae..1112a02 100644 --- a/html_to_django/converter.py +++ b/html_to_django/converter.py @@ -61,7 +61,8 @@ def convert_file(path: str, overwrite: bool = False) -> None: if overwrite: out_path = path else: - out_path = path.replace(".html", ".n.html") + filename, file_extension = os.path.splitext(path) + out_path = f"{filename}.n{file_extension}" with open(out_path, "w") as file: for lib in required_libraries: file.write(f"{{% load {lib} %}}\n") diff --git a/tests/tests_converter.py b/tests/tests_converter.py index 316e89e..69e5a55 100644 --- a/tests/tests_converter.py +++ b/tests/tests_converter.py @@ -58,6 +58,38 @@ class ConverterTests(TestCase): # verify that no new file was created self.assertFalse(os.path.exists(f"{tmpdir}/test.n.html")) + def test_convert_file_non_html_extension(self) -> None: + with tempfile.TemporaryDirectory() as tmpdir: + shutil.copytree( + "tests/test_project", + tmpdir, + dirs_exist_ok=True + ) + os.rename(f"{tmpdir}/test.html", f"{tmpdir}/test.txt") + + convert_file(f"{tmpdir}/test.txt") + # verify that the source file has been overwriten + self.assertTrue(filecmp.cmp( + "tests/test_project_expected_result/test.html", + f"{tmpdir}/test.n.txt" + )) + + def test_convert_file_no_extension(self) -> None: + with tempfile.TemporaryDirectory() as tmpdir: + shutil.copytree( + "tests/test_project", + tmpdir, + dirs_exist_ok=True + ) + os.rename(f"{tmpdir}/test.html", f"{tmpdir}/test") + + convert_file(f"{tmpdir}/test") + # verify that the source file has been overwriten + self.assertTrue(filecmp.cmp( + "tests/test_project_expected_result/test.html", + f"{tmpdir}/test.n" + )) + def test_convert_file_nonexistent(self) -> None: with self.assertRaises(FileNotFoundError): convert_file("tests/test/project/nonexistent_file.html")