Skip to content

Commit c8c4cf8

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 c8c4cf8

File tree

2 files changed

+26
-7
lines changed

2 files changed

+26
-7
lines changed

lib/hex/utils.ex

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -331,18 +331,29 @@ 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"),
341+
with :unset <- Process.get(:hex_repo_identifier, :unset),
342+
flag when flag in ["1", "true"] <- System.get_env("HEX_REPO_IDENTIFIER", "1"),
338343
path when is_binary(path) <- System.find_executable("git"),
339344
{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)
345+
identifier =
346+
output
347+
|> String.trim()
348+
|> then(&:crypto.hash(:sha256, &1))
349+
|> Base.encode16(case: :lower)
350+
351+
Process.put(:hex_repo_identifier, identifier)
352+
353+
identifier
344354
else
345-
_ -> nil
355+
cached when is_binary(cached) -> cached
356+
_other -> nil
346357
end
347358
end
348359
end

test/hex/utils_test.exs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,5 +33,13 @@ defmodule Hex.UtilsTest do
3333
after
3434
System.delete_env("HEX_REPO_IDENTIFIER")
3535
end
36+
37+
test "the identifier is cached within the current process" do
38+
value = "cached-identifier"
39+
40+
Process.put(:hex_repo_identifier, value)
41+
42+
assert value == Hex.Utils.repo_identifier()
43+
end
3644
end
3745
end

0 commit comments

Comments
 (0)