How to start a mix task from a mix task?

I would like to start a mix task from a custom mix task.

Sort of

def run(_) do Mix.Shell.cmd("mix edeliver build release") #do other stuff 

But I canโ€™t figure out how to execute a shell command. If there is an easier way (besides creating a bash script) let me know.

+5
source share
3 answers

Shell is a redundant link here. If you want to run the edeliver task, run Mix.Tasks.Edeliver#run :

 def run(_) do Mix.Tasks.Edeliver.run(~w|build release|) # do other stuff 
+9
source

You can use Loki to execute a shell command. You can find functions to execute the execute/1 shell.

And an example of how I used in Mix.Task to perform other mixing tasks:

 defmodule Mix.Tasks.Sesamex.Gen.Auth do use Mix.Task import Loki.Cmd import Loki.Shell @spec run(List.t) :: none() def run([singular, plural]) do execute("mix sesamex.gen.model #{singular} #{plural}") execute("mix sesamex.gen.controllers #{singular}") execute("mix sesamex.gen.views #{singular}") execute("mix sesamex.gen.templates #{singular}") execute("mix sesamex.gen.routes #{singular}") # ... end end 

Or just see how it executes the command:

 @spec execute(String.t, list(Keyword.t)) :: {Collectable.t, exit_status :: non_neg_integer} def execute(string, opts) when is_bitstring(string) and is_list(opts) do [command | args] = String.split(string) say IO.ANSI.format [:green, " * execute ", :reset, string] System.cmd(command, args, env: opts) end 

I hope he helps you.

+1
source

While I never tried to run the mix task using Mix.shell.cmd from inside another mix task, and I'm not sure if this is the best practice, it seems like something like what you are aiming for will work:

 def run(args) do Mix.Shell.cmd("mix test", fn(output) -> IO.write(output) end) # (...) end 

The above code runs the tests through mix test and prints their output. Note: the above code is based on Mix 1.3.4, the interface is slightly different in 1.4.0.

Which may be a more elegant approach, although it will create a mixing alias for a โ€œcomplexโ€ task consisting of tasks for which you depend and your user:

 # inside mix.exs def project do [ # (...) aliases: [ "composite.task": [ "test", "edeliver build release", "my.custom.task", ] ] ] end 

Now running mix composite.task should do two other tasks before my.custom.task .

0
source

Source: https://habr.com/ru/post/1262817/


All Articles