|
| 1 | +defmodule Mix.Tasks.TemplateAssets do |
| 2 | + use Mix.Task |
| 3 | + |
| 4 | + alias ComponentsGuideWeb.Endpoint |
| 5 | + |
| 6 | + @shortdoc "Move images from templates to static assets" |
| 7 | + def run(_) do |
| 8 | + Mix.Task.run("app.start") |
| 9 | + |
| 10 | + image_paths = Path.wildcard(Path.join(templates_path(), "/**/*.{png,jpg,jpeg,gif}")) |
| 11 | + for image_path <- image_paths do |
| 12 | + process_image(image_path) |
| 13 | + end |
| 14 | + |
| 15 | + # templates_path = Application.app_dir(:components_guide_web, "templates") |
| 16 | + # Application.app_dir(:components_guide_web, "priv") |
| 17 | + |
| 18 | + count = Enum.count(image_paths) |
| 19 | + |
| 20 | + Mix.shell().info("Processed #{count} file(s).") |
| 21 | + end |
| 22 | + |
| 23 | + defp project_dir(), do: File.cwd! |
| 24 | + defp templates_path(), do: Path.join(project_dir(), "/apps/components_guide_web/lib/components_guide_web/templates") |
| 25 | + defp static_collected_dir(), do: Path.join(project_dir(), "/apps/components_guide_web/priv/static/collected") |
| 26 | + |
| 27 | + defp process_image(image_path) do |
| 28 | + data = File.read!(image_path) |
| 29 | + media_type = MIME.from_path(image_path) |
| 30 | + hash = :crypto.hash(:sha256, data) |
| 31 | + hash_base64 = hash |> Base.url_encode64() |
| 32 | + destination_dir = Path.join(static_collected_dir(), media_type) |
| 33 | + File.mkdir_p!(destination_dir) |
| 34 | + extension = MIME.extensions(media_type) |> List.first() |
| 35 | + destination_path = Path.join(destination_dir, "#{hash_base64}.#{extension}") |
| 36 | + File.copy!(image_path, destination_path) |
| 37 | + Mix.shell().info("Copied #{image_path} to #{destination_path}") |
| 38 | + end |
| 39 | +end |
0 commit comments