Skip to content

Commit ffb5c02

Browse files
committed
Add local caching to repo identifier lookup
Prevents fetching the same identifier on every client call by caching the value in the current process dictionary. While the git command isn't particularly slow, this should avoid spawning during repeated http calls.
1 parent 9de9bfe commit ffb5c02

File tree

2 files changed

+37
-10
lines changed

2 files changed

+37
-10
lines changed

lib/hex/utils.ex

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -331,18 +331,33 @@ defmodule Hex.Utils do
331331
This function finds the SHA of the first commit in the repository and hashes it once more for
332332
anonymization.
333333
334-
Returns `nil` if git is not available or the directory is not a git repository.
334+
Returns `nil` when:
335+
336+
- The `HEX_REPO_IDENTIFIER` environment variable is set to anything other `1` or `true`
337+
- The `git` executable isn't available
338+
- The current directory isn't within a git repository
335339
"""
336340
def repo_identifier do
337-
with flag when flag in ["1", "true"] <- System.get_env("HEX_REPO_IDENTIFIER", "1"),
338-
path when is_binary(path) <- System.find_executable("git"),
339-
{output, 0} <- System.cmd("git", ["rev-list", "--max-parents=0", "HEAD"]) do
340-
output
341-
|> String.trim()
342-
|> then(&:crypto.hash(:sha256, &1))
343-
|> Base.encode16(case: :lower)
344-
else
345-
_ -> nil
341+
case Process.get(:hex_repo_identifier, :unset) do
342+
cached when is_binary(cached) ->
343+
cached
344+
345+
_ ->
346+
with flag when flag in ["1", "true"] <- System.get_env("HEX_REPO_IDENTIFIER", "1"),
347+
path when is_binary(path) <- System.find_executable("git"),
348+
{output, 0} <- System.cmd("git", ["rev-list", "--max-parents=0", "HEAD"]) do
349+
identifier =
350+
output
351+
|> String.trim()
352+
|> then(&:crypto.hash(:sha256, &1))
353+
|> Base.encode16(case: :lower)
354+
355+
Process.put(:hex_repo_identifier, identifier)
356+
357+
identifier
358+
else
359+
_other -> nil
360+
end
346361
end
347362
end
348363
end

test/hex/utils_test.exs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
defmodule Hex.UtilsTest do
22
use ExUnit.Case
33

4+
setup do
5+
on_exit(fn -> Process.delete(:hex_repo_identifier) end)
6+
end
7+
48
describe "repo_identifier/0" do
59
test "an identifier is included within a repository" do
610
assert Hex.Utils.repo_identifier() =~ ~r/^[a-f0-9]{64}$/
@@ -33,5 +37,13 @@ defmodule Hex.UtilsTest do
3337
after
3438
System.delete_env("HEX_REPO_IDENTIFIER")
3539
end
40+
41+
test "the identifier is cached within the current process" do
42+
value = "cached-identifier"
43+
44+
Process.put(:hex_repo_identifier, value)
45+
46+
assert value == Hex.Utils.repo_identifier()
47+
end
3648
end
3749
end

0 commit comments

Comments
 (0)