Module:auto cat

Revision as of 13:46, 5 February 2024 by Maria (talk | contribs)
local export = {}

-- %s = any string
-- %l = any language name
-- %c = any language code
local pattern_matches = {
	["%s by language"] = {"Fundamental"},
	["%l %s"] = {"%s by language", "%l language"},
}
local no_match = "Category pages not matched by auto cat"

function get_lua_pattern_from_pattern(pattern)
	pattern = string.gsub(pattern, "%s", "(.+)")
	pattern = string.gsub(pattern, "%l", "([%a-]+)")
	pattern = string.gsub(pattern, "%c", "([%l-]+)")
	return "^" .. pattern .. "$"
end

function process_category(pattern, category_name)
	-- TODO: make this work
	return {}
end

function categories_to_string(categories)
	local out = ""
	for _, category in ipairs(categories) do
		out = out .. "[[Category:" .. category .. "]]"
	end
	return out
end

function export.show(frame)
	local title_obj = mw.title.getCurrentTitle()
	if title_obj.nsText ~= "Category" then
		error("{{auto cat}} can only be used on pages in the Category: namespace")
	end
	local category_name = title_obj.text
	
	local categories = nil
	
	for pattern, categories in ipairs(pattern_matches) do
		lua_pattern = get_lua_pattern_from_pattern(pattern)
		if string.find(category_name, lua_pattern) ~= nil then
			categories = process_category(pattern, category_name)
			break
		end
	end
	
	if categories == nil then
		categories = {no_match}
	end
	return categories_to_string(categories)
end

return export