larskris
larskris

Reputation: 306

How to alias run twice in mix.exs?

I'm trying to run two different scripts, v1_to_v2_migrator.exs and update_images.exs

defp aliases do
  ["ecto.reset": ["ecto.drop", "ecto.create", "ecto.migrate", "run priv/repo/v1_to_v2_migrator.exs", "run priv/repo/update_images.exs"]

Only the first file runs. I've tried to reenable run but I can't escape the filename.

"run 'priv/repo/v1_to_v2_migrator.exs'; run -e 'Mix.Task.reenable(:run)'"

gives this error:

** (Mix) No such file: priv/repo/v1_to_v2_migrator.exs;

Where the file ending includes the semicolon.

Upvotes: 2

Views: 390

Answers (3)

José Valim
José Valim

Reputation: 51429

For your particular example, you can pass multiple files to run:

mix run -r priv/repo/foo.exs -r priv/repo/bar.exs

But if the question is how to generally reenable tasks, then @Dogbert's and @mudasobwa's approaches are correct.

Upvotes: 4

Dogbert
Dogbert

Reputation: 222398

You can use Mix.Task.rerun/2 to invoke mix run twice like this:

["ecto.reset": [
  "ecto.drop",
  "ecto.create",
  "ecto.migrate",
  ~s|run -e 'Mix.Task.rerun("run", ["priv/repo/v1_to_v2_migrator.exs"]); Mix.Task.rerun("run", ["priv/repo/update_images.exs"])'|]]

Upvotes: 5

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

While answer by @Dogbert would work, I’d suggest you take a different approach. When you find yourself stuck with the tool’s provided functionality it usually means the paradigm change is required.

Unlike many other build tools, mix welcomes task creation. It’s easy, pretty straightforward and more idiomatic than executing multiple scripts. Just create a file, say, my_awesome_task.ex in your lib/mix/tasks directory (create the directory unless it already exists,) using the following scaffold:

defmodule Mix.Tasks.MyAwesomeTask do
  use Mix.Task

  @shortdoc "Migrates v1 to v2 and updates images"

  @doc false
  def run(args \\ []) do
    # it’s better to implement stuff explicitly,
    #   but this is also fine
    Mix.Tasks.Run.run(["priv/repo/v1_to_v2_migrator.exs"])
    Mix.Tasks.Run.rerun(["priv/repo/update_images.exs"])
  end
end

Now all you need is to call this task in your mix.exs:

["ecto.reset": ~w|ecto.drop ecto.create ecto.migrate my_awesome_task|]

Upvotes: 2

Related Questions