Difference between revisions of "Module:Category handler"

From BESA® Wiki
Jump to: navigation, search
(allow invocations specifying the page parameter to use the mw.loadData optimisations, and don't call mw.title.new every time)
 
(start a replacement for Template:Category handler)
(17 intermediate revisions by 2 users not shown)
Line 1: Line 1:
--------------------------------------------------------------------------------
+
local basepageSubpage = require('Module:Basepage subpage').main
--                                                                            --
+
--                              CATEGORY HANDLER                              --
+
--                                                                            --
+
--      This module implements the {{category handler}} 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. This module requires [[Module:Namespace detect]]      --
+
--      and [[Module:Yesno]] to be available on the local wiki. It can be    --
+
--      configured for different wikis by altering the values in              --
+
--      [[Module:Category handler/config]], and pages can be blacklisted      --
+
--      from categorisation by using [[Module:Category handler/blacklist]].   --
+
--                                                                            --
+
--------------------------------------------------------------------------------
+
  
-- Load required modules
+
-- Configuration data.
local yesno = require('Module:Yesno')
+
local cfg = {}
  
-- Lazily load things we don't always need
+
cfg.nocat = 'nocat'   
local mShared, mappings
+
cfg.categories = 'categories'
 +
cfg.subpage = 'subpage'
 +
cfg.page = 'page'
 +
cfg.category2 = 'category2'
 +
cfg.all = 'all'
 +
cfg.main = 'main'
 +
cfg.other = 'other'
  
 +
-- Module start.
 
local p = {}
 
local p = {}
 +
local args = {}
  
--------------------------------------------------------------------------------
+
-- Get the page object. This will return the page object for the page
-- Helper functions
+
-- specified, or nil if there are errors in the title or if the
--------------------------------------------------------------------------------
+
-- expensive function count has been exceeded.
 
+
local function getPageObject()
local function trimWhitespace(s, removeBlanks)
+
    -- Get the title object for args.page if it is specified. Otherwise
if type(s) ~= 'string' then
+
    -- get the title object for the current page.
return s
+
    if args[cfg.page] then
end
+
        -- Get the page object, passing the function through pcall
s = s:match('^%s*(.-)%s*$')
+
        -- in case we are over the expensive function count limit.
if removeBlanks then
+
        local noError, pageObject = pcall(mw.title.new, args[cfg.page])
if s ~= '' then
+
        if not noError then
return s
+
            return nil
else
+
        else
return nil
+
            return pageObject
end
+
        end
else
+
    else
return s
+
        return mw.title.getCurrentTitle()
end
+
    end  
 
end
 
end
  
--------------------------------------------------------------------------------
+
-- Find whether we need to return a category or not.
-- CategoryHandler class
+
local function needsCategory( pageObject )
--------------------------------------------------------------------------------
+
    if not pageObject then return end
 
+
    if args[cfg.nocat] == 'true'
local CategoryHandler = {}
+
        or ( args[cfg.category2] and args[cfg.category2] ~= 'yes' )
CategoryHandler.__index = CategoryHandler
+
        or ( args[cfg.subpage] == 'no' and pageObject.isSubpage )
 
+
        or ( args[cfg.subpage] == 'only' and not pageObject.isSubpage ) then
function CategoryHandler.new(data, args)
+
        return false
local obj = setmetatable({ _data = data, _args = args }, CategoryHandler)
+
    else
+
        return true
-- Set the title object
+
    end
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
+
 
+
-- 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)
+
-- Find whether we need to check the blacklist or not.
local parameterNames = self._data.parameters[key]
+
local function needsBlacklistCheck()
local pntype = type(parameterNames)
+
    if args[cfg.nocat] == 'false'
if pntype == 'string' or pntype == 'number' then
+
        or args[cfg.categories] == 'yes'
return self._args[parameterNames]
+
        or args[cfg.category2] == 'yes' then
elseif pntype == 'table' then
+
        return false
for _, name in ipairs(parameterNames) do
+
    else
local value = self._args[name]
+
        return true
if value ~= nil then
+
    end
return value
+
end
+
end
+
return nil
+
else
+
error(string.format(
+
'invalid config key "%s"',
+
tostring(key)
+
), 2)
+
end
+
 
end
 
end
  
function CategoryHandler:isSuppressedByArguments()
+
local function _main()
return
+
    local pageObject = getPageObject()
-- See if a category suppression argument has been set.
+
    if not needsCategory( pageObject ) then return end
self._nocat == true
+
   
or self._categories == false
+
    return needsBlacklistCheck()
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
  
function CategoryHandler:shouldSkipBlacklistCheck()
+
-- Process the arguments.
-- Check whether the category suppression arguments indicate we
+
function p.main(frame)
-- should skip the blacklist check.
+
    -- If called via #invoke, use the args passed into the invoking
return self._nocat == false
+
    -- template, or the args passed to #invoke if any exist. Otherwise
or self._categories == true
+
    -- assume args are being passed directly in.
or self._category2 == self._data.category2Yes
+
    local origArgs
end
+
    if frame == mw.getCurrentFrame() then
 
+
        origArgs = frame:getParent().args
function CategoryHandler:matchesBlacklist()
+
        for k, v in pairs( frame.args ) do
if self._usesCurrentTitle then
+
            origArgs = frame.args
return self._data.currentTitleMatchesBlacklist
+
            break
else
+
        end
mShared = mShared or require('Module:Category handler/shared')
+
    else
return mShared.matchesBlacklist(
+
        origArgs = frame
self.title.prefixedText,
+
    end
mw.loadData('Module:Category handler/blacklist')
+
   
)
+
    -- The following don't need blank values preserved:
end
+
    -- nocat
end
+
    -- categories
 
+
    -- subpage
function CategoryHandler:isSuppressed()
+
    -- page
-- Find if categories are suppressed by either the arguments or by
+
    -- positional parameters (1-10)
-- matching the blacklist.
+
   
return self:isSuppressedByArguments()
+
    -- The following *do* need blank values preserved
or not self:shouldSkipBlacklistCheck() and self:matchesBlacklist()
+
    -- category2
end
+
    -- all
 
+
    -- other
function CategoryHandler:getNamespaceParameters()
+
    -- main
if self._usesCurrentTitle then
+
    -- all the namespace parameters
return self._data.currentTitleNamespaceParameters
+
else
+
if not mappings then
+
mShared = mShared or require('Module:Category handler/shared')
+
mappings = mShared.getParamMappings(true) -- gets mappings with mw.loadData
+
end
+
return mShared.getNamespaceParameters(
+
self.title,
+
mappings
+
)
+
end
+
end
+
 
+
function CategoryHandler:namespaceParametersExist()
+
-- Find whether any namespace parameters have been specified.
+
-- We use the order "all" --> namespace params --> "other" as this is what
+
-- the old template did.
+
if self:parameter('all') then
+
return true
+
end
+
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
+
 
+
function CategoryHandler:getCategories()
+
local params = self:getNamespaceParameters()
+
local nsCategory
+
for i, param in ipairs(params) do
+
local value = self._args[param]
+
if value ~= nil then
+
nsCategory = value
+
break
+
end
+
end
+
if nsCategory ~= nil or self:namespaceParametersExist() then
+
-- Namespace parameters exist - advanced usage.
+
if nsCategory == nil then
+
nsCategory = self:parameter('other')
+
end
+
local ret = {self:parameter('all')}
+
local numParam = tonumber(nsCategory)
+
if numParam and numParam >= 1 and math.floor(numParam) == numParam then
+
-- nsCategory is an integer
+
ret[#ret + 1] = self._args[numParam]
+
else
+
ret[#ret + 1] = nsCategory
+
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
+
return nil
+
end
+
 
+
--------------------------------------------------------------------------------
+
-- Exports
+
--------------------------------------------------------------------------------
+
 
+
local p = {}
+
 
+
function p._exportClasses()
+
-- Used for testing purposes.
+
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
+
return handler:getCategories()
+
end
+
  
function p.main(frame, data)
+
    -- Trim whitespace and remove blank arguments for the following args:
data = data or mw.loadData('Module:Category handler/data')
+
    -- 1, 2, 3 etc., "nocat", "categories", "subpage", and "page".
local args = require('Module:Arguments').getArgs(frame, {
+
    for k, v in pairs(origArgs) do
wrappers = data.wrappers,
+
        v = mw.text.trim(v) -- Trim whitespace.
valueFunc = function (k, v)
+
        if type(k) == 'number'
v = trimWhitespace(v)
+
            or k == cfg.nocat
if type(k) == 'number' then
+
            or k == cfg.categories
if v ~= '' then
+
            or k == cfg.subpage
return v
+
            or k == cfg.page then
else
+
            if v ~= '' then
return nil
+
                args[k] = v
end
+
            end
else
+
        else
return v
+
            args[k] = v
end
+
        end
end
+
    end
})
+
   
return p._main(args, data)
+
    -- Lower-case "nocat", "categories", "category2", and "subpage".
 +
    local lowercase = { cfg.nocat, cfg.categories, cfg.category2, cfg.subpage }
 +
    for _, v in ipairs( lowercase ) do
 +
        if args[v] then
 +
            args[v] = mw.ustring.lower( args[v] )
 +
        end
 +
    end
 +
   
 +
    return _main()
 
end
 
end
  
 
return p
 
return p

Revision as of 10:13, 25 June 2013

Documentation for this module may be created at Module:Category handler/doc

Script error: Lua error: Internal error: The interpreter exited with status 126.

local basepageSubpage = require('Module:Basepage subpage').main

-- Configuration data.
local cfg = {}

cfg.nocat = 'nocat'    
cfg.categories = 'categories'
cfg.subpage = 'subpage'
cfg.page = 'page'
cfg.category2 = 'category2'
cfg.all = 'all'
cfg.main = 'main'
cfg.other = 'other'

-- Module start.
local p = {}
local args = {}

-- 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.
local function getPageObject()
    -- Get the title object for args.page if it is specified. Otherwise
    -- get the title object for the current page.
    if args[cfg.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, args[cfg.page])
        if not noError then
            return nil
        else
            return pageObject
        end
    else
        return mw.title.getCurrentTitle()
    end    
end

-- Find whether we need to return a category or not.
local function needsCategory( pageObject )
    if not pageObject then return end
    if args[cfg.nocat] == 'true'
        or ( args[cfg.category2] and args[cfg.category2] ~= 'yes' )
        or ( args[cfg.subpage] == 'no' and pageObject.isSubpage )
        or ( args[cfg.subpage] == 'only' and not pageObject.isSubpage ) then
        return false
    else
        return true
    end
end

-- Find whether we need to check the blacklist or not.
local function needsBlacklistCheck()
    if args[cfg.nocat] == 'false'
        or args[cfg.categories] == 'yes'
        or args[cfg.category2] == 'yes' then
        return false
    else
        return true
    end
end

local function _main()
    local pageObject = getPageObject()
    if not needsCategory( pageObject ) then return end
    
    return needsBlacklistCheck()
end

-- Process the arguments.
function p.main(frame)
    -- If called via #invoke, use the args passed into the invoking
    -- template, or the args passed to #invoke if any exist. Otherwise
    -- assume args are being passed directly in.
    local origArgs
    if frame == mw.getCurrentFrame() then
        origArgs = frame:getParent().args
        for k, v in pairs( frame.args ) do
            origArgs = frame.args
            break
        end
    else
        origArgs = frame
    end
    
    -- The following don't need blank values preserved:
    -- nocat
    -- categories
    -- subpage
    -- page
    -- positional parameters (1-10)
    
    -- The following *do* need blank values preserved
    -- category2
    -- all
    -- other
    -- main
    -- all the namespace parameters

    -- Trim whitespace and remove blank arguments for the following args:
    -- 1, 2, 3 etc., "nocat", "categories", "subpage", and "page".
    for k, v in pairs(origArgs) do
        v = mw.text.trim(v) -- Trim whitespace.
        if type(k) == 'number'
            or k == cfg.nocat
            or k == cfg.categories
            or k == cfg.subpage
            or k == cfg.page then
            if v ~= '' then
                args[k] = v
            end
        else
            args[k] = v
        end
    end
    
    -- Lower-case "nocat", "categories", "category2", and "subpage".
    local lowercase = { cfg.nocat, cfg.categories, cfg.category2, cfg.subpage }
    for _, v in ipairs( lowercase ) do
        if args[v] then
            args[v] = mw.ustring.lower( args[v] )
        end
    end
    
    return _main()
end

return p