correctly rename non .html files when only converting one file

This commit is contained in:
truePhilipp committed 2024-05-10 10:31:06 +00:00
1 parent 0487b39737
commit de35de34cd
3 files changed
+36 -1

No files matched your search

+2
View File
@@ -14,6 +14,8 @@ TODO: pip install instructions
```bash ```bash
html_to_django [-h] [-r] path 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. 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`. By default, new ones are created in place next to the existing files, with the extension `.n.html`.
+2 -1
View File
@@ -61,7 +61,8 @@ def convert_file(path: str, overwrite: bool = False) -> None:
if overwrite: if overwrite:
out_path = path out_path = path
else: 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: with open(out_path, "w") as file:
for lib in required_libraries: for lib in required_libraries:
file.write(f"{{% load {lib} %}}\n") file.write(f"{{% load {lib} %}}\n")
+32
View File
@@ -58,6 +58,38 @@ class ConverterTests(TestCase):
# verify that no new file was created # verify that no new file was created
self.assertFalse(os.path.exists(f"{tmpdir}/test.n.html")) 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: def test_convert_file_nonexistent(self) -> None:
with self.assertRaises(FileNotFoundError): with self.assertRaises(FileNotFoundError):
convert_file("tests/test/project/nonexistent_file.html") convert_file("tests/test/project/nonexistent_file.html")