Module:Category handler: Difference between revisions

From Xenharmonic Wiki
Jump to navigation Jump to search
Ganaram inukshuk (talk | contribs)
overhaul logic for suffixes?
Ganaram inukshuk (talk | contribs)
No edit summary
Line 110: Line 110:
-- suppressed suffix (subpage)
-- suppressed suffix (subpage)
function p._category_handler(cats, ns_override, suffixes, is_debug)
function p._category_handler(cats, ns_override, suffixes, is_debug)
local cats = cats or {}
    local cats = cats or {}
local is_debug = yesno(is_debug, false)
    local is_debug = yesno(is_debug, false)
local title = mw.title.getCurrentTitle()


-- Don't bother if if:
    local frame = mw.getCurrentFrame()
-- - In debug mode
    -- Get the page where the template/module is being used (parent frame)
-- - In a suppressed namespace
    local parent_title = frame:getParent() and mw.title.new(frame:getParent():getTitle()) or mw.title.getCurrentTitle()
-- - On a subpage like /doc or /sandbox (but not if transcluded)
    local parent_ns = parent_title.nsText
-- - Not a "content" page (IE, not a main/module/template page)
if is_debug
or is_suppressed_namespace(ns_override)
or not title.isContentPage
then
return ''
end


-- Categorize
    -- Don't categorize if:
local result = ''
    -- - Debug mode is on (force suppress)
for _, cat in ipairs(cats) do
    -- - Parent page is in suppressed namespace
cat = mw.text.trim(cat or '')
    -- - Parent page is NOT a content page (e.g. subpages like /doc, /sandbox)
if cat ~= '' then
    if is_debug
result = result .. string.format('[[Category:%s]]', cat)
        or is_suppressed_namespace(ns_override, parent_ns)
end
        or not parent_title.isContentPage
end
    then
        return ''
    end


return result
    -- Categorize
    local result = ''
    for _, cat in ipairs(cats) do
        cat = mw.text.trim(cat or '')
        if cat ~= '' then
            result = result .. string.format('[[Category:%s]]', cat)
        end
    end
 
    return result
end
end



Revision as of 07:14, 21 October 2025

Module documentation[view] [edit] [history] [purge]
This module may be invoked by templates using its corresponding template Template:Category handler, or used directly from other modules.
Module:Category handler is ready for use. This message indicates that a module is ready for use, or has recently been repaired. This message may be removed once this module has been used on several pages or once it is verified to work as intended.

Details: Functionally complete. Default lists may be adjusted still.

Introspection summary for Module:Category handler 
Functions provided (2)
Line Function Params
111 _category_handler (main) (cats, ns_override, suffixes, is_debug)
144 category_handler (invokable) (frame)
Lua modules required (1)
Variable Module Functions used
yesno Module:Yesno yesno

No function descriptions were provided. The Lua code may have further information.


-- This module follows [[User:Ganaram inukshuk/Provisional style guide for Lua]]
local yesno = require("Module:Yesno")

local p = {}

-- Basic category handler, based on Wikipedia's category handler. It categorizes
-- pages, given a table of categories as input, and suppresses categorization if
-- the page is in the table of excluded namespaces, or table of excluded 
-- suffixes (subpages).
-- The most common categorizing templates that have/require complex rules are:
-- - Infoboxes; these usually shouldn't categorize if they're outside the main
--   namespace.
-- - Certain mboxes; some mboxes categorize certain pages, but they shouldn't
--   categorize their own documentation.

-- Default list of namespaces in which to suppress categorization. Most
-- categorizing templates are expected to be placed in main, template, or
-- module; those that don't are likely special-use templates (like idiosyncratic
-- and editable user page) which likely won't need this module, or templates
-- with very basic categorization rules for which this is overkill.
-- Adjust as needed!
local DEFAULT_SUPPRESSED_NAMESPACES = {
    ["talk"] = true,
    ["user"] = true,
    ["user talk"] = true,
    ["file talk"] = true,
    ["mediawiki talk"] = true,
    ["template talk"] = true,
    ["help"] = true,
    ["help talk"] = true,
    ["category talk"] = true,
    ["module talk"] = true,
    ["xenharmonic wiki"] = true,
    ["xenharmonic wiki talk"] = true,
    ["media"] = true,
}
-- Inversely, the following namespaces are unsuppressed: main, file, mediawiki,
-- template, category, module

-- Default list of page suffixes in which to suppress categorization.
-- Adjust as needed!
local DEFAULT_SUPPRESSED_SUFFIXES = {
	"doc",
	"sandbox",
}

-- Helper function: check if current namespace is excluded
-- Accepts an optional table, containing or overriding other namespaces' rules
local function is_suppressed_namespace(ns_override)
	-- Get current namespace, as lowercase
	local curr_ns = mw.ustring.lower(mw.title.getCurrentTitle().nsText or '')
	
	-- Build table of suppressed namespaces; start with default list
	local namespaces = {}
	for k, v in pairs(DEFAULT_SUPPRESSED_NAMESPACES) do
		namespaces[k] = v
	end

	-- Then extend/override list using ns_override, if available
	if type(ns_override) == "table" then
		for k, v in pairs(ns_override) do
			namespaces[k] = v
		end
	end

	-- Return; if no namespace found, default to false
	return namespaces[curr_ns] or false
end

-- Helper function
-- Checks whether the page title ends in a suppressed suffix
-- Accepts an opiontal table, containing additional suffixes to suppress
-- Suffix and custom suffixes are lowercased to guarantee matching
--[[
local function has_suppressed_suffix(suffixes_override)
	local title = mw.title.getCurrentTitle()
	local pagename = mw.ustring.lower(title.text)

	-- Build table of suppressed suffixes, start with default suffixes
	local suffixes = {}
	for _, suffix in ipairs(DEFAULT_SUPPRESSED_SUFFIXES) do
		table.insert(suffixes, suffix)
	end

	-- Then append additional suffixes, if available (append, not replace)
	if type(suffixes_override) == "table" then
		for _, suffix in ipairs(suffixes_override) do
			table.insert(suffixes, suffix)
		end
	end

	-- Find and match suffix
	for _, suffix in ipairs(suffixes) do
		suffix = mw.ustring.lower(mw.text.trim(suffix or ''))	-- Also normalize
		if suffix ~= '' then
			local pattern = '/' .. mw.ustring.gsub(suffix, '([%^%$%(%)%%%.%[%]%*%+%-%?])', '%%%1') .. '$'
			if mw.ustring.match(pagename, pattern) then
				return true
			end
		end
	end

	return false
end
]]--

-- "Main" function; can be called by other modules
-- Categorizes a page, given a table of categories
-- Disallows categories if it's in a suppressed namespace or the page has a
-- suppressed suffix (subpage)
function p._category_handler(cats, ns_override, suffixes, is_debug)
    local cats = cats or {}
    local is_debug = yesno(is_debug, false)

    local frame = mw.getCurrentFrame()
    -- Get the page where the template/module is being used (parent frame)
    local parent_title = frame:getParent() and mw.title.new(frame:getParent():getTitle()) or mw.title.getCurrentTitle()
    local parent_ns = parent_title.nsText

    -- Don't categorize if:
    -- - Debug mode is on (force suppress)
    -- - Parent page is in suppressed namespace
    -- - Parent page is NOT a content page (e.g. subpages like /doc, /sandbox)
    if is_debug
        or is_suppressed_namespace(ns_override, parent_ns)
        or not parent_title.isContentPage
    then
        return ''
    end

    -- Categorize
    local result = ''
    for _, cat in ipairs(cats) do
        cat = mw.text.trim(cat or '')
        if cat ~= '' then
            result = result .. string.format('[[Category:%s]]', cat)
        end
    end

    return result
end

-- Wrapper for templates calling via #invoke
function p.category_handler(frame)
	local args = frame:getParent().args
	local cats_unparsed        = args["categories" ] or ""
	local excluded_ns_unparsed = args["excluded_ns"] or ""
	--local suffixes_unparsed    = args["suffixes"   ] or ""
	local is_debug = yesno(args["debug"], false)		-- Parse debug mode; setting this to TRUE disables all categories

	-- Parse categories
	local cats = {}
	for cat in mw.text.gsplit(cats_unparsed, "[,\n]") do
		cat = mw.text.trim(cat)
		if cat ~= "" then
			table.insert(cats, cat)
		end
	end

	-- Parse excluded namespaces
	-- These are added in addition to the default list
	-- This currently can't force-allow suppressed namespaces as template input,
	-- only disallow additional namespaces
	local ns_override = {}
	for ns in mw.text.gsplit(excluded_ns_unparsed, "[;\n]") do
		ns = mw.text.trim(ns)
		if ns ~= "" then
			ns_override[ns] = true
		end
	end

	-- Parse excluded suffixes
	--[[
	local suffixes = {}
	for suffix in mw.text.gsplit(suffixes_unparsed, "[;\n]") do
		suffix = mw.text.trim(suffix)
		if suffix ~= "" then
			table.insert(suffixes, suffix)
		end
	end
	]]--

	return p._category_handler(cats, ns_override, suffixes, is_debug)
end

return p