🏡 index : quine-global/nugitea.git

defmodule Nugitea.Storage do
  @moduledoc """
  The storage tier: owns the repo root and runs every git process, the way
  Gitaly does for GitLab. It trusts its caller; access checks happen once, in
  the app tier, before anything gets here.

  These functions run on the storage node. The app tier reaches them through
  `Nugitea.Storage.Client`: Erlang distribution and nothing else, no protocol
  of our own. With NUGITEA_ROLE=all the "remote" node is this one.

  Repos are addressed by path (`owner/name`, `org/sub-org/name`), laid out
  on disk as `<root>/<path>.git`.
  """

  alias Nugitea.Names

  @services %{"upload-pack" => "upload-pack", "receive-pack" => "receive-pack"}
  # A new repo's default branch, as Gitea's [repository] DEFAULT_BRANCH.
  @default_branch "main"

  @hooks ~w(pre-receive update post-receive)
  @archive_formats ~w(zip tar tar.gz tgz)

  # ---- repos --------------------------------------------------------------

  def dir(path) do
    with :ok <- Names.validate_repo_path(path), do: {:ok, Path.join(root(), path <> ".git")}
  end

  def exists?(path) do
    case dir(path) do
      {:ok, dir} -> File.dir?(dir)
      {:error, _} -> false
    end
  end

  @doc "Every repo under the root, as paths; walks owner dirs, not into repos."
  def list, do: list_under(root(), [])

  defp list_under(dir, owners) do
    for entry <- File.ls!(dir), File.dir?(Path.join(dir, entry)), reduce: [] do
      acc ->
        case String.split_at(entry, -4) do
          {name, ".git"} when owners != [] -> [Enum.join(owners ++ [name], "/") | acc]
          {_, ".git"} -> acc
          _ -> acc ++ list_under(Path.join(dir, entry), owners ++ [entry])
        end
    end
    |> Enum.sort()
  end

  @doc """
  `git init --bare`, then hook delegators, as Gitea's InitRepository and
  CreateDelegateHooks do.
  """
  def init_bare(path) do
    with {:ok, dir} <- dir(path) do
      if File.exists?(dir) do
        {:error, "repo #{inspect(path)} already exists"}
      else
        File.mkdir_p!(dir)
        # On main, Gitea's DEFAULT_BRANCH, not whatever git's
        # init.defaultBranch says (master, here).
        :ok = git(dir, ["init", "--bare", "--quiet", "--initial-branch=#{@default_branch}", "."])
        install_hooks(dir)
      end
    end
  end

  # Gitea's hooks/<name> delegate to `gitea hook <name>`. nugitea's hooks
  # don't do anything yet (no protected branches, no webhooks), so each is a
  # stub that accepts the push: the landing spot for future policy.
  defp install_hooks(dir) do
    for name <- @hooks do
      hook = Path.join([dir, "hooks", name])

      File.write!(
        hook,
        "#!/bin/sh\n# AUTO GENERATED BY NUGITEA, DO NOT MODIFY\ncat >/dev/null\nexit 0\n"
      )

      File.chmod!(hook, 0o755)
    end

    :ok
  end

  @doc "A unary git command in the repo, for mirrors (remote add/remove, fetch, push --mirror)."
  def run_git(path, args) do
    with {:ok, dir} <- dir(path), do: git(dir, args)
  end

  # ---- smart HTTP and SSH ----------------------------------------------

  @doc "The ref advertisement that starts a smart-HTTP exchange (`GET .../info/refs`)."
  def info_refs(path, service, protocol \\ nil) do
    with {:ok, dir} <- existing(path),
         {:ok, cmd} <- service(service) do
      {out, 0} =
        System.cmd("git", [cmd, "--stateless-rpc", "--advertise-refs", dir],
          env: protocol_env(protocol)
        )

      pkt = "# service=git-#{cmd}\n"
      {:ok, [pkt_len(pkt), pkt, "0000", out]}
    end
  end

  defp pkt_len(pkt),
    do:
      (byte_size(pkt) + 4)
      |> Integer.to_string(16)
      |> String.pad_leading(4, "0")
      |> String.downcase()

  @doc """
  Runs `git <service>` for one exchange, started on this node by the app
  tier. Input arrives as `{ref, :input, chunk}` messages then `{ref, :eof}`;
  git's output goes back to `reply_to` as `{ref, :output, chunk}`, then
  `{ref, :exit, status}`. Both directions stream at once, so this serves
  smart HTTP (`stateless: true`, one request then the response) and SSH's
  interactive protocol alike.

  `protocol` is the client's Git-Protocol header (e.g. "version=2"), passed
  to git as GIT_PROTOCOL; `gzip` inflates gzipped HTTP request bodies.

  For receive-pack operations, tracks refs before/after to detect pushes and sends
  `{ref, :pushed, [%{ref, before, after}]}` messages to the reply_to process when changes occur.
  """
  def exchange(reply_to, ref, path, service, opts) do
    {:ok, dir} = existing(path)
    {:ok, cmd} = service(service)

    # For receive-pack, we track refs before and after the operation
    is_receive_pack = cmd == "receive-pack"

    before_refs =
      if is_receive_pack do
        case get_refs(dir) do
          {:ok, refs} -> refs
          _ -> nil
        end
      end

    args = if opts[:stateless], do: [cmd, "--stateless-rpc", dir], else: [cmd, dir]

    git = System.find_executable("git")

    {:ok, _pid, os_pid} =
      :exec.run([git | args], [:stdin, :stdout, :monitor, {:env, protocol_env(opts[:protocol])}])

    inflater = opts[:gzip] && inflater()
    # The repo's directory from here on: git needs it, not the repo's path.
    loop(reply_to, ref, os_pid, inflater, is_receive_pack, before_refs, dir)
  end

  defp loop(reply_to, ref, os_pid, inflater, is_receive_pack, before_refs, path) do
    receive do
      {^ref, :input, chunk} ->
        :exec.send(
          os_pid,
          if(inflater, do: IO.iodata_to_binary(:zlib.inflate(inflater, chunk)), else: chunk)
        )

        loop(reply_to, ref, os_pid, inflater, is_receive_pack, before_refs, path)

      {^ref, :eof} ->
        if inflater, do: :zlib.close(inflater)
        :exec.send(os_pid, :eof)

        # Check if this was a receive-pack operation and track changes
        if is_receive_pack && before_refs do
          case get_refs(path) do
            {:ok, after_refs} ->
              changed_refs = find_changed_refs(before_refs, after_refs)

              unless Enum.empty?(changed_refs) do
                send(reply_to, {ref, :pushed, changed_refs})
              end

            _ ->
              # Do nothing if we can't get the refs
              nil
          end
        end

        loop(reply_to, ref, os_pid, nil, is_receive_pack, before_refs, path)

      {:stdout, ^os_pid, chunk} ->
        send(reply_to, {ref, :output, chunk})
        loop(reply_to, ref, os_pid, inflater, is_receive_pack, before_refs, path)

      {:DOWN, ^os_pid, :process, _, reason} ->
        if is_receive_pack && before_refs, do: adopt_default_branch(path, before_refs)

        # Check if this was a receive-pack operation and track changes
        if is_receive_pack && before_refs do
          case get_refs(path) do
            {:ok, after_refs} ->
              changed_refs = find_changed_refs(before_refs, after_refs)

              unless Enum.empty?(changed_refs) do
                send(reply_to, {ref, :pushed, changed_refs})
              end

            _ ->
              # Do nothing if we can't get the refs
              nil
          end
        end

        send(reply_to, {ref, :exit, exit_status(reason)})
    end
  end

  # Gitea's rule (services/repository/push.go): the first push to an empty
  # repo makes its branch the default, if the default branch (main) wasn't
  # pushed. `dir` is the repo's directory.
  defp adopt_default_branch(dir, []) do
    with {:error, _} <- capture(dir, ["rev-parse", "--verify", "--quiet", "HEAD"]),
         {:ok, out} <- capture(dir, ["for-each-ref", "--format=%(refname:short)", "refs/heads"]),
         [first | _] = branches <- String.split(out, "\n", trim: true) do
      branch = if @default_branch in branches, do: @default_branch, else: first
      git(dir, ["symbolic-ref", "HEAD", "refs/heads/" <> branch])
    end

    :ok
  end

  defp adopt_default_branch(_dir, _before_refs), do: :ok

  defp exit_status(:normal), do: 0
  defp exit_status({:exit_status, status}), do: :exec.status(status) |> elem(1)
  defp exit_status(_), do: 1

  defp inflater do
    z = :zlib.open()
    # 31 = gzip header + max window
    :ok = :zlib.inflateInit(z, 31)
    z
  end

  # The client's Git-Protocol header (HTTP) or GIT_PROTOCOL env (SSH), e.g.
  # "version=2", as git's GIT_PROTOCOL; only what git actually sends.
  defp protocol_env(proto) when is_binary(proto) do
    if proto =~ ~r/\A[A-Za-z0-9=;,._-]+\z/, do: [{"GIT_PROTOCOL", proto}], else: []
  end

  defp protocol_env(nil), do: []

  # ---- file browser -----------------------------------------------------

  @doc "Local branch names."
  def branches(path) do
    with {:ok, dir} <- existing(path),
         {:ok, out} <- capture(dir, ["for-each-ref", "--format=%(refname:short)", "refs/heads"]) do
      {:ok, String.split(out, "\n", trim: true)}
    end
  end

  @doc "Tag names, newest first."
  def tags(path) do
    with {:ok, dir} <- existing(path),
         {:ok, out} <-
           capture(dir, [
             "for-each-ref",
             "--sort=-creatordate",
             "--format=%(refname:short)",
             "refs/tags"
           ]) do
      {:ok, String.split(out, "\n", trim: true)}
    end
  end

  @doc """
  Returns branch tips for all branches including refname, objectname (commit hash) and subject.
  Format matches git for-each-ref output with %(refname) %(objectname) %(subject).
  """
  def branch_tips(path) do
    with {:ok, dir} <- existing(path),
         {:ok, out} <-
           capture(dir, [
             "for-each-ref",
             "--format=%(refname) %(objectname) %(subject)",
             "refs/heads"
           ]) do
      {:ok, String.split(out, "\n", trim: true)}
    end
  end

  @doc """
  Gets branch data for a specific branch with name, commit hash and message.
  """
  def branch(path, branch_name) do
    with {:ok, dir} <- existing(path),
         {:ok, out} <-
           capture(dir, [
             "for-each-ref",
             "--format=%(objectname) %(subject)",
             "refs/heads/#{branch_name}"
           ]) do
      case String.split(out, "\n", trim: true) do
        [line] when line != "" ->
          [commit_hash, message] = String.split(line, " ", parts: 2)
          {:ok, %{name: branch_name, commit: %{id: commit_hash, message: message}}}

        _ ->
          {:error, :not_found}
      end
    end
  end

  @doc "One level of the tree at `ref:path` (or `ref`'s root): `%{name, kind, sha}`."
  def tree(path, ref, subpath) do
    treeish = if subpath == "", do: ref, else: "#{ref}:#{subpath}"

    with {:ok, dir} <- existing(path),
         :ok <- no_leading_dash([ref, subpath]),
         {:ok, out} <- capture(dir, ["ls-tree", treeish]) do
      entries =
        for line <- String.split(out, "\n", trim: true),
            [meta, name] = String.split(line, "\t", parts: 2),
            [_mode, kind, sha] = String.split(meta, " "),
            # commit (submodule) entries aren't browsable
            kind in ["tree", "blob"],
            do: %{name: name, kind: String.to_existing_atom(kind), sha: sha}

      {:ok, entries}
    end
  end

  @doc "The blob at `ref:path`: `%{sha, content}` (raw bytes)."
  def blob(path, ref, subpath) do
    treeish = "#{ref}:#{subpath}"

    with {:ok, dir} <- existing(path),
         :ok <- no_leading_dash([ref, subpath]),
         :ok <- if(subpath == "", do: {:error, "empty path"}, else: :ok),
         {:ok, sha} <- capture(dir, ["rev-parse", treeish]),
         {:ok, content} <- capture(dir, ["cat-file", "blob", treeish]) do
      {:ok, %{sha: String.trim(sha), content: content}}
    end
  end

  @doc "Every file path in `ref`'s tree, recursively (the search feature's list)."
  def files(path, ref) do
    with {:ok, dir} <- existing(path),
         :ok <- no_leading_dash([ref]),
         {:ok, out} <- capture(dir, ["ls-tree", "-r", "--name-only", ref]) do
      {:ok, String.split(out, "\n", trim: true)}
    end
  end

  @doc "The default branch of a repository (`git symbolic-ref --short HEAD`)."
  def default_branch(path) do
    with {:ok, dir} <- existing(path),
         {:ok, out} <- capture(dir, ["symbolic-ref", "--short", "HEAD"]) do
      {:ok, String.trim(out)}
    end
  end

  @doc "Sets the default branch of a repository (refusing a branch that doesn't exist)."
  def set_default_branch(path, branch) do
    with {:ok, dir} <- existing(path),
         {:ok, _out} <- capture(dir, ["show-ref", "--verify", "refs/heads/#{branch}"]) do
      :ok = git(dir, ["symbolic-ref", "HEAD", "refs/heads/#{branch}"])
      :ok
    end
  end

  # git would read a leading "-" as an option, not a ref or path.
  defp no_leading_dash(args) do
    case Enum.find(args, &String.starts_with?(&1, "-")) do
      nil -> :ok
      arg -> {:error, "invalid ref or path #{inspect(arg)}"}
    end
  end

  # ---- helpers ----------------------------------------------------------

  defp existing(path) do
    with {:ok, dir} <- dir(path) do
      if File.dir?(dir), do: {:ok, dir}, else: {:error, :not_found}
    end
  end

  defp service(name) do
    case @services do
      %{^name => cmd} -> {:ok, cmd}
      _ -> {:error, :bad_service}
    end
  end

  defp git(dir, args) do
    case System.cmd("git", ["-C", dir | args], stderr_to_stdout: true) do
      {_, 0} -> :ok
      {out, status} -> {:error, "git #{hd(args)} exited #{status}: #{String.trim(out)}"}
    end
  end

  defp capture(dir, args) do
    case System.cmd("git", ["-C", dir | args], stderr_to_stdout: false) do
      {out, 0} -> {:ok, out}
      {_, status} -> {:error, "git #{hd(args)} exited #{status}"}
    end
  end

  # Get the current refs for a repository to track changes
  defp get_refs(dir) do
    case capture(dir, ["for-each-ref", "--format=%(refname) %(objectname)", "refs/heads"]) do
      {:ok, out} ->
        refs =
          String.split(out, "\n", trim: true)
          |> Enum.map(fn line ->
            [refname, objectname] = String.split(line, " ", parts: 2)
            %{ref: refname, sha: objectname}
          end)

        {:ok, refs}

      {:error, _} = err ->
        err
    end
  end

  # Find references that have changed between before and after snapshots
  defp find_changed_refs(before_refs, after_refs) do
    before_map = Enum.into(before_refs, %{}, fn %{ref: r, sha: s} -> {r, s} end)

    # Find all refs that were either new or changed by comparing with before_refs
    Enum.filter(after_refs, fn %{ref: ref, sha: after_sha} ->
      case Map.get(before_map, ref) do
        nil ->
          # New reference
          true

        before_sha when before_sha != after_sha ->
          # Changed reference  
          true

        _ ->
          # No change
          false
      end
    end)
  end

  @doc "Delete a repository directory from disk."
  def delete(path) do
    with {:ok, dir} <- dir(path) do
      if File.dir?(dir) do
        File.rm_rf!(dir)
        :ok
      else
        {:error, :not_found}
      end
    end
  end

  @doc """
  Forks a repository by cloning it in bare mode. Takes the source repo path and 
  creates a new one at dest path with a git clone --bare --no-local.
  Sets up the hooks like init_bare does.
  """
  def fork(src, dest) do
    with {:ok, src_dir} <- dir(src),
         {:ok, dest_dir} <- dir(dest) do
      if File.dir?(dest_dir) do
        {:error, "repo #{inspect(dest)} already exists"}
      else
        # Clone the repository with --bare --no-local options
        case System.cmd("git", ["clone", "--bare", "--no-local", src_dir, dest_dir]) do
          {_, 0} ->
            install_hooks(dest_dir)
            :ok

          {out, status} ->
            {:error, "git clone exited #{status}: #{String.trim(out)}"}
        end
      end
    end
  end

  @doc """
  Returns the size of a repository in KiB, using `git count-objects -v`.
  The result is the sum of `size` and `size-pack` from git count-objects.
  """
  def size(path) do
    with {:ok, dir} <- existing(path) do
      case capture(dir, ["count-objects", "-v"]) do
        {:ok, output} ->
          # Parse the output to extract size and size-pack
          size =
            output
            |> String.split("\n")
            |> Enum.reduce(0, fn line, acc ->
              case Regex.run(~r/^size:\s+(\d+)/, line) do
                [_, size_str] -> acc + String.to_integer(size_str)
                _ -> acc
              end
            end)

          size_pack =
            output
            |> String.split("\n")
            |> Enum.reduce(0, fn line, acc ->
              case Regex.run(~r/^size-pack:\s+(\d+)/, line) do
                [_, size_pack_str] -> acc + String.to_integer(size_pack_str)
                _ -> acc
              end
            end)

          {:ok, size + size_pack}

        _ ->
          {:error, "Unable to determine size"}
      end
    end
  end

  @doc """
  Lists commits in the repository.

  Options:
  - `limit`: maximum number of commits to return (default: all)
  - `skip`: number of commits to skip (default: 0)
  - `path`: filter commits by path

  Returns a list of commit maps with keys:
  %{sha, parents, author_name, author_email, author_date, committer_name, 
    committer_email, committer_date, message}
  """
  def commits(path, ref, opts) do
    with {:ok, dir} <- existing(path),
         :ok <- no_leading_dash([ref]) do
      # One record per commit, ended by \x1e: the full message (%B) can hold
      # newlines. Dates in strict ISO 8601 (%aI, %cI), as Gitea's API gives.
      base_args = [
        "log",
        "--format=%H%x00%P%x00%an%x00%ae%x00%aI%x00%cn%x00%ce%x00%cI%x00%B%x1e"
      ]

      # The ref goes before the path filter's `--`, or git reads it as a path.
      full_args =
        base_args
        |> add_option(opts, :limit, "-n")
        |> add_option(opts, :skip, "--skip")
        |> Kernel.++([ref])
        |> add_path_filter(opts)

      case capture(dir, full_args) do
        {:ok, out} ->
          commits =
            out
            |> String.split("\x1e")
            |> Enum.map(&String.trim_leading(&1, "\n"))
            |> Enum.reject(&(&1 == ""))
            |> Enum.map(fn commit_line ->
              parts = String.split(commit_line, "\x00", parts: 9)
              message = parts |> Enum.at(8, "") |> String.trim_trailing()

              [
                sha: Enum.at(parts, 0),
                parents: Enum.at(parts, 1) |> String.split(" ", trim: true),
                author_name: Enum.at(parts, 2),
                author_email: Enum.at(parts, 3),
                author_date: Enum.at(parts, 4),
                committer_name: Enum.at(parts, 5),
                committer_email: Enum.at(parts, 6),
                committer_date: Enum.at(parts, 7),
                message: message,
                subject: message |> String.split("\n", parts: 2) |> hd()
              ]
            end)

          {:ok, commits}

        {:error, _} = err ->
          err
      end
    end
  end

  defp add_option(args, opts, key, flag) do
    if opts[key] do
      args ++ [flag, Integer.to_string(opts[key])]
    else
      args
    end
  end

  defp add_path_filter(args, opts) do
    if opts[:path] do
      args ++ ["--follow", "--", opts[:path]]
    else
      args
    end
  end

  @doc """
  A commit's diff as text/plain: against its first parent, as Gitea shows
  it, renames detected, and against nothing for a repo's first commit
  (`sha^` doesn't exist there).
  """
  def commit_diff(path, sha) do
    with {:ok, dir} <- existing(path),
         :ok <- no_leading_dash([sha]),
         {:ok, out} <-
           capture(dir, [
             "diff-tree",
             "-p",
             "--root",
             "-M",
             "--no-commit-id",
             "-m",
             "--first-parent",
             sha
           ]) do
      {:ok, out}
    end
  end

  @doc "The files that differ between `base` and `head` (`git diff --name-only BASE...HEAD`)."
  def changed_files(path, base, head) do
    with {:ok, dir} <- existing(path),
         :ok <- no_leading_dash([base, head]),
         {:ok, out} <- capture(dir, ["diff", "--name-only", "#{base}...#{head}"]) do
      {:ok, String.split(out, "\n", trim: true)}
    end
  end

  @doc "Get the patch for a commit as text/plain"
  def commit_patch(path, sha) do
    with {:ok, dir} <- existing(path),
         :ok <- no_leading_dash([sha]),
         {:ok, out} <- capture(dir, ["format-patch", "-1", "--stdout", sha]) do
      {:ok, out}
    end
  end

  @doc """
  Archives a repository at a specific reference with a prefix.

  The format must be either "zip" or "tar.gz".
  The name of the archive is based on the repository name.
  Returns a stream of binary data of the archive.
  """
  def archive(path, ref, format) do
    with {:ok, dir} <- existing(path),
         :ok <- no_leading_dash([ref]),
         :ok <- if(format in @archive_formats, do: :ok, else: {:error, "bad archive format"}),
         name <- path |> String.split("/") |> List.last(),
         prefix = "#{name}/",
         command = ["archive", "--format=#{format}", "--prefix=#{prefix}", ref] do
      case System.cmd("git", ["-C", dir | command], stderr_to_stdout: false) do
        {out, 0} -> {:ok, out}
        {_err, status} -> {:error, "git archive exited with status #{status}"}
      end
    end
  end

  @doc """
  Creates a new tag in repository.

  Creates an annotated tag with the given name, target, and message.

  Options:
  - `message`: optional annotation message (default: no message)
  - `target`: reference to tag (default: HEAD)

  Returns :ok on success, or {:error, reason} on failure.
  """
  def create_tag(path, name, target, message) do
    with {:ok, dir} <- existing(path),
         :ok <- check_ref_format(name),
         :ok <- no_leading_dash([name, target]) do
      if message != "" do
        # Create annotated tag with message
        git(dir, ["tag", "-a", "-m", message, name, target])
      else
        # Create lightweight tag 
        git(dir, ["tag", name, target])
      end
    end
  end

  @doc "Deletes a tag from repository."
  def delete_tag(path, name) do
    with {:ok, dir} <- existing(path),
         :ok <- no_leading_dash([name]) do
      # Attempt to delete the tag - git will return error if tag doesn't exist
      case git(dir, ["tag", "-d", name]) do
        :ok -> :ok
        # If deletion fails due to non-existent tag, treat as success
        {:error, _} -> :ok
      end
    end
  end

  @doc """
  Creates a new branch in repository.

  Checks that the branch name is valid using git check-ref-format --branch.
  The branch will be created from an existing reference (from_ref).
  """
  def create_branch(path, name, from_ref) do
    with {:ok, dir} <- existing(path),
         :ok <- check_ref_format(name),
         :ok <- no_leading_dash([from_ref]),
         {:ok, _out} <- capture(dir, ["update-ref", "refs/heads/#{name}", from_ref]) do
      :ok
    end
  end

  @doc """
  Returns the number of commits in a repository.

  Uses `git rev-list --count HEAD` to count the commits in the repository.
  """
  def commit_count(path) do
    with {:ok, dir} <- existing(path) do
      case capture(dir, ["rev-list", "--count", "HEAD"]) do
        {:ok, output} ->
          # Parse the output as an integer (trim whitespace and parse)
          {:ok, String.trim(output) |> String.to_integer()}

        {:error, _} = err ->
          err
      end
    end
  end

  defp check_ref_format(name) do
    case System.cmd("git", ["check-ref-format", "--branch", name]) do
      {_, 0} -> :ok
      {_, _} -> {:error, "invalid branch name #{inspect(name)}"}
    end
  end

  defp root, do: Application.fetch_env!(:nugitea, :repo_root)
end