From 6841eb17526b2ea4b3967102c1989564192e7e7e Mon Sep 17 00:00:00 2001 From: Tom van Dijck Date: Wed, 10 May 2017 09:20:47 -0700 Subject: [PATCH] [core] Allow filters to be written as: ```lua filter { files = { "**.c" }, system = "windows" } ``` --- src/base/criteria.lua | 35 ++++++++++++++++++++++++++++++++++- tests/base/test_criteria.lua | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/src/base/criteria.lua b/src/base/criteria.lua index 99b51841..70854b4b 100644 --- a/src/base/criteria.lua +++ b/src/base/criteria.lua @@ -37,6 +37,39 @@ } +-- +-- Flattens a hierarchy of criteria terms into a single array containing all +-- of the values as strings in the form of "term:value1 or value2" etc. +-- + function criteria.flatten(terms) + local result = {} + + local function flatten(terms) + for key, value in pairs(terms) do + if type(key) == "number" then + if type(value) == "table" then + flatten(value) + elseif value then + table.insert(result, value) + end + elseif type(key) == "string" then + local word = key .. ":" + if type(value) == "table" then + local values = table.flatten(value) + word = word .. table.concat(values, " or ") + else + word = word .. value + end + table.insert(result, word) + else + error("Unknown key type in terms.") + end + end + end + + flatten(terms) + return result + end --- -- Create a new criteria object. @@ -51,7 +84,7 @@ --- function criteria.new(terms, unprefixed) - terms = table.flatten(terms) + terms = criteria.flatten(terms) -- Preprocess the list of terms for better performance in matches(). -- Each term is replaced with a pattern, with an implied AND between diff --git a/tests/base/test_criteria.lua b/tests/base/test_criteria.lua index 78f29f31..2992b85e 100644 --- a/tests/base/test_criteria.lua +++ b/tests/base/test_criteria.lua @@ -171,6 +171,40 @@ end +-- +-- Test criteria creation through a table. +-- + + function suite.createCriteriaWithTable() + crit = criteria.new { + files = { "**.c" }, + system = "windows" + } + test.istrue(criteria.matches(crit, { system="windows", files="hello.c" })) + end + + function suite.createCriteriaWithTable2() + crit = criteria.new { + system = "not windows" + } + test.isfalse(criteria.matches(crit, { system="windows" })) + end + + function suite.createCriteriaWithTable3() + crit = criteria.new { + system = "not windows or linux" + } + test.istrue(criteria.matches(crit, { system="macosx" })) + end + + function suite.createCriteriaWithTable4() + crit = criteria.new { + system = "windows or linux" + } + test.istrue(criteria.matches(crit, { system="windows" })) + end + + -- -- "Not" modifiers can also be used on filenames. --