Repository: mgcth/mysgen

Issue:
Mangle image names
## Description

Add option to mangel image names and sort them by date. Requires that image name is the date, as the code expects images with stripped metadata.

Discussion:

Patch:
diff --git a/README.md b/README.md
index 0c5fd30..5ff2ff9 100644
--- a/README.md
+++ b/README.md
@@ -57,7 +57,8 @@ The configuration file `config.json` should contain the following
         "fenced_code",
         "mdx_math"
     ],
-    "s3-bucket": "bucket"
+    "s3-bucket": "bucket",
+    "mangle_image_name": true
 }
 ```
 
diff --git a/src/mysgen/mysgen.py b/src/mysgen/mysgen.py
index 86a694e..a460fc8 100644
--- a/src/mysgen/mysgen.py
+++ b/src/mysgen/mysgen.py
@@ -4,6 +4,8 @@ import os
 import json
 import glob
 import boto3
+import shutil
+import hashlib
 import markdown
 from PIL import Image
 from typing import Any
@@ -159,10 +161,32 @@ class ImagePost(Post):
         self.meta["thumbnail_size"] = base["thumbnail_size"]
         self.meta["thumbnails"] = []
         self.meta["image_paths"] = []
-        for to_image in glob.glob(join(self.to_path, "*.*")):
-            if not isfile(to_image):
-                continue
 
+        images = [
+            to_image
+            for to_image in glob.glob(join(self.to_path, "*.*"))
+            if isfile(to_image)
+        ]
+
+        if base["mangle_image_name"]:
+            sorted_images = sorted(images)
+            images = [
+                join(
+                    *split(to_image)[:-2],
+                    str(i)
+                    + "-"
+                    + hashlib.sha256(
+                        bytearray(split(to_image)[-1].split(".")[0], "utf-8")
+                    ).hexdigest()[:7],
+                )
+                + "."
+                + to_image.split(".")[-1]
+                for i, to_image in enumerate(sorted_images)
+            ]
+            for im, im_sha in zip(sorted_images, images):
+                shutil.move(im, im_sha)
+
+        for to_image in images:
             self.meta["image_paths"].append(split(to_image)[-1])
             self._resize_image(to_image)
 


Test patch:
diff --git a/tests/fixtures/test_config.json b/tests/fixtures/test_config.json
index bb04cfa..aa2fa08 100644
--- a/tests/fixtures/test_config.json
+++ b/tests/fixtures/test_config.json
@@ -23,5 +23,6 @@
         "fenced_code",
         "mdx_math"
     ],
-    "s3-bucket": false
+    "s3-bucket": false,
+    "mangle_image_name": false
 }
\ No newline at end of file
diff --git a/tests/test_unit.py b/tests/test_unit.py
index 9dccccd..065921e 100644
--- a/tests/test_unit.py
+++ b/tests/test_unit.py
@@ -4,6 +4,7 @@ Functions to test mysgen.
 import os
 import json
 import pytest
+import hashlib
 from datetime import datetime
 from collections import OrderedDict
 from distutils.errors import DistutilsFileError
@@ -465,7 +466,10 @@ class TestUnitImagePost:
         assert post.from_path == "src/images/post"
         assert post.to_path == "build/posts/post/images"
 
-    @pytest.mark.parametrize("isfile", [(True), (False)])
+    @pytest.mark.parametrize(
+        "isfile, mangle_image_name", [(True, False), (False, False), (True, True)]
+    )
+    @patch("mysgen.mysgen.shutil.move")
     @patch("mysgen.mysgen.ImagePost._resize_image")
     @patch("mysgen.mysgen.isfile")
     @patch("mysgen.mysgen.glob.glob")
@@ -478,17 +482,19 @@ class TestUnitImagePost:
         mock_glob,
         mock_isfile,
         mock_resize_image,
+        mock_move,
         isfile,
+        mangle_image_name,
     ):
         """
         Unit test of ImagePost process method.
         """
-        mock_base = MagicMock()
+        mock_base = {"mangle_image_name": mangle_image_name, "thumbnail_size": 0}
         mock_template = MagicMock()
         post = ImagePost(
             {"path": "posts/post1.md"}, MagicMock(), MagicMock(), MagicMock()
         )
-        mock_glob.return_value = (g for g in ["path/image1.jpg", "path/image2.jpg"])
+        mock_glob.return_value = (g for g in ["path/image2.jpg", "path/image1.jpg"])
         mock_isfile.return_value = isfile
         post.process(mock_base, mock_template)
 
@@ -500,8 +506,19 @@ class TestUnitImagePost:
 
         if isfile:
             assert mock_resize_image.call_count == 2
-            assert post.meta["image_paths"] == ["image1.jpg", "image2.jpg"]
             mock_item_process.assert_called_once_with(mock_base, mock_template)
+
+            if mangle_image_name:
+                assert post.meta["image_paths"] == [
+                    "0-"
+                    + hashlib.sha256(bytearray("image1", "utf-8")).hexdigest()[:7]
+                    + ".jpg",
+                    "1-"
+                    + hashlib.sha256(bytearray("image2", "utf-8")).hexdigest()[:7]
+                    + ".jpg",
+                ]
+            else:
+                assert post.meta["image_paths"] == ["image2.jpg", "image1.jpg"]
         else:
             assert mock_resize_image.call_count == 0
             assert post.meta["image_paths"] == []