Skip to content
This repository has been archived by the owner on Oct 8, 2020. It is now read-only.

Commit

Permalink
Define Xgit.Core.ObjectId for describing SHA-1 object IDs. (#13)
Browse files Browse the repository at this point in the history
* Define Xgit.Core.ObjectId for describing SHA-1 object IDs.

* A few minor tweaks.
  • Loading branch information
scouten committed Jul 14, 2019
1 parent 50138d1 commit 56521e4
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
28 changes: 28 additions & 0 deletions lib/xgit/core/object_id.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
defmodule Xgit.Core.ObjectId do
@moduledoc ~S"""
An object ID is a string that identifies an object within a repository.
This string must match the format for a SHA-1 hash (i.e. 40 characters
of lowercase hex).
"""

@typedoc "A string containing 40 bytes of lowercase hex digits."
@type t :: String.t()

@doc ~S"""
Get the special all-null object ID, often used to stand-in for no object.
"""
@spec zero :: t
def zero, do: "0000000000000000000000000000000000000000"

@doc ~S"""
Returns `true` if the value is a valid object ID.
(In other words, is it a string containing 40 characters of lowercase hex?)
"""
@spec valid?(id :: term) :: boolean
def valid?(id)

def valid?(s) when is_binary(s), do: String.length(s) == 40 && String.match?(s, ~r/^[0-9a-f]+$/)
def valid?(_), do: false
end
23 changes: 23 additions & 0 deletions test/xgit/core/object_id_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
defmodule Xgit.Core.ObjectIdTest do
use ExUnit.Case, async: true

alias Xgit.Core.ObjectId

test "zero/0" do
zero = ObjectId.zero()
assert is_binary(zero)
assert String.length(zero) == 40
assert ObjectId.valid?(zero)
assert String.match?(zero, ~r/^0+$/)
end

test "valid?/1" do
assert ObjectId.valid?("1234567890abcdef12341234567890abcdef1234")
refute ObjectId.valid?("1234567890abcdef1231234567890abcdef1234")
refute ObjectId.valid?("1234567890abcdef123451234567890abcdef1234")
refute ObjectId.valid?("1234567890abCdef12341234567890abcdef1234")
refute ObjectId.valid?("1234567890abXdef12341234567890abcdef1234")

refute ObjectId.valid?(nil)
end
end

0 comments on commit 56521e4

Please sign in to comment.