File: cache.ex

package info (click to toggle)
erlang-hex 2.0.6-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,204 kB
  • sloc: erlang: 2,950; sh: 203; makefile: 10
file content (31 lines) | stat: -rw-r--r-- 684 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
defmodule Hex.Netrc.Cache do
  @moduledoc false

  alias Hex.Netrc.Parser

  @agent_name __MODULE__

  def start_link(_arg) do
    Agent.start_link(fn -> %{} end, name: @agent_name)
  end

  def child_spec(arg) do
    %{
      id: __MODULE__,
      start: {__MODULE__, :start_link, [arg]}
    }
  end

  def fetch(path \\ Parser.netrc_path()) when is_binary(path) do
    Agent.get_and_update(@agent_name, fn cache ->
      case Map.fetch(cache, path) do
        {:ok, cached_parse_result} ->
          {cached_parse_result, cache}

        :error ->
          parse_result = Parser.parse(path)
          {parse_result, Map.put(cache, path, parse_result)}
      end
    end)
  end
end