簡體   English   中英

如何在混合任務中運行混合任務?

[英]How do I run a mix task from within a mix task?

我想在自定義組合任務中運行混合任務。

就像是

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

但我無法弄清楚如何執行shell命令。 如果有更簡單的方法(除了制作一個bash腳本),請告訴我。

Shell是這里的冗余鏈接。 如果要運行edeliver任務,請運行Mix.Tasks.Edeliver#run

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

Mix.Task.run("edeliver build release")有效

要執行shell命令,您可以使用Loki 您可以找到shell execute/1函數。

以及我在Mix.Task中用於執行其他混音任務的示例:

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

或者只看它如何執行命令:

@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

希望它對你有所幫助。

雖然我從來沒有嘗試通過Mix.shell.cmd從另一個混合任務中運行混合任務,但我不確定它是否是最佳實踐,看起來像你想要的東西會起作用:

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

上面的代碼確實通過mix test運行mix test並打印出它們的輸出。 注意:上面的代碼基於Mix 1.3.4,界面在1.4.0中略有不同。

可能更優雅的方法是為“復合”任務創建混合別名 ,包括您依賴的任務和自定義任務:

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

現在運行mix composite.task應該在my.custom.task之前運行另外兩個任務。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM