Module:RecursiveSelectiveList

Revision as of 06:42, 22 December 2024 by EnWikiAdmin (talk | contribs)

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

local p = {}

-- Function to get pages recursively
local function getPagesFromCategory(categoryName, limit, visited, output)
    local categoryTitle = mw.title.new("Category:" .. categoryName)
    if not categoryTitle or not categoryTitle.exists then
        table.insert(output, "<!-- Debug: Category '" .. categoryName .. "' does not exist -->")
        return
    end

    -- Debug: Add to HTML comments
    table.insert(output, "<!-- Debug: Processing category '" .. categoryName .. "' -->")

    -- Get pages directly in the category
    local members = mw.site.categories[categoryName]
    for _, member in ipairs(members) do
        if member.ns == 0 and not visited[member.prefixedText] then
            visited[member.prefixedText] = true
            table.insert(output, "* [[" .. member.prefixedText .. "]]")
        end
    end

    -- Get subcategories and process them recursively
    local subcategories = {}
    for _, member in ipairs(members) do
        if member.ns == 14 and not visited[member.prefixedText] then
            visited[member.prefixedText] = true
            table.insert(subcategories, member.title)
        end
    end

    -- Debug: Log subcategories being processed
    table.insert(output, "<!-- Debug: Found " .. #subcategories .. " subcategories in '" .. categoryName .. "' -->")

    for _, subcategory in ipairs(subcategories) do
        if limit and #output >= limit then
            break
        end
        getPagesFromCategory(subcategory, limit, visited, output)
    end
end

-- Main function
function p.main(frame)
    local args = frame:getParent().args
    local categoryName = args["categoryName"]
    local limit = tonumber(args["limit"])
    local debugOutput = {} -- For storing debug comments

    if not categoryName then
        return "Error: Please provide a category name."
    end

    -- Debug: Add initial input validation to comments
    table.insert(debugOutput, "<!-- Debug: Starting with category '" .. categoryName .. "' -->")

    local output = {}
    getPagesFromCategory(categoryName, limit, {}, output)

    -- Join output and debug comments
    local result = table.concat(debugOutput, "\n") .. "\n" .. table.concat(output, "\n")
    return result
end

return p