This repository has been archived by the owner on Oct 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Define Xgit.Core.ObjectId for describing SHA-1 object IDs. (#13)
* Define Xgit.Core.ObjectId for describing SHA-1 object IDs. * A few minor tweaks.
- Loading branch information
Showing
2 changed files
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |