Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

Handle cross-device file move (#4640)

ruslandoga52437e8df00e
diff --git a/lib/plausible/file.ex b/lib/plausible/file.ex
new file mode 100644
index 0000000000..689134b945
--- /dev/null
+++ b/lib/plausible/file.ex
@@ -0,0 +1,27 @@
+defmodule Plausible.File do
+ @moduledoc """
+ File helpers for Plausible.
+ """
+
+ @doc """
+ Moves a file from one location to another.
+
+ Tries renaming first, and falls back to copying and deleting the original.
+ """
+ @spec mv!(Path.t(), Path.t()) :: :ok
+ def mv!(source, destination) do
+ File.rename!(source, destination)
+ rescue
+ e in File.RenameError ->
+ try do
+ case e.reason do
+ # fallback to cp/rm for cross-device moves
+ # https://github.com/plausible/analytics/issues/4638
+ :exdev -> File.cp!(source, destination)
+ _ -> reraise(e, __STACKTRACE__)
+ end
+ after
+ File.rm(source)
+ end
+ end
+end
diff --git a/lib/plausible_web/live/csv_import.ex b/lib/plausible_web/live/csv_import.ex
index 5234ba1fe7..20751de4c7 100644
--- a/lib/plausible_web/live/csv_import.ex
+++ b/lib/plausible_web/live/csv_import.ex
@@ -45,7 +45,7 @@ defmodule PlausibleWeb.Live.CSVImport do
fn meta, entry ->
local_path = Path.join(local_dir, Path.basename(meta.path))
- File.rename!(meta.path, local_path)
+ Plausible.File.mv!(meta.path, local_path)
{:ok, %{"local_path" => local_path, "filename" => entry.client_name}}
end
end
diff --git a/lib/workers/export_analytics.ex b/lib/workers/export_analytics.ex
index dd8a8aeb20..51a1c0af06 100644
--- a/lib/workers/export_analytics.ex
+++ b/lib/workers/export_analytics.ex
@@ -101,7 +101,7 @@ defmodule Plausible.Workers.ExportAnalytics do
File.mkdir_p!(Path.dirname(local_path))
if File.exists?(local_path), do: File.rm!(local_path)
- File.rename!(tmp_path, local_path)
+ Plausible.File.mv!(tmp_path, local_path)
end
defp email_failure(args) do