defmodule Kvasir.Dev.Downloader do require Logger def clear(component) do File.rm_rf!(dir(component)) end def commit(component) do case File.read(Path.join(dir(component), ".commit")) do {:ok, v} -> v _ -> nil end end def component(component, commit \\ nil) do path = dir(component) c = commit(component) pull = if(String.trim(commit || "") != "", do: commit, else: "release/v1.0") cond do c == pull -> :noop pull == "release/v1" and c != nil -> :noop :download -> Logger.info("Downloading: #{component}") name = if(component == "core", do: "kvasir", else: "kvasir_#{component}") url = "https://github.com/IanLuites/#{name}/tarball/#{pull}" IO.puts(url) with :ok <- File.mkdir_p(path), {:ok, %{body: data}} <- HTTPX.get(url, settings: [follow_redirect: true]), {:ok, files} <- :erl_tar.extract({:binary, data}, [:memory, :compressed]) do Logger.info("Extracting: #{component}") Enum.each(files, fn {file, content} -> case Path.split(to_string(file)) do [_, "lib" | f] -> ff = Path.join([path | f]) File.mkdir_p!(Path.dirname(ff)) File.write!(ff, content) _ -> :ok end end) c = if String.length(pull) == 40 do commit else HTTPX.get!("https://api.github.com/repos/IanLuites/#{name}/git/ref/heads/#{pull}", format: :json ).body["object"]["sha"] end File.write!(Path.join(path, ".commit"), c) :ok else {:error, err} -> Logger.error("Failed: #{component} => #{inspect(err)}") end end end defp dir(component), do: Path.join([__DIR__, "components", component]) end