Script to remove unused snapshots

The AshPostgres schema snapshots take up a lot of lines of code in my project. I remember talk at ElixirConf US 2023 about the possibility of creating a script to remove all but the newest ones. Is there a script like that available?

There is not, unfortunately, but it would be pretty easy to write one :smiley:

# Lists snapshot files that can be deleted
# Save this file to list_old_snapshots.exs, then run
# elixir list_old_snapshots.exs | xargs git rm
defmodule RemoveOldSnapshots do
  def list_files_for_deletion(base_path) do
    base_path
    |> File.ls!()
    |> Enum.map(&Path.join(base_path, &1))
    |> Enum.filter(fn path -> File.lstat!(path).type == :directory end)
    |> Enum.flat_map(fn path ->
      files =
        path
        |> File.ls!()
        |> Enum.sort()
        |> Enum.reverse()

      files =
        case files do
          [_first | rest] -> rest
          [] -> []
        end

      files
      |> Enum.reverse()
      |> Enum.map(&Path.join(path, &1))
    end)
  end
end

files = RemoveOldSnapshots.list_files_for_deletion("priv/resource_snapshots/repo")
IO.puts(Enum.join(files, "\n"))

PR I created that removes old snapshots:

2 Likes

Very nice :smiley:

Ah crap, you’re going to hate me. I didn’t write it and I totally forgot it existed… mix ash_postgres.squash_snapshots — ash_postgres v2.4.11 :sob:

My bad :bowing_man: :bowing_man: :bowing_man:

1 Like

Ah, that one is much nicer!