模块:Cat

来自Cookie☆Wiki

可在模块:Cat/doc创建此模块的帮助文档

local p = {}

local yesno = require 'Module:Yesno'

local data = require 'Module:Cat/data'

local function matchPatternsInList(list, str)
    for _, pattern in ipairs(list) do
        if string.find(str, pattern) then
            return true
        end
    end
    return false
end

local function shouldBeSupressed(rules, title)
    -- 根据命名空间筛选是否添加分类
    -- ns_mode 是名字空间判定的模式, 可以是 blacklist 或 whitelist, 默认为 blacklist
    if not rules.ns_mode or rules.ns_mode == 'blacklist' then
        -- nsid_blacklist: {number-> bool?}, 键是名字空间的 id, 值是是否在黑名单内, 缺省为不在
        if rules.nsid_blacklist and rules.nsid_blacklist[title.namespace] then
            return true
        end
    elseif rules.ns_mode == 'whitelist' then
        -- nsid_whitelist: {number-> bool?}, 规则同 nsid_blacklist
        if not rules.nsid_whitelist or not rules.nsid_whitelist[title.namespace] then
            return true
        end
    else
        error('bad ns_mode')
    end

    -- 根据条目标题模式筛选是否添加分类
    -- title_mode 是条目标题判定的模式, 规则同 ns_mode
    if not rules.title_mode or rules.title_mode == 'blacklist' then
        -- title_blacklist: [pattern], 存放了一组 pattern 用于匹配
        if rules.title_blacklist and matchPatternsInList(rules.title_blacklist, title.text) then
            return true
        end
    elseif rules.title_mode == 'whitelist' then
        if not rules.title_whitelist or not matchPatternsInList(rules.title_whitelist, title.text) then
            return true
        end
    else
        error('bad title_mode')
    end

    return false
end

function p.main()
    local frame = mw.getCurrentFrame():getParent()
    
    -- 如果 nocat 参数为真, 直接不会分类
    -- 如果 nocat 参数为假, 无论如何都会分类
    local nocat = yesno(frame.args.nocat, nil)
    if nocat then
        return nil
    elseif nocat == false then
        return frame.args[1]
    end

    local title = mw.title.getCurrentTitle()

    if shouldBeSupressed(data.rulesMap['*'], title) then
        return nil
    end

    local kind = frame.args[2] or frame.args['kind'] or 'unspecified'
    local rules = data.rulesMap[kind] or data.rulesMap['unspecified']

    if rules and shouldBeSupressed(rules, title) then
        return nil
    end 

    return frame.args[1]

end

return p