Skip to content

Commit

Permalink
Add RDF.Diff.apply/2
Browse files Browse the repository at this point in the history
  • Loading branch information
marcelotto committed Nov 20, 2019
1 parent b6438b1 commit a1cbbd2
Show file tree
Hide file tree
Showing 2 changed files with 107 additions and 1 deletion.
23 changes: 22 additions & 1 deletion lib/rdf/diff.ex
Expand Up @@ -30,7 +30,7 @@ defmodule RDF.Diff do
defp coerce_graph(data), do: Graph.new(data)

@doc """
Computes the diff between two `RDF.Graph`s or `RDF.Description`s.
Computes a diff between two `RDF.Graph`s or `RDF.Description`s.
The first argument represents the original and the second argument the new version
of the RDF data to be compared. Any combination of `RDF.Graph`s or
Expand Down Expand Up @@ -149,4 +149,25 @@ defmodule RDF.Diff do
deletions: Graph.add(diff1.deletions, diff2.deletions)
)
end

@doc """
Applies a diff to a `RDF.Graph` or `RDF.Description` by deleting the `deletions` and adding the `additions` of the `diff`.
Deletions of statements which are not present in the given graph or description
are simply ignored.
The result of an application is always a `RDF.Graph`, even if a `RDF.Description`
is given and the additions from the diff are all about the subject of this description.
"""
def apply(diff, rdf_data)

def apply(%__MODULE__{} = diff, %Graph{} = graph) do
graph
|> Graph.delete(diff.deletions)
|> Graph.add(diff.additions)
end

def apply(%__MODULE__{} = diff, %Description{} = description) do
__MODULE__.apply(diff, Graph.new(description))
end
end
85 changes: 85 additions & 0 deletions test/unit/diff_test.exs
Expand Up @@ -197,4 +197,89 @@ defmodule RDF.DiffTest do
])
)
end

describe "apply/2" do
test "on a graph" do
assert Diff.new(
additions: Graph.new([
EX.S1
|> EX.p(EX.O3)
|> EX.p3(EX.O),
EX.S3
|> EX.p(EX.O)
]),
deletions: Graph.new([
EX.S1
|> EX.p(EX.O1)
|> EX.p2(EX.O),
EX.S2
|> EX.p(EX.O)
]))
|> Diff.apply(Graph.new([
EX.S1
|> EX.p(EX.O1, EX.O2)
|> EX.p2(EX.O),
EX.S2
|> EX.p(EX.O)
])) ==
Graph.new([
EX.S1
|> EX.p(EX.O2, EX.O3)
|> EX.p3(EX.O),
EX.S3
|> EX.p(EX.O)
])
end

test "on a description" do
assert Diff.new(
additions: Graph.new([
EX.S1
|> EX.p(EX.O3)
|> EX.p3(EX.O),
EX.S3
|> EX.p(EX.O)
]),
deletions: Graph.new([
EX.S1
|> EX.p(EX.O1)
|> EX.p2(EX.O),
]))
|> Diff.apply(
EX.S1
|> EX.p(EX.O1, EX.O2)
|> EX.p2(EX.O)
) ==
Graph.new([
EX.S1
|> EX.p(EX.O2, EX.O3)
|> EX.p3(EX.O),
EX.S3
|> EX.p(EX.O)
])
end

test "when the statements to be deleted are not present" do
assert Diff.new(
additions: Graph.new(
EX.S1
|> EX.p(EX.O4)
),
deletions: Graph.new([
EX.S1
|> EX.p(EX.O2, EX.O3)
|> EX.p2(EX.O),
EX.S2
|> EX.p(EX.O)
]))
|> Diff.apply(Graph.new(
EX.S1
|> EX.p(EX.O1, EX.O2)
)) ==
Graph.new(
EX.S1
|> EX.p(EX.O1, EX.O4)
)
end
end
end

0 comments on commit a1cbbd2

Please sign in to comment.