From c543a211620dd8a7f80f569bba878c8156a0dc5f Mon Sep 17 00:00:00 2001 From: Daniel Poelzleithner Date: Wed, 16 Mar 2022 17:38:03 +0100 Subject: [PATCH] Add function to substitude commands with placeholders --- lsyncd.lua | 24 ++++++++++++++++++++++++ tests/utils_test.lua | 13 +++++++++++++ 2 files changed, 37 insertions(+) diff --git a/lsyncd.lua b/lsyncd.lua index d46553b..3a1adcf 100644 --- a/lsyncd.lua +++ b/lsyncd.lua @@ -3983,6 +3983,30 @@ function splitQuotedString return rv end +function replaceCommand(cmd, data) + assert(type(data) == "table") + local getData = function(arg) + print(arg, data) + local rv = data[arg] + if rv ~= nil then + return rv + else + return "" + end + end + if type(cmd) == "string" then + return string.gsub(cmd, "%${(%w+)}", getData) + elseif type(cmd) == "table" then + local rv = {} + for i, v in ipairs(cmd) do + rv[i] = string.gsub(v, "%${(%w+)}", getData) + end + return rv + else + log("Error", "Unsupported type in replacCommand") + end +end + -- -- Interface to inotify. -- diff --git a/tests/utils_test.lua b/tests/utils_test.lua index c7e6942..c73441a 100644 --- a/tests/utils_test.lua +++ b/tests/utils_test.lua @@ -9,4 +9,17 @@ assert(isTableEqual( {"-p", "22", "-i", "/home/test/bla blu/id_rsa"} )) +-- test string replacement +local testData = { + localPort = 1234, + localHost = "localhorst" +} +assert(replaceCommand("echo ssh ${localHost}:${localPort}", testData) == + "echo ssh localhorst:1234") + +assert(isTableEqual( + replaceCommand({"-p${doesNotExist}", "2${localHost}2", "-i '${localPort}'"}, testData), + {"-p", "2localhorst2", "-i '1234'"} +)) + os.exit(0) \ No newline at end of file