|
| 1 | +defmodule Mix.Local.Utils do |
| 2 | + @moduledoc """ |
| 3 | + This module collects pieces of common functionality utilized by archive- and escript-related |
| 4 | + tasks. |
| 5 | + """ |
| 6 | + |
| 7 | + @doc """ |
| 8 | + Print a list of items in a uniform way. Used for printing the list of installed archives and |
| 9 | + escripts. |
| 10 | +
|
| 11 | + ## Options |
| 12 | +
|
| 13 | + * `:empty_message` - the message to print when there are no items |
| 14 | + * `:footnote` - the message to print after the list |
| 15 | +
|
| 16 | + """ |
| 17 | + def print_list([], options) do |
| 18 | + Mix.shell.info Keyword.get(options, :empty_message, "No items found.") |
| 19 | + end |
| 20 | + |
| 21 | + def print_list(items, options) do |
| 22 | + Enum.each items, fn item -> Mix.shell.info ["* ", item] end |
| 23 | + Mix.shell.info Keyword.get(options, :footnote, "") |
| 24 | + end |
| 25 | + |
| 26 | + @doc """ |
| 27 | + A common implementation for uninstalling archives, scripts, etc. |
| 28 | +
|
| 29 | + ## Options |
| 30 | +
|
| 31 | + * `:item_name` - the name of the item being uninstalled. Also the name of the task which is used |
| 32 | + to print a list of all such items |
| 33 | + * `:item_plural` - plural of item name |
| 34 | +
|
| 35 | + """ |
| 36 | + def uninstall(argv, root, options) do |
| 37 | + {_, argv, _} = OptionParser.parse(argv) |
| 38 | + |
| 39 | + item_name = Keyword.fetch!(options, :item_name) |
| 40 | + item_plural = Keyword.fetch!(options, :item_plural) |
| 41 | + |
| 42 | + if name = List.first(argv) do |
| 43 | + path = Path.join(root, name) |
| 44 | + if File.regular?(path) do |
| 45 | + if should_uninstall?(path, item_name), do: File.rm!(path) |
| 46 | + else |
| 47 | + Mix.shell.error "Could not find a local #{item_name} named #{inspect name}. "<> |
| 48 | + "Existing #{item_plural} are:" |
| 49 | + Mix.Task.run item_name |
| 50 | + end |
| 51 | + else |
| 52 | + Mix.raise "No #{item_name} was given to #{item_name}.uninstall" |
| 53 | + end |
| 54 | + end |
| 55 | + |
| 56 | + @doc """ |
| 57 | + Parse `path_or_url` as a URI and return its base name. |
| 58 | + """ |
| 59 | + def basename(path_or_url) do |
| 60 | + if path = URI.parse(path_or_url).path do |
| 61 | + Path.basename(path) |
| 62 | + else |
| 63 | + Mix.raise "Expected #{inspect path_or_url} to be a url or a local file path" |
| 64 | + end |
| 65 | + end |
| 66 | + |
| 67 | + defp should_uninstall?(path, item_name) do |
| 68 | + Mix.shell.yes?("Are you sure you want to uninstall #{item_name} #{path}?") |
| 69 | + end |
| 70 | +end |
0 commit comments