Module:Namespace detect/data

Revision as of 06:41, 22 March 2014 by en>Mr. Stradivarius (add a getArgKeys function, so that we can have multiple keys for each argument (helpful for localisation) and so that we only have to create that table once per page)
Jump to navigation Jump to search

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

--------------------------------------------------------------------------------
--                          Namespace detect data                             --
-- This module holds data for [[Module:Namespace detect]] to be loaded per    --
-- page, rather than per #invoke, for performance reasons.                    --
--------------------------------------------------------------------------------

local cfg = require('Module:Namespace detect/config')

local function addKey(t, key, defaultKey)
	if key ~= defaultKey then
		t[#t + 1] = key
	end
end

local function getArgKeys()
	-- Returns a table of parameters to query for each default parameter name.
	-- This allows wikis to customise parameter names in the cfg table while
	-- ensuring that default parameter names will always work. The cfg table
	-- values can be added as a string, or as an array of strings.
	local argKeys = {
		main = {'main'},
		talk = {'talk'},
		other = {'other'},
		subjectns = {'subjectns'},
		demospace = {'demospace'},
		page = {'page'}
	}
	for defaultKey, t in pairs(argKeys) do
		local cfgValue = cfg[defaultKey]
		local cfgValueType = type(cfgValue)
		if cfgValueType == 'string' then
			addKey(t, cfgValue, defaultKey)
		elseif cfgValueType == 'table' then
			for i, key in ipairs(cfgValue) do
				addKey(t, key, defaultKey)
			end
		end
		cfg[defaultKey] = nil -- Free the cfg value as we don't need it any more.
	end
	return argKeys
end

local function getParamMappings()
	--[[
	-- Returns a table of how parameter names map to namespace names. 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'},
	--   ...
	-- }
	--]]
	local ustringLower = mw.ustring.lower
	local tinsert = table.insert
	local subjectNamespaces = mw.site.subjectNamespaces
	local talk = cfg.talk
	local mappings = {}
	mappings[ustringLower(subjectNamespaces[0].name)] = {cfg.main}
	mappings[talk] = {talk}
	for nsid, ns in pairs(subjectNamespaces) do
		if nsid ~= 0 then -- Exclude main namespace.
			local nsname = ustringLower(ns.name)
			local canonicalName = ustringLower(ns.canonicalName)
			mappings[nsname] = {nsname}
			if canonicalName ~= nsname then
				tinsert(mappings[nsname], canonicalName)
			end
			for _, alias in ipairs(ns.aliases) do
				tinsert(mappings[nsname], ustringLower(alias))
			end
		end
	end
	return mappings
end

return {
	argKeys = getArgKeys(),
	cfg = cfg,
	mappings = getParamMappings()
}