# Copyright 2017 Comcast Cable Communications Management, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule Mix.Tasks.Dialyzer.Clean do
  use Mix.Task

  @moduledoc """
  Cleans up PLTs that were generated by the `dialyzer` task. By default, only
  PLTs in the current project are removed.

  ## Options

  * `--all`: Remove the Erlang/OTP and Elixir PLTs in addition to the project
    PLT(s).
  """

  @shortdoc "Cleans up generated PLTs"

  import Mix.Tasks.Dialyzer, only: [otp_plt_name: 0, elixir_plt_name: 0]

  @doc false
  @impl true
  def run(args) do
    project_plts =
      Mix.Project.build_path()
      |> Path.join("deps-*.plt")
      |> Path.wildcard()

    files =
      if "--all" in args do
        [otp_plt_name(), elixir_plt_name()]
      else
        []
      end ++ project_plts

    cleaned_files =
      for file <- files, File.exists?(file) do
        Mix.shell().info("Removing #{file}...")
        File.rm!(file)
      end
      |> Enum.count()

    if cleaned_files > 0 do
      Mix.shell().info([:green, "Removed #{cleaned_files} PLTs!"])
    else
      Mix.shell().info("Nothing to do!")
    end
  end
end
