lib/mix/tasks/hf.whoami.ex

defmodule Mix.Tasks.Hf.Whoami do
  @shortdoc "Show the currently authenticated HuggingFace user"
  @moduledoc """
  Displays information about the currently authenticated user.

      $ mix hf.whoami
  """

  use Mix.Task

  @impl Mix.Task
  def run(args) do
    {opts, _, _} = OptionParser.parse(args, strict: [token: :string])
    token = opts[:token] || HuggingfaceClient.Config.token()

    unless token do
      Mix.raise("Not logged in. Run: mix hf.login --token hf_xxx")
    end

    case HuggingfaceClient.Hub.Auth.who_am_i(access_token: token) do
      {:ok, user} ->
        Mix.shell().info("User:  #{user["name"] || user["fullname"]}")
        Mix.shell().info("Email: #{user["email"] || "(not shown)"}")
        orgs = user["orgs"] || []

        if orgs != [] do
          Mix.shell().info("Orgs:  #{Enum.map_join(orgs, ", ", & &1["name"])}")
        end

      {:error, err} ->
        Mix.raise("Authentication failed: #{Exception.message(err)}")
    end
  end
end