Module:Namespace detect: Difference between revisions

From sona pona, the Toki Pona wiki
Content added Content deleted
(Created page with "-------------------------------------------------------------------------------- -- -- -- CATEGORY HANDLER -- -- -- -- This module implements the {{category handler}} template in Lua, -- -- with a few improvements: all namespaces and all namespace alia...")
 
(Wrong one, sorry)
 
Line 1: Line 1:
--[[
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- --
-- --
-- CATEGORY HANDLER --
-- NAMESPACE DETECT --
-- --
-- --
-- This module implements the {{category handler}} template in Lua, --
-- This module implements the {{namespace detect}} template in Lua, with a --
-- with a few improvements: all namespaces and all namespace aliases --
-- few improvements: all namespaces and all namespace aliases are supported, --
-- are supported, and namespace names are detected automatically for --
-- and namespace names are detected automatically for the local wiki. The --
-- the local wiki. This module requires [[Module:Namespace detect]] --
-- module can also use the corresponding subject namespace value if it is --
-- and [[Module:Yesno]] to be available on the local wiki. It can be --
-- used on a talk page. Parameter names can be configured for different wikis --
-- configured for different wikis by altering the values in --
-- by altering the values in the "cfg" table in --
-- Module:Namespace detect/config. --
-- [[Module:Category handler/config]], and pages can be blacklisted --
-- from categorisation by using [[Module:Category handler/blacklist]]. --
-- --
-- --
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--]]

local data = mw.loadData('Module:Namespace detect/data')
local argKeys = data.argKeys
local cfg = data.cfg
local mappings = data.mappings


-- Load required modules
local yesno = require('Module:Yesno')
local yesno = require('Module:Yesno')
local mArguments -- Lazily initialise Module:Arguments

local mTableTools -- Lazily initilalise Module:TableTools
-- Lazily load things we don't always need
local ustringLower = mw.ustring.lower
local mShared, mappings


local p = {}
local p = {}


local function fetchValue(t1, t2)
--------------------------------------------------------------------------------
-- Fetches a value from the table t1 for the first key in array t2 where
-- Helper functions
-- a non-nil value of t1 exists.
--------------------------------------------------------------------------------
for i, key in ipairs(t2) do

local value = t1[key]
local function trimWhitespace(s, removeBlanks)
if type(s) ~= 'string' then
if value ~= nil then
return s
return value
end
s = s:match('^%s*(.-)%s*$')
if removeBlanks then
if s ~= '' then
return s
else
return nil
end
end
else
return s
end
end
return nil
end
end


local function equalsArrayValue(t, value)
--------------------------------------------------------------------------------
-- Returns true if value equals a value in the array t. Otherwise
-- CategoryHandler class
-- returns false.
--------------------------------------------------------------------------------
for i, arrayValue in ipairs(t) do

if value == arrayValue then
local CategoryHandler = {}
return true
CategoryHandler.__index = CategoryHandler

function CategoryHandler.new(data, args)
local obj = setmetatable({ _data = data, _args = args }, CategoryHandler)
-- Set the title object
do
local pagename = obj:parameter('demopage')
local success, titleObj
if pagename then
success, titleObj = pcall(mw.title.new, pagename)
end
if success and titleObj then
obj.title = titleObj
if titleObj == mw.title.getCurrentTitle() then
obj._usesCurrentTitle = true
end
else
obj.title = mw.title.getCurrentTitle()
obj._usesCurrentTitle = true
end
end
end
end
return false

-- Set suppression parameter values
for _, key in ipairs{'nocat', 'categories'} do
local value = obj:parameter(key)
value = trimWhitespace(value, true)
obj['_' .. key] = yesno(value)
end
do
local subpage = obj:parameter('subpage')
local category2 = obj:parameter('category2')
if type(subpage) == 'string' then
subpage = mw.ustring.lower(subpage)
end
if type(category2) == 'string' then
subpage = mw.ustring.lower(category2)
end
obj._subpage = trimWhitespace(subpage, true)
obj._category2 = trimWhitespace(category2) -- don't remove blank values
end
return obj
end
end


function CategoryHandler:parameter(key)
function p.getPageObject(page)
-- Get the page object, passing the function through pcall in case of
local parameterNames = self._data.parameters[key]
-- errors, e.g. being over the expensive function count limit.
local pntype = type(parameterNames)
if page then
if pntype == 'string' or pntype == 'number' then
local success, pageObject = pcall(mw.title.new, page)
return self._args[parameterNames]
if success then
elseif pntype == 'table' then
return pageObject
for _, name in ipairs(parameterNames) do
else
local value = self._args[name]
if value ~= nil then
return nil
return value
end
end
end
return nil
else
else
return mw.title.getCurrentTitle()
error(string.format(
'invalid config key "%s"',
tostring(key)
), 2)
end
end
end
end


-- Provided for backward compatibility with other modules
function CategoryHandler:isSuppressedByArguments()
function p.getParamMappings()
return
return mappings
-- See if a category suppression argument has been set.
self._nocat == true
or self._categories == false
or (
self._category2
and self._category2 ~= self._data.category2Yes
and self._category2 ~= self._data.category2Negative
)

-- Check whether we are on a subpage, and see if categories are
-- suppressed based on our subpage status.
or self._subpage == self._data.subpageNo and self.title.isSubpage
or self._subpage == self._data.subpageOnly and not self.title.isSubpage
end
end


local function getNamespace(args)
function CategoryHandler:shouldSkipBlacklistCheck()
-- This function gets the namespace name from the page object.
-- Check whether the category suppression arguments indicate we
local page = fetchValue(args, argKeys.demopage)
-- should skip the blacklist check.
if page == '' then
return self._nocat == false
page = nil
or self._categories == true
or self._category2 == self._data.category2Yes
end

function CategoryHandler:matchesBlacklist()
if self._usesCurrentTitle then
return self._data.currentTitleMatchesBlacklist
else
mShared = mShared or require('Module:Category handler/shared')
return mShared.matchesBlacklist(
self.title.prefixedText,
mw.loadData('Module:Category handler/blacklist')
)
end
end
local demospace = fetchValue(args, argKeys.demospace)
end
if demospace == '' then

demospace = nil
function CategoryHandler:isSuppressed()
end
-- Find if categories are suppressed by either the arguments or by
local subjectns = fetchValue(args, argKeys.subjectns)
-- matching the blacklist.
local ret
return self:isSuppressedByArguments()
if demospace then
or not self:shouldSkipBlacklistCheck() and self:matchesBlacklist()
-- Handle "demospace = main" properly.
end
if equalsArrayValue(argKeys.main, ustringLower(demospace)) then

ret = mw.site.namespaces[0].name
function CategoryHandler:getNamespaceParameters()
else
if self._usesCurrentTitle then
ret = demospace
return self._data.currentTitleNamespaceParameters
end
else
else
local pageObject = p.getPageObject(page)
if not mappings then
if pageObject then
mShared = mShared or require('Module:Category handler/shared')
if pageObject.isTalkPage then
mappings = mShared.getParamMappings(true) -- gets mappings with mw.loadData
-- Get the subject namespace if the option is set,
-- otherwise use "talk".
if yesno(subjectns) then
ret = mw.site.namespaces[pageObject.namespace].subject.name
else
ret = 'talk'
end
else
ret = pageObject.nsText
end
else
return nil -- return nil if the page object doesn't exist.
end
end
return mShared.getNamespaceParameters(
self.title,
mappings
)
end
end
ret = ret:gsub('_', ' ')
return ustringLower(ret)
end
end


function p._main(args)
function CategoryHandler:namespaceParametersExist()
-- Check the parameters stored in the mappings table for any matches.
-- Find whether any namespace parameters have been specified.
local namespace = getNamespace(args) or 'other' -- "other" avoids nil table keys
-- We use the order "all" --> namespace params --> "other" as this is what
local params = mappings[namespace] or {}
-- the old template did.
local ret = fetchValue(args, params)
if self:parameter('all') then
--[[
return true
-- If there were no matches, return parameters for other namespaces.
-- This happens if there was no text specified for the namespace that
-- was detected or if the demospace parameter is not a valid
-- namespace. Note that the parameter for the detected namespace must be
-- completely absent for this to happen, not merely blank.
--]]
if ret == nil then
ret = fetchValue(args, argKeys.other)
end
end
return ret
if not mappings then
mShared = mShared or require('Module:Category handler/shared')
mappings = mShared.getParamMappings(true) -- gets mappings with mw.loadData
end
for ns, params in pairs(mappings) do
for i, param in ipairs(params) do
if self._args[param] then
return true
end
end
end
if self:parameter('other') then
return true
end
return false
end
end


function CategoryHandler:getCategories()
function p.main(frame)
mArguments = require('Module:Arguments')
local params = self:getNamespaceParameters()
local args = mArguments.getArgs(frame, {removeBlanks = false})
local nsCategory
local ret = p._main(args)
for i, param in ipairs(params) do
return ret or ''
local value = self._args[param]
end
if value ~= nil then

nsCategory = value
function p.table(frame)
break
--[[
end
-- Create a wikitable of all subject namespace parameters, for
end
-- documentation purposes. The talk parameter is optional, in case it
if nsCategory ~= nil or self:namespaceParametersExist() then
-- needs to be excluded in the documentation.
-- Namespace parameters exist - advanced usage.
--]]
if nsCategory == nil then
nsCategory = self:parameter('other')
-- Load modules and initialise variables.
end
mTableTools = require('Module:TableTools')
local ret = {self:parameter('all')}
local numParam = tonumber(nsCategory)
local namespaces = mw.site.namespaces
local cfg = data.cfg
if numParam and numParam >= 1 and math.floor(numParam) == numParam then
local useTalk = type(frame) == 'table'
-- nsCategory is an integer
and type(frame.args) == 'table'
ret[#ret + 1] = self._args[numParam]
and yesno(frame.args.talk) -- Whether to use the talk parameter.
-- Get the header names.
local function checkValue(value, default)
if type(value) == 'string' then
return value
else
else
return default
ret[#ret + 1] = nsCategory
end
end
if #ret < 1 then
return nil
else
return table.concat(ret)
end
elseif self._data.defaultNamespaces[self.title.namespace] then
-- Namespace parameters don't exist, simple usage.
return self._args[1]
end
end
local nsHeader = checkValue(cfg.wikitableNamespaceHeader, 'Namespace')
return nil
local aliasesHeader = checkValue(cfg.wikitableAliasesHeader, 'Aliases')
end


-- Put the namespaces in order.
--------------------------------------------------------------------------------
local mappingsOrdered = {}
-- Exports
for nsname, params in pairs(mappings) do
--------------------------------------------------------------------------------
if useTalk or nsname ~= 'talk' then

local p = {}
local nsid = namespaces[nsname].id
-- Add 1, as the array must start with 1; nsid 0 would be lost otherwise.

nsid = nsid + 1
function p._exportClasses()
mappingsOrdered[nsid] = params
-- Used for testing purposes.
end
return {
CategoryHandler = CategoryHandler
}
end

function p._main(args, data)
data = data or mw.loadData('Module:Category handler/data')
local handler = CategoryHandler.new(data, args)
if handler:isSuppressed() then
return nil
end
end
mappingsOrdered = mTableTools.compressSparseArray(mappingsOrdered)
return handler:getCategories()
end


-- Build the table.
function p.main(frame, data)
local ret = '{| class="wikitable"'
data = data or mw.loadData('Module:Category handler/data')
.. '\n|-'
local args = require('Module:Arguments').getArgs(frame, {
.. '\n! ' .. nsHeader
wrappers = data.wrappers,
.. '\n! ' .. aliasesHeader
valueFunc = function (k, v)
for i, params in ipairs(mappingsOrdered) do
v = trimWhitespace(v)
for j, param in ipairs(params) do
if type(k) == 'number' then
if v ~= '' then
if j == 1 then
ret = ret .. '\n|-'
return v
.. '\n| <code>' .. param .. '</code>'
else
return nil
.. '\n| '
elseif j == 2 then
end
ret = ret .. '<code>' .. param .. '</code>'
else
else
ret = ret .. ', <code>' .. param .. '</code>'
return v
end
end
end
end
})
end
ret = ret .. '\n|-'
return p._main(args, data)
.. '\n|}'
return ret
end
end



Latest revision as of 15:34, 30 May 2024

Documentation for this module may be created at Module:Namespace detect/doc

--[[
--------------------------------------------------------------------------------
--                                                                            --
--                            NAMESPACE DETECT                                --
--                                                                            --
-- This module implements the {{namespace detect}} template in Lua, with a    --
-- few improvements: all namespaces and all namespace aliases are supported,  --
-- and namespace names are detected automatically for the local wiki. The     --
-- module can also use the corresponding subject namespace value if it is     --
-- used on a talk page. Parameter names can be configured for different wikis --
-- by altering the values in the "cfg" table in                               --
-- Module:Namespace detect/config.                                            --
--                                                                            --
--------------------------------------------------------------------------------
--]]

local data = mw.loadData('Module:Namespace detect/data')
local argKeys = data.argKeys
local cfg = data.cfg
local mappings = data.mappings

local yesno = require('Module:Yesno')
local mArguments -- Lazily initialise Module:Arguments
local mTableTools -- Lazily initilalise Module:TableTools
local ustringLower = mw.ustring.lower

local p = {}

local function fetchValue(t1, t2)
	-- Fetches a value from the table t1 for the first key in array t2 where
	-- a non-nil value of t1 exists.
	for i, key in ipairs(t2) do
		local value = t1[key]
		if value ~= nil then
			return value
		end
	end
	return nil
end

local function equalsArrayValue(t, value)
	-- Returns true if value equals a value in the array t. Otherwise
	-- returns false.
	for i, arrayValue in ipairs(t) do
		if value == arrayValue then
			return true
		end
	end
	return false
end

function p.getPageObject(page)
	-- Get the page object, passing the function through pcall in case of
	-- errors, e.g. being over the expensive function count limit.
	if page then
		local success, pageObject = pcall(mw.title.new, page)
		if success then
			return pageObject
		else
			return nil
		end
	else
		return mw.title.getCurrentTitle()
	end
end

-- Provided for backward compatibility with other modules
function p.getParamMappings()
	return mappings
end

local function getNamespace(args)
	-- This function gets the namespace name from the page object.
	local page = fetchValue(args, argKeys.demopage)
	if page == '' then
		page = nil
	end
	local demospace = fetchValue(args, argKeys.demospace)
	if demospace == '' then
		demospace = nil
	end
	local subjectns = fetchValue(args, argKeys.subjectns)
	local ret
	if demospace then
		-- Handle "demospace = main" properly.
		if equalsArrayValue(argKeys.main, ustringLower(demospace)) then
			ret = mw.site.namespaces[0].name
		else
			ret = demospace
		end
	else
		local pageObject = p.getPageObject(page)
		if pageObject then
			if pageObject.isTalkPage then
				-- Get the subject namespace if the option is set,
				-- otherwise use "talk".
				if yesno(subjectns) then
					ret = mw.site.namespaces[pageObject.namespace].subject.name
				else
					ret = 'talk'
				end
			else
				ret = pageObject.nsText
			end
		else
			return nil -- return nil if the page object doesn't exist.
		end
	end
	ret = ret:gsub('_', ' ')
	return ustringLower(ret)
end

function p._main(args)
	-- Check the parameters stored in the mappings table for any matches.
	local namespace = getNamespace(args) or 'other' -- "other" avoids nil table keys
	local params = mappings[namespace] or {}
	local ret = fetchValue(args, params)
	--[[
	-- If there were no matches, return parameters for other namespaces.
	-- This happens if there was no text specified for the namespace that
	-- was detected or if the demospace parameter is not a valid
	-- namespace. Note that the parameter for the detected namespace must be
	-- completely absent for this to happen, not merely blank.
	--]]
	if ret == nil then
		ret = fetchValue(args, argKeys.other)
	end
	return ret
end

function p.main(frame)
	mArguments = require('Module:Arguments')
	local args = mArguments.getArgs(frame, {removeBlanks = false})
	local ret = p._main(args)
	return ret or ''
end

function p.table(frame)
	--[[
	-- Create a wikitable of all subject namespace parameters, for
	-- documentation purposes. The talk parameter is optional, in case it
	-- needs to be excluded in the documentation.
	--]]
	
	-- Load modules and initialise variables.
	mTableTools = require('Module:TableTools')
	local namespaces = mw.site.namespaces
	local cfg = data.cfg
	local useTalk = type(frame) == 'table' 
		and type(frame.args) == 'table' 
		and yesno(frame.args.talk) -- Whether to use the talk parameter.
	
	-- Get the header names.
	local function checkValue(value, default)
		if type(value) == 'string' then
			return value
		else
			return default
		end
	end
	local nsHeader = checkValue(cfg.wikitableNamespaceHeader, 'Namespace')
	local aliasesHeader = checkValue(cfg.wikitableAliasesHeader, 'Aliases')

	-- Put the namespaces in order.
	local mappingsOrdered = {}
	for nsname, params in pairs(mappings) do
		if useTalk or nsname ~= 'talk' then
			local nsid = namespaces[nsname].id
			-- Add 1, as the array must start with 1; nsid 0 would be lost otherwise.
			nsid = nsid + 1 
			mappingsOrdered[nsid] = params
		end
	end
	mappingsOrdered = mTableTools.compressSparseArray(mappingsOrdered)

	-- Build the table.
	local ret = '{| class="wikitable"'
		.. '\n|-'
		.. '\n! ' .. nsHeader
		.. '\n! ' .. aliasesHeader
	for i, params in ipairs(mappingsOrdered) do
		for j, param in ipairs(params) do
			if j == 1 then
				ret = ret .. '\n|-'
					.. '\n| <code>' .. param .. '</code>'
					.. '\n| '
			elseif j == 2 then
				ret = ret .. '<code>' .. param .. '</code>'
			else
				ret = ret .. ', <code>' .. param .. '</code>'
			end
		end
	end
	ret = ret .. '\n|-'
		.. '\n|}'
	return ret
end

return p