运行 时自定义混合任务不触发编译

Custom mix task not triggering compile when run

我有一个自定义混合任务。它工作完美,但是,它不会像其他混合任务那样在调用时触发编译。我可以 运行 手动编译,但这非常令人沮丧,因为我几乎总是忘记这样做并且必须 运行 任务一次或两次,然后我才意识到为什么我没有看到我的更改。

这是"my"任务,我缺少什么?

defmodule Mix.Tasks.Return do
  @moduledoc """
  Task for processing returns
  """
  use Mix.Task
  require Logger
  alias Returns

  @shortdoc "Check for returns and process"

  def run(args) do
    args
    |> get_return_file_name()
    |> Returns.process()
    |> Kernel.inspect()
    |> Logger.info()
  end

  defp get_file_name(nil), do: get_file_name([])
  defp get_file_name([]), do: get_default_file_name()
  defp get_file_name([filename]), do: filename

  defp get_default_file_name() do
    DateTime.utc_now() 
    |> DateTime.to_string()   
    |> String.split(" ")  
    |> List.first()
    |> (fn date -> "default-#{date}.txt" end).()
  end
end

您需要在您的任务中明确说明您要编译。

@impl true
def run(args) do
  ...
  Mix.Task.run("compile")
  ...

几个例子是app.tree, app.start and phx.routes

这是因为并非所有混合任务都需要编译步骤。例如,mix deps.get 在获取依赖项之前不会编译项目,否则你可能会有很多 errors/warnings 缺少模块。所有依赖项都应该手动调用,没有隐式机制根据 mix.

内置的一些“内部规则”来调用任务链

Mix.Task.run("compile") 修复可能实际上不起作用。 José Valim 有这样的建议:

That's because if they are recompiled, you won't execute the new module version in memory. A work-around is for you to do this:

def run(args) do
  Mix.Task.run("compile")
  __MODULE__.compiled_run(args)
end

def compiled_run(args) do
  ...
end

That will force it to pick the latest version of the module. Although this is probably something we should tackle in Elixir itself.