diff options
author | koray kavukcuoglu <koray@kavukcuoglu.org> | 2015-01-13 21:08:52 +0300 |
---|---|---|
committer | koray kavukcuoglu <koray@kavukcuoglu.org> | 2015-01-13 21:08:52 +0300 |
commit | 0eaa799c4fa494e8b46133f0d1c76f10538e32b1 (patch) | |
tree | e46fbc03e403ce7620c91a61db238b9267cd74c7 | |
parent | 3bad63d42993df054ed12a4e123baf9584627a28 (diff) | |
parent | b07a42e7cfa9953a1981d1d0bc455a59635fa58b (diff) |
Merge pull request #8 from jjh42/annotations
Working with annotations.
-rw-r--r-- | init.lua | 40 | ||||
-rw-r--r-- | test_graphviz.lua | 12 |
2 files changed, 50 insertions, 2 deletions
@@ -164,6 +164,30 @@ function Graph:leaves() return leaves end + +function graph._dotEscape(str) + if string.find(str, '[^a-zA-Z]') then + -- Escape newlines. + local escaped = string.gsub(str, '\n', '\\n') + str = '"' .. escaped .. '"' + end + return str +end + + +--[[ Generate a string like 'color=blue tailport=s' from a table + (e.g. {color = 'blue', tailport = 's'}. Its up to the user to escape + strings properly. +]] +local function makeAttributeString(attributes) + str = {} + for k, v in pairs(attributes) do + table.insert(str, tostring(k) .. '=' .. graph._dotEscape(tostring(v))) + end + return ' ' .. table.concat(str, ' ') +end + + function Graph:todot(title) local nodes = self.nodes local edges = self.edges @@ -175,9 +199,21 @@ function Graph:todot(title) table.insert(str,'node [shape = oval]; ') local nodelabels = {} for i,node in ipairs(nodes) do - local l = '"' .. ( 'Node' .. node.id .. '\\n' .. node:label() ) .. '"' + local nodeName + if node.graphName then + nodeName = node:graphName() + else + nodeName = 'Node' .. node.id + end + local l = graph._dotEscape(nodeName .. '\n' .. node:label()) nodelabels[node] = 'n' .. node.id - table.insert(str, '\n' .. nodelabels[node] .. '[label=' .. l .. '];') + local graphAttributes = '' + if node.graphAttributes then + graphAttributes = makeAttributeString(node:graphAttributes()) + end + table.insert(str, + '\n' .. nodelabels[node] .. + '[label=' .. l .. graphAttributes .. '];') end table.insert(str,'\n') for i,edge in ipairs(edges) do diff --git a/test_graphviz.lua b/test_graphviz.lua index 714d41c..3a18cba 100644 --- a/test_graphviz.lua +++ b/test_graphviz.lua @@ -21,4 +21,16 @@ function tests.layout() "y coordinates should be ordered") end + +function tests.testDotEscape() + tester:assert(graph._dotEscape('red') == 'red', 'Don\'t escape single words') + tester:assert(graph._dotEscape('My label') == '"My label"', + 'Use quotes for spaces') + tester:assert(graph._dotEscape('Non[an') == '"Non[an"', + 'Use quotes for non-alpha characters') + tester:assert(graph._dotEscape('My\nnewline') == '"My\\nnewline"', + 'Escape newlines') +end + + return tester:add(tests):run() |