简体   繁体   中英

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.

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"])'|]]

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.

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|]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM