Commit 0d4aaf98c32546b310d25320778595f0ac97f317

Michael Crumm 2022-01-19T11:54:24

Use user cache directory

diff --git a/CHANGELOG.md b/CHANGELOG.md
index db51c23..104e424 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,7 @@
 
 ## v0.3.1
 
+  * Use user cache directory (h/t @josevalim)
   * Add support for 32bit linux (h/t @derek-zhou)
   * Support `HTTP_PROXY/HTTPS_PROXY` to fetch esbuild (h/t @iaddict)
   * Update Sass version to `1.43.4`
diff --git a/lib/dart_sass.ex b/lib/dart_sass.ex
index 12dfd4f..d388356 100644
--- a/lib/dart_sass.ex
+++ b/lib/dart_sass.ex
@@ -237,9 +237,12 @@ defmodule DartSass do
   """
   def install do
     version = configured_version()
-    tmp_dir = Path.join(System.tmp_dir!(), "cs-dart-sass")
-    File.rm_rf!(tmp_dir)
-    File.mkdir_p!(tmp_dir)
+    tmp_opts = if System.get_env("MIX_XDG"), do: %{os: :linux}, else: %{}
+
+    tmp_dir =
+      freshdir_p(:filename.basedir(:user_cache, "cs-sass", tmp_opts)) ||
+        freshdir_p(Path.join(System.tmp_dir!(), "cs-sass")) ||
+        raise "could not install sass. Set MIX_XDG=1 and then set XDG_CACHE_HOME to the path you want to use as cache"
 
     platform = detect_platform()
     name = "dart-sass-#{version}-#{target(platform)}"
@@ -270,6 +273,15 @@ defmodule DartSass do
     end
   end
 
+  defp freshdir_p(path) do
+    with {:ok, _} <- File.rm_rf(path),
+         :ok <- File.mkdir_p(path) do
+      path
+    else
+      _ -> nil
+    end
+  end
+
   defp unpack_archive(".zip", zip, cwd) do
     with {:ok, _} <- :zip.unzip(zip, cwd: to_charlist(cwd)), do: :ok
   end