Difference between revisions of "Module:Namespace detect/sandbox"

From blackwiki
Jump to navigation Jump to search
blackwiki>Mr. Stradivarius
(sync)
m (29 revisions imported)
 
(23 intermediate revisions by 3 users not shown)
Line 1: Line 1:
----------------------------------------------------------------------
+
--[[
--                                                                 --
+
--------------------------------------------------------------------------------
--                       NAMESPACE DETECT                         --
+
--                                                                           --
--                                                                 --
+
--                           NAMESPACE DETECT                               --
--     This module implements the {{namespace detect}} template    --
+
--                                                                           --
--     in Lua, with a few improvements: all namespaces and all     --
+
-- This module implements the {{namespace detect}} template in Lua, with a   --
--      namespace aliases are supported, and namespace names are    --
+
-- few improvements: all namespaces and all namespace aliases are supported, --
--     detected automatically for the local wiki. Function names  --
+
-- and namespace names are detected automatically for the local wiki. The    --
--     can be configured for different wikis by altering the      --
+
-- module can also use the corresponding subject namespace value if it is    --
--     values in the "cfg" table.                                 --
+
-- 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')
--                      Configuration data                         --
+
local argKeys = data.argKeys
--      Language-specific parameter names can be set here.         --
+
local cfg = data.cfg
----------------------------------------------------------------------
+
local mappings = data.mappings
  
local cfg = {}
+
local yesno = require('Module:Yesno')
 +
local mArguments -- Lazily initialise Module:Arguments
 +
local mTableTools -- Lazily initilalise Module:TableTools
 +
local ustringLower = mw.ustring.lower
  
-- The name for the parameter to display content for the main namespace:
+
local p = {}
cfg.main = 'main'
 
  
-- The name for the parameter to display content in talk namespaces:
+
local function fetchValue(t1, t2)
cfg.talk = 'talk'
+
-- 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
  
-- The name for the parameter to display content for "other" namespaces
+
local function equalsArrayValue(t, value)
-- (namespaces for which parameters have not been specified, or for when
+
-- Returns true if value equals a value in the array t. Otherwise
-- cfg.demospace is set to cfg.other):
+
-- returns false.
cfg.other = 'other'
+
for i, arrayValue in ipairs(t) do
 
+
if value == arrayValue then
-- The name for the parameter to set a demonstration namespace:
+
return true
cfg.demospace = 'demospace'
+
end
 
+
end
-- The name for the parameter to set a specific page to compare:
+
return false
cfg.page = 'page'
+
end
 
 
-- The header for the namespace column in the wikitable containing the
 
-- list of possible subject-space parameters.
 
cfg.wikitableNamespaceHeader = 'Namespace'
 
 
 
-- The header for the wikitable containing the list of possible
 
-- subject-space parameters.
 
cfg.wikitableAliasesHeader = 'Aliases'
 
  
----------------------------------------------------------------------
+
function p.getPageObject(page)
--                    End configuration data                      --
+
-- 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)
--                        Global functions                          --
+
if success then
--      The following functions are global, because we want them    --
+
return pageObject
--      to be accessible from other Lua modules called using        --
+
else
--      require().                                                  --
+
return nil
----------------------------------------------------------------------
+
end
 
+
else
-- Declare the table of functions to return.
+
return mw.title.getCurrentTitle()
local p = {}
+
end
 
 
-- Get the page object. This will return the page object for the page
 
-- specified, or nil if there are errors in the title or if the
 
-- expensive function count has been exceeded.
 
function p.getPageObject( page )
 
    -- Get the title object for args.page if it is specified. Otherwise
 
    -- get the title object for the current page.
 
    if page then
 
        -- Get the page object, passing the function through pcall  
 
        -- in case we are over the expensive function count limit.
 
        local noError, pageObject = pcall(mw.title.new, page)
 
        if not noError then
 
            return nil
 
        else
 
            return pageObject
 
        end
 
    else
 
        return mw.title.getCurrentTitle()
 
    end  
 
 
end
 
end
  
--[[ Returns a table of how parameter names map to namespace names.
+
-- Provided for backward compatibility with other modules
The keys are the actual namespace names, in lower case, and the
 
values are the possible parameter names for that namespace, also
 
in lower case. The table entries are structured like this:
 
    [''] = {
 
        {'main'},
 
    },
 
    ['wikipedia'] = {
 
        {'wikipedia', 'project', 'wp' }
 
    }
 
]]
 
 
function p.getParamMappings()
 
function p.getParamMappings()
    local mappings = {}
+
return mappings
    mappings[mw.ustring.lower( mw.site.namespaces[0].name )] = { cfg.main }
 
    mappings[cfg.talk] = { cfg.talk }
 
    for nsid, ns in pairs( mw.site.subjectNamespaces ) do
 
        if nsid ~= 0 then -- Exclude main namespace.
 
            local nsname = mw.ustring.lower( ns.name )
 
            local canonicalName = mw.ustring.lower( ns.canonicalName )
 
            mappings[nsname] = { nsname }
 
            if canonicalName ~= nsname then
 
                table.insert( mappings[nsname], canonicalName )
 
            end
 
            for _, alias in ipairs( ns.aliases ) do
 
                table.insert( mappings[nsname], mw.ustring.lower( alias ) )
 
            end
 
        end
 
    end
 
    return mappings
 
 
end
 
end
  
--[[ Create a wikitable of all subject namespace parameters, for documentation
+
local function getNamespace(args)
  purposes. Talk is excluded, as it should usually be treated separately in
+
-- This function gets the namespace name from the page object.
  the documentation.
+
local page = fetchValue(args, argKeys.demopage)
]]
+
if page == '' then
function p.table()
+
page = nil
    -- Get the parameter mappings.
+
end
    local mappings = p.getParamMappings()
+
local demospace = fetchValue(args, argKeys.demospace)
   
+
if demospace == '' then
    -- Start the wikitable.
+
demospace = nil
    local ret = '{| class="wikitable"'
+
end
        .. '\n|-'
+
local subjectns = fetchValue(args, argKeys.subjectns)
        .. '\n! ' .. cfg.wikitableNamespaceHeader
+
local ret
        .. '\n! ' .. cfg.wikitableAliasesHeader
+
if demospace then
   
+
-- Handle "demospace = main" properly.
    -- Generate the row for the main namespace, as we want this
+
if equalsArrayValue(argKeys.main, ustringLower(demospace)) then
    -- to be first in the list.
+
ret = mw.site.namespaces[0].name
    ret = ret .. '\n|-'
+
else
        .. '\n| <code>' .. cfg.main .. '</code>'
+
ret = demospace
        .. '\n|'
+
end
       
+
else
    -- Enclose all parameter names in <code> tags.
+
local pageObject = p.getPageObject(page)
    for ns, params in pairs( mappings ) do
+
if pageObject then
        if ns ~= mw.site.namespaces[0].name then
+
if pageObject.isTalkPage then
            for i, param in ipairs( params ) do
+
-- Get the subject namespace if the option is set,
                mappings[ns][i] = '<code>' .. param .. '</code>'
+
-- otherwise use "talk".
            end
+
if yesno(subjectns) then
        end
+
ret = mw.site.namespaces[pageObject.namespace].subject.name
    end
+
else
   
+
ret = 'talk'
    -- Generate the other wikitable rows.
+
end
    for ns, params in pairs( mappings ) do
+
else
        if ns ~= mw.site.namespaces[0].name then -- Ignore the main namespace.
+
ret = pageObject.nsText
            ret = ret .. '\n|-'
+
end
                .. '\n| ' .. params[1]
+
else
                .. '\n| ' .. table.concat( params, ', ', 2 )
+
return nil -- return nil if the page object doesn't exist.
        end
+
end
    end
+
end
   
+
ret = ret:gsub('_', ' ')
    -- End the wikitable.
+
return ustringLower(ret)
    ret = ret .. '\n|-'
 
        .. '\n|}'
 
   
 
    return ret
 
 
end
 
end
  
----------------------------------------------------------------------
+
function p._main(args)
--                         Local functions                          --
+
-- Check the parameters stored in the mappings table for any matches.
--     The following are internal functions, which we do not want  --
+
local namespace = getNamespace(args) or 'other' -- "other" avoids nil table keys
--      to be accessible from other modules.                        --
+
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
  
-- Gets the namespace name to compare to the arguments. The returned value
+
function p.main(frame)
-- is lower-case.
+
mArguments = require('Module:Arguments')
local function getNamespace( page, demospace )
+
local args = mArguments.getArgs(frame, {removeBlanks = false})
    local ret
+
local ret = p._main(args)
    if demospace then
+
return ret or ''
        -- Handle "demospace = main" properly.
 
        if mw.ustring.lower( demospace ) == cfg.main then
 
            ret = mw.site.namespaces[0].name
 
        else
 
            ret = demospace
 
        end
 
    else
 
        local pageObject = p.getPageObject( page )
 
        if pageObject then
 
            if pageObject.isTalkPage then
 
                -- {{namespace detect}} uses the same value for all talk
 
                -- namespaces, so that's what the module should do too.
 
                ret = cfg.talk
 
            else
 
                ret = pageObject.nsText
 
            end
 
        else
 
            return nil -- return nil if the page object doesn't exist.
 
        end
 
    end
 
    return mw.ustring.lower(ret)
 
 
end
 
end
  
-- Compare the namespace found with the parameters that have been
+
function p.table(frame)
-- specified, and return content of the appropriate parameter.
+
--[[
local function compare( args )
+
-- Create a wikitable of all subject namespace parameters, for
    -- Get the namespace to compare the parameters to, and the parameter
+
-- documentation purposes. The talk parameter is optional, in case it
    -- mapping table.
+
-- needs to be excluded in the documentation.
    local namespace = getNamespace( args[cfg.page], args[cfg.demospace] )
+
--]]
    local mappings = p.getParamMappings()
+
   
+
-- Load modules and initialise variables.
    -- Check for any matches in the namespace arguments. The order we check
+
mTableTools = require('Module:TableTools')
    -- them doesn't matter, as there can only be one match.
+
local namespaces = mw.site.namespaces
    for ns, params in pairs( mappings ) do
+
local cfg = data.cfg
        if ns == namespace then
+
local useTalk = type(frame) == 'table'  
            -- Check all aliases for matches. The default local namespace is
+
and type(frame.args) == 'table'
            -- checked first, as {{namespace detect}} checked these before
+
and yesno(frame.args.talk) -- Whether to use the talk parameter.
            -- alias names.
+
            for _, param in ipairs( params ) do
+
-- Get the header names.
                if args[param] then
+
local function checkValue(value, default)
                    return args[param]
+
if type(value) == 'string' then
                end
+
return value
            end
+
else
        end
+
return default
    end
+
end
   
+
end
    -- If there were no matches, return parameters for other namespaces.  
+
local nsHeader = checkValue(cfg.wikitableNamespaceHeader, 'Namespace')
    -- This happens if there was no text specified for the namespace that
+
local aliasesHeader = checkValue(cfg.wikitableAliasesHeader, 'Aliases')
    -- 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 args[cfg.other] then
 
        return args[cfg.other]
 
    end
 
end
 
  
----------------------------------------------------------------------
+
-- Put the namespaces in order.
--                            Main function                        --
+
local mappingsOrdered = {}
--      This is the function that will be most used. It processes  --
+
for nsname, params in pairs(mappings) do
--      the arguments and calls the compare() function. It is      --
+
if useTalk or nsname ~= 'talk' then
--     global, but is put down here as it depends on the other    --
+
local nsid = namespaces[nsname].id
--      local in order for it to work.                             --
+
-- 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)
  
function p.main(frame)
+
-- Build the table.
    -- If called via #invoke, use the args passed into the invoking
+
local ret = '{| class="wikitable"'
    -- template, or the args passed to #invoke if any exist. Otherwise
+
.. '\n|-'
    -- assume args are being passed directly in.
+
.. '\n! ' .. nsHeader
    local origArgs
+
.. '\n! ' .. aliasesHeader
    if frame == mw.getCurrentFrame() then
+
for i, params in ipairs(mappingsOrdered) do
        origArgs = frame:getParent().args
+
for j, param in ipairs(params) do
        for k, v in pairs( frame.args ) do
+
if j == 1 then
            origArgs = frame.args
+
ret = ret .. '\n|-'
            break
+
.. '\n| <code>' .. param .. '</code>'
        end
+
.. '\n| '
    else
+
elseif j == 2 then
        origArgs = frame
+
ret = ret .. '<code>' .. param .. '</code>'
    end
+
else
   
+
ret = ret .. ', <code>' .. param .. '</code>'
    -- Trim whitespace and remove blank arguments for demospace and
+
end
    -- page parameters.
+
end
    local args = {}
+
end
    for k, v in pairs(origArgs) do
+
ret = ret .. '\n|-'
        v = mw.text.trim(v) -- Trim whitespace.
+
.. '\n|}'
        if k == cfg.demospace or k == cfg.page then
+
return ret
            if v ~= '' then
 
                args[k] = v
 
            end
 
        else
 
            args[k] = v
 
        end
 
    end
 
   
 
    return compare(args)
 
 
end
 
end
  
 
return p
 
return p

Latest revision as of 08:05, 27 September 2020

Documentation for this module may be created at Module:Namespace detect/sandbox/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