2.4 KiB · text History 573fef1
defmodule VigilWeb.Api.V0.ReleaseJSON do
  @moduledoc """
  Releases, deploys and commits in Sentry's shapes (2019 Sentry's
  `api/serializers/models/{release,deploy,commit}.py`), with what
  sentry-cli's `ReleaseInfo` and `Deploy` need: `version` and
  `dateCreated` always; `shortVersion` too (GlitchTip's `ReleaseSchema`
  emits both, MIT).
  """

  alias Vigil.Releases
  alias Vigil.Releases.{Deploy, Release}

  @doc "A release; `stats` from `Vigil.Releases.release_stats/1`."
  def release(%Release{} = r, stats) do
    stats = stats || %{}
    by_project = stats[:new_groups_by_project] || %{}
    commits = Releases.list_commits(r)

    %{
      id: r.id,
      version: r.version,
      shortVersion: Releases.short_version(r.version),
      status: to_string(r.status),
      ref: r.ref,
      url: r.url,
      dateCreated: r.inserted_at,
      dateReleased: r.date_released,
      data: Map.drop(r.data || %{}, ["commits"]),
      newGroups: stats[:new_groups] || 0,
      owner: nil,
      commitCount: r.commit_count,
      lastCommit: commits |> List.first() |> then(&(&1 && commit(&1))),
      deployCount: r.deploy_count,
      lastDeploy: stats[:last_deploy] && deploy(stats[:last_deploy]),
      authors: Releases.authors(r),
      projects:
        Enum.map(r.projects, fn p ->
          %{
            # As elsewhere in /api/0: a project's id is its DSN number.
            id: to_string(p.dsn_id),
            slug: p.slug,
            name: p.name,
            platform: p.platform,
            platforms: if(p.platform, do: [p.platform], else: []),
            newGroups: Map.get(by_project, p.id, 0)
          }
        end),
      firstEvent: stats[:first_event],
      lastEvent: stats[:last_event]
    }
  end

  def deploy(%Deploy{} = d) do
    %{
      id: d.id,
      environment: d.environment,
      name: d.name,
      url: d.url,
      dateStarted: d.date_started,
      dateFinished: d.date_finished
    }
  end

  @doc """
  A commit as kept from sentry-cli's `GitCommit`, in Sentry's shape, plus
  GlitchTip's flat `authorName`/`authorEmail`.
  """
  def commit(c) do
    %{
      id: c["id"],
      message: c["message"],
      dateCreated: c["timestamp"],
      repository: c["repository"] && %{name: c["repository"]},
      author:
        if(c["author_email"] || c["author_name"],
          do: %{name: c["author_name"], email: c["author_email"]}
        ),
      authorName: c["author_name"],
      authorEmail: c["author_email"]
    }
  end
end