Module:RecursiveSelectiveList

Revision as of 07:51, 22 December 2024 by EnWikiAdmin (talk | contribs)

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

local p = {}
local mw = require('mw')

-- Main function: Entry point for the module
function p.main(frame)
    -- Retrieve the template arguments
    local args = frame.args

    -- Get the 'categoryName' parameter from the template
    local categoryName = args.categoryName

    -- Check if 'categoryName' is provided
    if not categoryName or categoryName == "" then
        return "Error: 'categoryName' parameter is missing or empty."
    end

    -- Ensure the category name starts with "Category:"
    if not categoryName:match("^Category:") then
        categoryName = "Category:" .. categoryName
    end

    -- Debugging: Display the final category name being used
    local debugInfo = "Debug: Fetching members for '" .. categoryName .. "'\n"

    -- Fetch category members using the built-in method
    local members = p.getCategoryMembers(categoryName, args.limit)

    -- Check if the category has members
    if not members or #members == 0 then
        -- Add debug information about failure
        debugInfo = debugInfo .. "No members found for '" .. categoryName .. "'.\n"
        return debugInfo .. "The category '" .. categoryName .. "' has no members."
    end

    -- Return the list of category members as a comma-separated string
    return debugInfo .. "Members: " .. table.concat(members, ", ")
end

-- Function to fetch category members using the getCategoryMembers method
function p.getCategoryMembers(categoryName, limit)
    -- Table to store the member titles
    local members = {}

    -- Define default limit if not provided
    local cmlimit = tonumber(limit) or 500  -- MediaWiki allows up to 500 for bots and 50 for regular users

    -- Get the category title object
    local categoryTitle = mw.title.new(categoryName)
    if not categoryTitle then
        mw.log("Error: Invalid category title '" .. categoryName .. "'.")
        return members
    end

    -- Fetch category members using the method on the category title
    local iterator = categoryTitle:getCategoryMembers(cmlimit)

    -- Iterate over the category members and collect their titles
    for _, member in ipairs(iterator) do
        table.insert(members, member.title)
    end

    -- Debugging: Log the number of members fetched
    mw.log("Fetched " .. tostring(#members) .. " members from category '" .. categoryName .. "'.")

    return members
end

return p