Module:DependencyList: Difference between revisions

osrsw>Gaz Lloyd
m use [^:] instead
osrsw>TehKittyCat
Sync with rsw
Line 1: Line 1:
require("strict");
local p = {}
local p = {}
local libraryUtil = require( 'libraryUtil' )
local libraryUtil = require('libraryUtil')
local arr = require( 'Module:Array' )
local arr = require('Module:Array')
local yn = require( 'Module:Yesno' )
local yn = require('Module:Yesno')
local param = require( 'Module:Paramtest' )
local param = require('Module:Paramtest')
local dpl = require( 'Module:DPLlua' )
local dpl = require('Module:DPLlua')
local tooltip = require( 'Module:Tooltip' )
local tooltip = require('Module:Tooltip')
local userError = require("Module:User error")
local moduleIsUsed = false
local moduleIsUsed = false
local COLLAPSE_LIST_LENGTH_THRESHOLD = 5
local COLLAPSE_LIST_LENGTH_THRESHOLD = 5
Line 12: Line 14:


local builtins = {
local builtins = {
    ["libraryUtil"] = {
["libraryUtil"] = {
        link = "mw:Special:MyLanguage/Extension:Scribunto/Lua reference manual#libraryUtil",
link = "mw:Special:MyLanguage/Extension:Scribunto/Lua reference manual#libraryUtil",
        categories = {},
categories = {},
    },
},
    ["strict"] = {
["strict"] = {
        link = "mw:Special:MyLanguage/Extension:Scribunto/Lua reference manual#strict",
link = "mw:Special:MyLanguage/Extension:Scribunto/Lua reference manual#strict",
        categories = { "Strict mode modules" },
categories = { "Strict mode modules" },
    },
},
}
};


--- Used in case 'require( varName )' is found. Attempts to find a string value stored in 'varName'.
--- Used in case 'require( varName )' is found. Attempts to find a string value stored in 'varName'.
Line 27: Line 29:
---@return string
---@return string
local function substVarValue( content, varName )
local function substVarValue( content, varName )
    local res = content:match( varName .. '%s*=%s*(%b""%s-%.*)' ) or content:match( varName .. "%s*=%s*(%b''%s-%.*)" ) or ''
local res = content:match( varName .. '%s*=%s*(%b""%s-%.*)' ) or content:match( varName .. "%s*=%s*(%b''%s-%.*)" ) or ''
    if res:find( '^(["\'])[Mm]odule:[%S]+%1' ) and not res:find( '%.%.' ) and not res:find( '%%%a' ) then
if res:find( '^(["\'])[Mm]odule:[%S]+%1' ) and not res:find( '%.%.' ) and not res:find( '%%%a' ) then
        return mw.text.trim( res )
return mw.text.trim( res )
    else
else
        return ''
return ''
    end
end
end
end


Line 39: Line 41:
---@return string
---@return string
local function extractModuleName( capture, content )
local function extractModuleName( capture, content )
    capture = capture:gsub( '^%(%s*(.-)%s*%)$', '%1' )
capture = capture:gsub( '^%(%s*(.-)%s*%)$', '%1' )


    if capture:find( '^(["\']).-%1$' ) then -- Check if it is already a pure string
if capture:find( '^(["\']).-%1$' ) then -- Check if it is already a pure string
        return capture
return capture
    elseif capture:find( '^[%a_][%w_]*$' ) then -- Check if if is a single variable
elseif capture:find( '^[%a_][%w_]*$' ) then -- Check if if is a single variable
        return substVarValue( content, capture )
return substVarValue( content, capture )
    end
end


    return capture
return capture
end
end


Line 53: Line 55:
---@return string
---@return string
local function formatPageName( str )
local function formatPageName( str )
    local name = mw.text.trim(str)
local name = mw.text.trim(str)
        :gsub( '^([\'\"])(.-)%1$', '%2' ) -- Only remove quotes at start and end of string if both are the same type
:gsub( '^([\'\"])(.-)%1$', '%2' ) -- Only remove quotes at start and end of string if both are the same type
        :gsub( '_', ' ' )
:gsub( '_', ' ' )
        :gsub( '^.', string.upper )
:gsub( '^.', string.upper )
         :gsub( '^([^:]-:)(.)', function(a,b) return a..string.upper(b) end )
         :gsub( '^([^:]-:)(.)', function(a,b) return a..string.upper(b) end )


    return name
return name
end
end


Line 66: Line 68:
---@return string
---@return string
local function formatModuleName( str, allowBuiltins )
local function formatModuleName( str, allowBuiltins )
    if allowBuiltins then
if allowBuiltins then
        local name = mw.text.trim(str)
local name = mw.text.trim(str)
            -- Only remove quotes at start and end of string if both are the same type
-- Only remove quotes at start and end of string if both are the same type
            :gsub([[^(['"])(.-)%1$]], '%2')
:gsub([[^(['"])(.-)%1$]], '%2')


        if builtins[name] then
if builtins[name] then
            return name
return name
        end
end
    end
end


    local module = formatPageName( str )
local module = formatPageName( str )


    if not string.find( module, '^[Mm]odule:' ) then
if not string.find( module, '^[Mm]odule:' ) then
        module = 'Module:' .. module
module = 'Module:' .. module
    end
end


    return module
return module
end
end


local function dualGmatch( str, pat1, pat2 )
local function dualGmatch( str, pat1, pat2 )
    local f1 = string.gmatch( str, pat1 )
local f1 = string.gmatch( str, pat1 )
    if pat2 then
if pat2 then
        local f2 = string.gmatch( str, pat2 )
local f2 = string.gmatch( str, pat2 )
        return function()
return function()
            return f1() or f2()
return f1() or f2()
        end
end
    else
else
        return f1
return f1
    end
end
end
end


local function isDynamicPath( str )
local function isDynamicPath( str )
    return string.find( str, '%.%.' ) or string.find( str, '%%%a' )
return string.find( str, '%.%.' ) or string.find( str, '%%%a' )
end
end


Line 106: Line 108:
---@return string[]
---@return string[]
local function getDynamicRequireList( query )
local function getDynamicRequireList( query )
    if query:find( '%.%.' ) then
if query:find( '%.%.' ) then
        query = mw.text.split( query, '..', true )
query = mw.text.split( query, '..', true )
        query = arr.map( query, function(x) return mw.text.trim(x) end )
query = arr.map( query, function(x) return mw.text.trim(x) end )
        query = arr.map( query, function(x) return (x:match('^[\'\"](.-)[\'\"]$') or '%') end )
query = arr.map( query, function(x) return (x:match('^[\'\"](.-)[\'\"]$') or '%') end )
        query = table.concat( query )
query = table.concat( query )
    else
else
        local _, _query = query:match( '(["\'])(.-)%1' )
local _, _query = query:match( '(["\'])(.-)%1' )
        query = _query:gsub( '%%%a', '%%' )
query = _query:gsub( '%%%a', '%%' )
    end
end
    query = query:gsub( '^[Mm]odule:', '' )
query = query:gsub( '^[Mm]odule:', '' )


    if query:find( '^[Ee]xchange/' ) or query:find( '^[Dd]ata/' ) then
query = mw.language.getContentLanguage():ucfirst(query)
        return { 'Module:' .. query }  -- This format will later be used by formatDynamicQueryLink()
if query:find( '^Exchange/' ) or query:find( '^Data/' ) then
    end
return { 'Module:' .. query }  -- This format will later be used by formatDynamicQueryLink()
end


    if dynamicRequireListQueryCache[ query ] then
if dynamicRequireListQueryCache[ query ] then
        return dynamicRequireListQueryCache[ query ]
return dynamicRequireListQueryCache[ query ]
    end
end


    local list = dpl.ask{
local list = dpl.ask{
        namespace = 'Module',
namespace = 'Module',
        titlematch = query,
titlematch = query,
        nottitlematch = '%/doc|'..query..'/%',
nottitlematch = '%/doc|'..query..'/%',
        distinct = 'strict',
distinct = 'strict',
        ignorecase = true,
ordermethod = 'title',
        ordermethod = 'title',
count = MAX_DYNAMIC_REQUIRE_LIST_LENGTH + 1,
        count = MAX_DYNAMIC_REQUIRE_LIST_LENGTH + 1,
skipthispage = 'no',
        skipthispage = 'no',
allowcachedresults = true,
        allowcachedresults = true,
cacheperiod = 604800 -- One week
        cacheperiod = 604800 -- One week
}
    }


    if #list > MAX_DYNAMIC_REQUIRE_LIST_LENGTH then
if #list > MAX_DYNAMIC_REQUIRE_LIST_LENGTH then
        list = { 'Module:' .. query }
list = { 'Module:' .. query }
    end
end


    dynamicRequireListQueryCache[ query ] = list
dynamicRequireListQueryCache[ query ] = list


    return list
return list
end
end


Line 152: Line 154:
---@return table<string, string[]>
---@return table<string, string[]>
local function getRequireList( moduleName, searchForUsedTemplates )
local function getRequireList( moduleName, searchForUsedTemplates )
    local content = mw.title.new( moduleName ):getContent()
local content = mw.title.new( moduleName ):getContent()
    local requireList = arr{}
local requireList = arr{}
    local loadDataList = arr{}
local loadDataList = arr{}
    local loadJsonDataList = arr{}
local loadJsonDataList = arr{}
    local usedTemplateList = arr{}
local usedTemplateList = arr{}
    local dynamicRequirelist = arr{}
local dynamicRequirelist = arr{}
    local dynamicLoadDataList = arr{}
local dynamicLoadDataList = arr{}
    local dynamicLoadJsonDataList = arr{}
local dynamicLoadJsonDataList = arr{}
    local extraCategories = arr{}
local extraCategories = arr{}


    assert( content ~= nil, string.format( '%s does not exist', moduleName ) )
assert( content ~= nil, string.format( '%s does not exist', moduleName ) )


    content = content:gsub( '%-%-%[(=-)%[.-%]%1%]', '' ):gsub( '%-%-[^\n]*', '' ) -- Strip comments
content = content:gsub( '%-%-%[(=-)%[.-%]%1%]', '' ):gsub( '%-%-[^\n]*', '' ) -- Strip comments


    local function getList( pat1, pat2, list, dynList )
local function getList( pat1, pat2, list, dynList )
        for match in dualGmatch( content, pat1, pat2 ) do
for match in dualGmatch( content, pat1, pat2 ) do
            match = mw.text.trim( match )
match = mw.text.trim( match )
            local name = extractModuleName( match, content )
local name = extractModuleName( match, content )


            if isDynamicPath( name ) then
if isDynamicPath( name ) then
                dynList:insert( getDynamicRequireList( name ), true )
dynList:insert( getDynamicRequireList( name ), true )
            elseif name ~= '' then
elseif name ~= '' then
                name = formatModuleName( name, true )
name = formatModuleName( name, true )
                table.insert( list, name )
table.insert( list, name )


                if builtins[name] then
if builtins[name] then
                    extraCategories = extraCategories:insert( builtins[name].categories, true )
extraCategories = extraCategories:insert( builtins[name].categories, true )
                end
end
            end
end
        end
end
    end
end


    getList( 'require%s*(%b())', 'require%s*((["\'])%s*[Mm]odule:.-%2)', requireList, dynamicRequirelist )
getList( 'require%s*(%b())', 'require%s*((["\'])%s*[Mm]odule:.-%2)', requireList, dynamicRequirelist )
    getList( 'mw%.loadData%s*(%b())', 'mw%.loadData%s*((["\'])%s*[Mm]odule:.-%2)', loadDataList, dynamicLoadDataList )
getList( 'mw%.loadData%s*(%b())', 'mw%.loadData%s*((["\'])%s*[Mm]odule:.-%2)', loadDataList, dynamicLoadDataList )
    getList( 'mw%.loadJsonData%s*(%b())', 'mw%.loadJsonData%s*((["\'])%s*[Mm]odule:.-%2)', loadJsonDataList, dynamicLoadJsonDataList )
getList( 'mw%.loadJsonData%s*(%b())', 'mw%.loadJsonData%s*((["\'])%s*[Mm]odule:.-%2)', loadJsonDataList, dynamicLoadJsonDataList )
    getList( 'pcall%s*%(%s*require%s*,([^%),]+)', nil, requireList, dynamicRequirelist )
getList( 'pcall%s*%(%s*require%s*,([^%),]+)', nil, requireList, dynamicRequirelist )
    getList( 'pcall%s*%(%s*mw%.loadData%s*,([^%),]+)', nil, loadDataList, dynamicLoadDataList )
getList( 'pcall%s*%(%s*mw%.loadData%s*,([^%),]+)', nil, loadDataList, dynamicLoadDataList )
    getList( 'pcall%s*%(%s*mw%.loadJsonData%s*,([^%),]+)', nil, loadJsonDataList, dynamicLoadJsonDataList )
getList( 'pcall%s*%(%s*mw%.loadJsonData%s*,([^%),]+)', nil, loadJsonDataList, dynamicLoadJsonDataList )


    if searchForUsedTemplates then
if searchForUsedTemplates then
        for preprocess in string.gmatch( content, ':preprocess%s*(%b())' ) do
for preprocess in string.gmatch( content, ':preprocess%s*(%b())' ) do
            local function recursiveGMatch( str, pat )
local function recursiveGMatch( str, pat )
                local list = {}
local list = {}
                local i = 0
local i = 0
                repeat
repeat
                    for match in string.gmatch( list[i] or str, pat ) do
for match in string.gmatch( list[i] or str, pat ) do
                        table.insert( list, match )
table.insert( list, match )
                    end
end
                    i =  i + 1
i =  i + 1
                until i > #list or i > 100
until i > #list or i > 100


                i = 0
i = 0
                return function()
return function()
                    i = i + 1
i = i + 1
                    return list[i]
return list[i]
                end
end
            end
end


            for template in recursiveGMatch( preprocess, '{(%b{})}' ) do
for template in recursiveGMatch( preprocess, '{(%b{})}' ) do
                local name = string.match( template, '{(.-)[|{}]' )
local name = string.match( template, '{(.-)[|{}]' )
                if name ~= '' then
if name ~= '' then
                    if name:find( ':' ) then
if name:find( ':' ) then
                        local ns = name:match( '^(.-):' )
local ns = name:match( '^(.-):' )
                        if arr.contains( {'', 'template', 'calculator', 'user'}, ns:lower() ) then
if arr.contains( {'', 'template', 'calculator', 'user'}, ns:lower() ) then
                            table.insert( usedTemplateList, name )
table.insert( usedTemplateList, name )
                        elseif ns == ns:upper() then
elseif ns == ns:upper() then
                            table.insert( usedTemplateList, ns ) -- Probably a magic word
table.insert( usedTemplateList, ns ) -- Probably a magic word
                        end
end
                    else
else
                        if name:match( '^%u+$' ) or name == '!' then
if name:match( '^%u+$' ) or name == '!' then
                            table.insert( usedTemplateList, name ) -- Probably a magic word
table.insert( usedTemplateList, name ) -- Probably a magic word
                        else
else
                            table.insert( usedTemplateList, 'Template:'..name )
table.insert( usedTemplateList, 'Template:'..name )
                        end
end
                    end
end
                end
end
            end
end
        end
end
    end
end


    requireList = requireList .. dynamicRequirelist
requireList = requireList .. dynamicRequirelist
    requireList = requireList:unique()
requireList = requireList:unique()
    loadDataList = loadDataList .. dynamicLoadDataList
loadDataList = loadDataList .. dynamicLoadDataList
    loadDataList = loadDataList:unique()
loadDataList = loadDataList:unique()
    loadJsonDataList = loadJsonDataList .. dynamicLoadJsonDataList
loadJsonDataList = loadJsonDataList .. dynamicLoadJsonDataList
    usedTemplateList = usedTemplateList:unique()
loadJsonDataList = loadJsonDataList:unique()
    extraCategories = extraCategories:unique()
usedTemplateList = usedTemplateList:unique()
    table.sort( requireList )
extraCategories = extraCategories:unique();
    table.sort( loadDataList )
table.sort( requireList )
    table.sort( loadJsonDataList )
table.sort( loadDataList )
    table.sort( usedTemplateList )
table.sort( loadJsonDataList )
    table.sort( extraCategories )
table.sort( usedTemplateList )
table.sort(extraCategories);


    return {
return {
        requireList = requireList,
requireList = requireList,
        loadDataList = loadDataList,
loadDataList = loadDataList,
        loadJsonDataList = loadJsonDataList,
loadJsonDataList = loadJsonDataList,
        usedTemplateList = usedTemplateList,
usedTemplateList = usedTemplateList,
        extraCategories = extraCategories
extraCategories = extraCategories,
    }
};
end
end


Line 258: Line 261:
---@return table<string, string>[]
---@return table<string, string>[]
local function getInvokeCallList( templateName )
local function getInvokeCallList( templateName )
    local content = mw.title.new( templateName ):getContent()
local content = mw.title.new( templateName ):getContent()
    local invokeList = {}
local invokeList = {}


    assert( content ~= nil, string.format( '%s does not exist', templateName ) )
assert( content ~= nil, string.format( '%s does not exist', templateName ) )


    for moduleName, funcName in string.gmatch( content, '{{[{|safeubt:}]-#[Ii]nvoke:([^|]+)|([^}|]+)[^}]*}}' ) do
for moduleName, funcName in string.gmatch( content, '{{[{|safeubt:}]-#[Ii]nvoke:([^|]+)|([^}|]+)[^}]*}}' ) do
        moduleName = formatModuleName( moduleName )
moduleName = formatModuleName( moduleName )
        funcName = mw.text.trim( funcName )
funcName = mw.text.trim( funcName )
        if string.find( funcName, '^{{{' ) then
if string.find( funcName, '^{{{' ) then
            funcName = funcName ..  '}}}'
funcName = funcName ..  '}}}'
        end
end
        table.insert( invokeList, {moduleName=moduleName, funcName=funcName} )
table.insert( invokeList, {moduleName=moduleName, funcName=funcName} )
    end
end


    -- For form calcs invoking the module directly
-- For form calcs invoking the module directly
    for config in dualGmatch( content, '<pre%s+class%s*=%s*["\']jcConfig["\'](.-)</pre>', '{{[Ff]orm calculator%s*|(.+)}}' ) do
for config in dualGmatch( content, '<[pd][ri][ev]%s+class%s*=%s*["\']jcConfig["\'](.-)</[pd][ri][ev]>', '{{[Ff]orm calculator%s*|(.+)}}' ) do
        local moduleName = string.match( config, 'module%s*=%s*(.-)[\n|]' )
local moduleName = string.match( config, 'module%s*=%s*(.-)[\n|]' )
        if param.has_content( moduleName ) then
if param.has_content( moduleName ) then
            moduleName = formatModuleName( moduleName )
moduleName = formatModuleName( moduleName )
            local funcName = string.match( config, 'modulefunc%s*=%s*(.-)[\n|]' ) or 'main'
local funcName = string.match( config, 'modulefunc%s*=%s*(.-)[\n|]' ) or 'main'
            table.insert( invokeList, {moduleName=moduleName, funcName=funcName} )
table.insert( invokeList, {moduleName=moduleName, funcName=funcName} )
        end
end
    end
end


    invokeList = arr.unique( invokeList, function(x) return x.moduleName..x.funcName end )
invokeList = arr.unique( invokeList, function(x) return x.moduleName..x.funcName end )
    table.sort( invokeList, function(x, y) return x.moduleName..x.funcName < y.moduleName..y.funcName end )
table.sort( invokeList, function(x, y) return x.moduleName..x.funcName < y.moduleName..y.funcName end )


    return invokeList
return invokeList
end
end


Line 292: Line 295:
---@return string
---@return string
local function messageBoxUnused( pageName, addCategories )
local function messageBoxUnused( pageName, addCategories )
    local html = mw.html.create( 'table' ):addClass( 'messagebox obsolete plainlinks' )
local html = mw.html.create( 'table' ):addClass( 'messagebox obsolete plainlinks' )
    html:tag( 'td' )
html:tag( 'td' )
        :attr( 'width', '40xp' )
:attr( 'width', '40xp' )
        :wikitext( '[[File:Willow logs (historical).png|center|30px|link=]]' )
:wikitext( '[[File:Willow logs (historical).png|center|30px|link=]]' )
    :done()
:done()
    :tag( 'td' )
:tag( 'td' )
        :wikitext( "'''This module is unused.'''" )
:wikitext( "'''This module is unused.'''" )
        :tag( 'div' )
:tag( 'div' )
            :css{ ['font-size']='0.85em', ['line-height']='1.45em' }
:css{ ['font-size']='0.85em', ['line-height']='1.45em' }
            :wikitext( string.format( 'This module is neither invoked by a template nor required/loaded by another module. If this is in error, make sure to add <code>{{[[Template:Documentation|Documentation]]}}</code>/<code>{{[[Template:No documentation|No&nbsp;documentation]]}}</code> to the calling template\'s or parent\'s module documentation.', pageName ) )
:wikitext( string.format( 'This module is neither invoked by a template nor required/loaded by another module. If this is in error, make sure to add <code>{{[[Template:Documentation|Documentation]]}}</code>/<code>{{[[Template:No documentation|No&nbsp;documentation]]}}</code> to the calling template\'s or parent\'s module documentation.', pageName ) )
            :wikitext( addCategories and '[[Category:Unused modules]]' or '' )
:wikitext( addCategories and '[[Category:Unused modules]]' or '' )
        :done()
:done()
    :done()
:done()


    return tostring( html )
return tostring( html )
end
end


local function collapseList( list, id, listType )
local function collapseList( list, id, listType )
    local text = string.format( '%d %s', #list, listType )
local text = string.format( '%d %s', #list, listType )
    local button = tooltip._span{ name=id, alt=text }
local button = tooltip._span{ name=id, alt=text }
    list = arr.map( list, function(x) return '\n# '..x end )
list = arr.map( list, function(x) return '\n# '..x end )
    local content = tooltip._div{ name=id, content='\n'..table.concat( list )..'\n\n' }
local content = tooltip._div{ name=id, content='\n'..table.concat( list )..'\n\n' }


    return { tostring( button ) .. tostring( content ) }
return { tostring( button ) .. tostring( content ) }
end
end


Line 322: Line 325:
---@return string
---@return string
local function formatDynamicQueryLink( query )
local function formatDynamicQueryLink( query )
    local prefix = query:match( '^([^/]+)' )
local prefix = query:match( '^([^/]+)' )
    local linkText = query:gsub( '%%', '&lt; ... &gt;' )
local linkText = query:gsub( '%%', '&lt; ... &gt;' )


    query = query:gsub( '^Module:',  '' )
query = query:gsub( '^Module:',  '' )


    query = query:gsub( '([^/]+)/?', function ( match )
query = query:gsub( '([^/]+)/?', function ( match )
        if match == '%' then
if match == '%' then
            return '\\/[^\\/]+'
return '\\/[^\\/]+'
        else
else
            return '\\/"' .. match .. '"'
return '\\/"' .. match .. '"'
        end
end
    end )
end )


    query = query:gsub( '^\\/', '' )
query = query:gsub( '^\\/', '' )


    query = string.format(
query = string.format(
        'intitle:/%s%s/i -intitle:/%s\\/""/i -intitle:doc prefix:"%s"',
'intitle:/%s%s/i -intitle:/%s\\/""/i -intitle:doc prefix:"%s"',
        query,
query,
        query:find( '"$' ) and '' or '""',
query:find( '"$' ) and '' or '""',
        query,
query,
        prefix
prefix
    )
)


    return string.format( '<span class="plainlinks">[%s %s]</span>', tostring( mw.uri.fullUrl( 'Special:Search', { search = query } ) ), linkText )
return string.format( '<span class="plainlinks">[%s %s]</span>', tostring( mw.uri.fullUrl( 'Special:Search', { search = query } ) ), linkText )
end
end


---@param templateName string
---@param templateName string
---@param addCategories boolean
---@param addCategories boolean
---@param invokeList table<string, string>[]   @This is the list returned by getInvokeCallList()
---@param invokeList table<string, string>[] @This is the list returned by getInvokeCallList()
---@return string
---@return string
local function formatInvokeCallList( templateName, addCategories, invokeList )
local function formatInvokeCallList( templateName, addCategories, invokeList )
    local category = addCategories and '[[Category:Lua-based templates]]' or ''
local category = addCategories and '[[Category:Lua-based templates]]' or ''
    local res = {}
local res = {}


    for _, item in ipairs( invokeList ) do
for _, item in ipairs( invokeList ) do
        table.insert( res, string.format(
table.insert( res, string.format(
            "<div class='seealso'>'''%s''' invokes function '''%s''' in [[%s]] using [[RuneScape:Lua|Lua]].</div>",
"<div class='seealso'>'''%s''' invokes function '''%s''' in [[%s]] using [[RuneScape:Lua|Lua]].</div>",
            templateName,
templateName,
            item.funcName,
item.funcName,
            item.moduleName
item.moduleName
        ) )
) )
    end
end


    if #invokeList > 0 then
if #invokeList > 0 then
        table.insert( res, category )
table.insert( res, category )
    end
end


    return table.concat( res )
return table.concat( res )
end
end


Line 377: Line 380:
---@return string
---@return string
local function formatInvokedByList( moduleName, addCategories, whatLinksHere )
local function formatInvokedByList( moduleName, addCategories, whatLinksHere )
    local function lcfirst( str )
local function lcfirst( str )
        return string.gsub( str, '^[Mm]odule:.', string.lower )
return string.gsub( str, '^[Mm]odule:.', string.lower )
    end
end


    local templateData = arr.map( whatLinksHere, function(x) return {templateName=x, invokeList=getInvokeCallList(x)} end )
local templateData = arr.map( whatLinksHere, function(x) return {templateName=x, invokeList=getInvokeCallList(x)} end )
    templateData = arr.filter( templateData, function(x)
templateData = arr.filter( templateData, function(x)
        return arr.any( x.invokeList, function(y)
return arr.any( x.invokeList, function(y)
            return lcfirst(y.moduleName) == lcfirst(moduleName)
return lcfirst(y.moduleName) == lcfirst(moduleName)
        end )
end )
    end )
end )


    local invokedByList = {}
local invokedByList = {}


    for _, template in ipairs( templateData ) do
for _, template in ipairs( templateData ) do
        for _, invoke in ipairs( template.invokeList ) do
for _, invoke in ipairs( template.invokeList ) do
            table.insert( invokedByList, string.format( "function '''%s''' is invoked by [[%s]]", invoke.funcName, template.templateName ) )
table.insert( invokedByList, string.format( "function '''%s''' is invoked by [[%s]]", invoke.funcName, template.templateName ) )
        end
end
    end
end


    table.sort( invokedByList)
table.sort( invokedByList)


    local res = {}
local res = {}


    if #invokedByList > COLLAPSE_LIST_LENGTH_THRESHOLD then
if #invokedByList > COLLAPSE_LIST_LENGTH_THRESHOLD then
        table.insert( res, string.format(
table.insert( res, string.format(
            "<div class='seealso'>'''%s''' is invoked by %s.</div>",
"<div class='seealso'>'''%s''' is invoked by %s.</div>",
            moduleName,
moduleName,
            collapseList( invokedByList, 'invokedBy', 'templates' )[1]
collapseList( invokedByList, 'invokedBy', 'templates' )[1]
        ) )
) )
    else
else
        for _, item in ipairs( invokedByList ) do
for _, item in ipairs( invokedByList ) do
            table.insert( res, string.format(
table.insert( res, string.format(
                "<div class='seealso'>'''%s's''' %s.</div>",
"<div class='seealso'>'''%s's''' %s.</div>",
                moduleName,
moduleName,
                item
item
            ) )
) )
        end
end
    end
end


    if #templateData > 0 then
if #templateData > 0 then
        moduleIsUsed = true
moduleIsUsed = true
        table.insert( res, (addCategories and '[[Category:Template invoked modules]]' or '') )
table.insert( res, (addCategories and '[[Category:Template invoked modules]]' or '') )
    end
end


    return table.concat( res )
return table.concat( res )
end
end


Line 429: Line 432:
---@return string
---@return string
local function formatRequiredByList( moduleName, addCategories, whatLinksHere )
local function formatRequiredByList( moduleName, addCategories, whatLinksHere )
    local childModuleData = arr.map( whatLinksHere, function ( title )
local childModuleData = arr.map( whatLinksHere, function ( title )
        local lists = getRequireList( title )
local lists = getRequireList( title )
        return {name=title, requireList=lists.requireList, loadDataList=lists.loadDataList .. lists.loadJsonDataList}
return {name=title, requireList=lists.requireList, loadDataList=lists.loadDataList .. lists.loadJsonDataList}
    end )
end )


    local requiredByList = arr.map( childModuleData, function ( item )
local requiredByList = arr.map( childModuleData, function ( item )
        if arr.any( item.requireList, function(x) return x:lower()==moduleName:lower() end ) then
if arr.any( item.requireList, function(x) return x:lower()==moduleName:lower() end ) then
            if item.name:find( '%%' ) then
if item.name:find( '%%' ) then
                return formatDynamicQueryLink( item.name )
return formatDynamicQueryLink( item.name )
            else
else
                return '[[' .. item.name .. ']]'
return '[[' .. item.name .. ']]'
            end
end
        end
end
    end )
end )


    local loadedByList = arr.map( childModuleData, function ( item )
local loadedByList = arr.map( childModuleData, function ( item )
        if arr.any( item.loadDataList, function(x) return x:lower()==moduleName:lower() end ) then
if arr.any( item.loadDataList, function(x) return x:lower()==moduleName:lower() end ) then
            if item.name:find( '%%' ) then
if item.name:find( '%%' ) then
                return formatDynamicQueryLink( item.name )
return formatDynamicQueryLink( item.name )
            else
else
                return '[[' .. item.name .. ']]'
return '[[' .. item.name .. ']]'
            end
end
        end
end
    end )
end )


    if #requiredByList > 0 or #loadedByList > 0 then
if #requiredByList > 0 or #loadedByList > 0 then
        moduleIsUsed  = true
moduleIsUsed  = true
    end
end


    if #requiredByList > COLLAPSE_LIST_LENGTH_THRESHOLD then
if #requiredByList > COLLAPSE_LIST_LENGTH_THRESHOLD then
        requiredByList = collapseList( requiredByList, 'requiredBy', 'modules' )
requiredByList = collapseList( requiredByList, 'requiredBy', 'modules' )
    end
end


    if #loadedByList > COLLAPSE_LIST_LENGTH_THRESHOLD then
if #loadedByList > COLLAPSE_LIST_LENGTH_THRESHOLD then
        loadedByList = collapseList( loadedByList, 'loadedBy', 'modules' )
loadedByList = collapseList( loadedByList, 'loadedBy', 'modules' )
    end
end


    local res = {}
local res = {}


    for _, requiredByModuleName in ipairs( requiredByList ) do
for _, requiredByModuleName in ipairs( requiredByList ) do
        table.insert( res, string.format(
table.insert( res, string.format(
            "<div class='seealso'>'''%s''' is required by %s.</div>",
"<div class='seealso'>'''%s''' is required by %s.</div>",
            moduleName,
moduleName,
            requiredByModuleName
requiredByModuleName
        ) )
) )
    end
end


    if #requiredByList > 0 then
if #requiredByList > 0 then
        table.insert( res, (addCategories and '[[Category:Modules required by modules]]' or '') )
table.insert( res, (addCategories and '[[Category:Modules required by modules]]' or '') )
    end
end


    for _, loadedByModuleName in ipairs( loadedByList ) do
for _, loadedByModuleName in ipairs( loadedByList ) do
        table.insert( res, string.format(
table.insert( res, string.format(
            "<div class='seealso'>'''%s''' is loaded by %s.</div>",
"<div class='seealso'>'''%s''' is loaded by %s.</div>",
            moduleName,
moduleName,
            loadedByModuleName
loadedByModuleName
        ) )
) )
    end
end


    if #loadedByList > 0 then
if #loadedByList > 0 then
        table.insert( res, (addCategories and '[[Category:Module data]]' or '') )
table.insert( res, (addCategories and '[[Category:Module data]]' or '') )
    end
end


    return table.concat( res )
return table.concat( res )
end
end


local function formatImportList( currentPageName, moduleList, id, message, category )
local function formatImportList( currentPageName, moduleList, id, message, category )
    if #moduleList > COLLAPSE_LIST_LENGTH_THRESHOLD then
if #moduleList > COLLAPSE_LIST_LENGTH_THRESHOLD then
        moduleList = collapseList( moduleList, id, 'modules' )
moduleList = collapseList( moduleList, id, 'modules' )
    end
end


    local res = arr.map( moduleList, function( moduleName )
local res = arr.map( moduleList, function( moduleName )
        return '<div class="seealso">' .. string.format( message, currentPageName, moduleName ) .. '</div>'
return '<div class="seealso">' .. string.format( message, currentPageName, moduleName ) .. '</div>'
    end )
end )


    if #moduleList > 0 and category then
if #moduleList > 0 and category then
        table.insert( res, string.format( '[[Category:%s]]', category ) )
table.insert( res, string.format( '[[Category:%s]]', category ) )
    end
end


    return table.concat( res )
return table.concat( res )
end
end


local function formatUsedTemplatesList( currentPageName, addCategories, usedTemplateList )
local function formatUsedTemplatesList( currentPageName, addCategories, usedTemplateList )
    local res = {}
local res = {}


    if #usedTemplateList > COLLAPSE_LIST_LENGTH_THRESHOLD then
if #usedTemplateList > COLLAPSE_LIST_LENGTH_THRESHOLD then
        usedTemplateList = collapseList( usedTemplateList, 'usedTemplates', 'templates' )
usedTemplateList = collapseList( usedTemplateList, 'usedTemplates', 'templates' )
    end
end


    for _, templateName in ipairs( usedTemplateList ) do
for _, templateName in ipairs( usedTemplateList ) do
        table.insert( res, string.format(
table.insert( res, string.format(
            "<div class='seealso'>'''%s''' transcludes %s using <samp>frame:preprocess()</samp>.</div>",
"<div class='seealso'>'''%s''' transcludes %s using <samp>frame:preprocess()</samp>.</div>",
            currentPageName,
currentPageName,
            templateName
templateName
        ) )
) )
    end
end


    return table.concat( res )
return table.concat( res )
end
end


function p.main( frame )
function p.main( frame )
    local args = frame:getParent().args
local args = frame:getParent().args
    return p._main( args[1], args.category, args.isUsed )
return p._main( args[1], args.category, args.isUsed )
end
end


Line 538: Line 541:
---@return string
---@return string
function p._main( currentPageName, addCategories, isUsed )
function p._main( currentPageName, addCategories, isUsed )
    libraryUtil.checkType( 'Module:RequireList._main', 1, currentPageName, 'string', true )
libraryUtil.checkType( 'Module:RequireList._main', 1, currentPageName, 'string', true )
    libraryUtil.checkTypeMulti( 'Module:RequireList._main', 2, addCategories, {'boolean', 'string', 'nil'} )
libraryUtil.checkTypeMulti( 'Module:RequireList._main', 2, addCategories, {'boolean', 'string', 'nil'} )
    libraryUtil.checkTypeMulti( 'Module:RequireList._main', 3, isUsed, {'boolean', 'string', 'nil'} )
libraryUtil.checkTypeMulti( 'Module:RequireList._main', 3, isUsed, {'boolean', 'string', 'nil'} )


    local title = mw.title.getCurrentTitle()
local title = mw.title.getCurrentTitle()


    -- Leave early if not in module, template or calculator namespace or if module is part of exchange or data groups
-- Leave early if not in module, template or calculator namespace or if module is part of exchange or data groups
    if param.is_empty( currentPageName ) and (
if param.is_empty( currentPageName ) and (
        ( not arr.contains( {'Module', 'Template', 'Calculator'}, title.nsText ) ) or
( not arr.contains( {'Module', 'Template', 'Calculator'}, title.nsText ) ) or
        ( title.nsText == 'Module' and ( arr.contains( {'Exchange', 'Exchange historical', 'Data'}, title.text:match( '^(.-)/' ) ) ) )
( title.nsText == 'Module' and ( arr.contains( {'Exchange', 'Exchange historical', 'Data'}, title.text:match( '^(.-)/' ) ) ) )
    ) then
) then
        return ''
return ''
    end
end


    currentPageName = param.default_to( currentPageName, title.fullText )
currentPageName = param.default_to( currentPageName, title.fullText )
    currentPageName = string.gsub( currentPageName, '/[Dd]oc$', '' )
currentPageName = string.gsub( currentPageName, '/[Dd]oc$', '' )
    currentPageName = formatPageName( currentPageName )
currentPageName = formatPageName( currentPageName )
    addCategories = yn( param.default_to( addCategories, title.subpageText~='doc' ) )
    moduleIsUsed = yn( param.default_to( isUsed, false ) )


    if title.text:lower():find( 'sandbox' ) then
if (addCategories == nil) then
        moduleIsUsed = true -- Don't show sandbox modules as unused
addCategories = title.subpageText~='doc'
    end
end
addCategories = yn(addCategories)
-- Don't show module as unused if isUsed=true or on a sandbox page
moduleIsUsed = yn(isUsed) or false
if title.text:lower():find( 'sandbox' ) then
moduleIsUsed = true
end


    if currentPageName:find( '^Template:' ) or currentPageName:find( '^Calculator:' ) then
if currentPageName:find( '^Template:' ) or currentPageName:find( '^Calculator:' ) then
        local invokeList = getInvokeCallList( currentPageName )
local ok, invokeList = pcall(getInvokeCallList, currentPageName);
        return formatInvokeCallList(currentPageName, addCategories, invokeList)
if ok then
    end
return formatInvokeCallList(currentPageName, addCategories, invokeList);
else
return userError(invokeList);
end
end


    local whatTemplatesLinkHere, whatModulesLinkHere = dpl.ask( {
local whatTemplatesLinkHere, whatModulesLinkHere = dpl.ask( {
        namespace = 'Template|Calculator',
namespace = 'Template|Calculator',
        linksto = currentPageName,
linksto = currentPageName,
        distinct = 'strict',
distinct = 'strict',
        ignorecase = true,
ordermethod = 'title',
        ordermethod = 'title',
allowcachedresults = true,
        allowcachedresults = true,
cacheperiod = 604800 -- One week
        cacheperiod = 604800 -- One week
}, {
    }, {
namespace = 'Module',
        namespace = 'Module',
linksto = currentPageName,
        linksto = currentPageName,
nottitlematch = '%/doc|Exchange/%|Exchange historical/%|Data/%|' .. currentPageName:gsub( 'Module:', '' ),
        nottitlematch = '%/doc|Exchange/%|Exchange historical/%|Data/%|' .. currentPageName:gsub( 'Module:', '' ),
distinct = 'strict',
        distinct = 'strict',
ordermethod = 'title',
        ignorecase = true,
allowcachedresults = true,
        ordermethod = 'title',
cacheperiod = 604800 -- One week
        allowcachedresults = true,
} )
        cacheperiod = 604800 -- One week
    } )


    local lists = getRequireList( currentPageName, true )
local ok, lists = pcall(getRequireList, currentPageName, true);
if not ok then
return userError(lists);
end


    local requireList = arr.map( lists.requireList, function ( moduleName )
local requireList = arr.map( lists.requireList, function ( moduleName )
        if moduleName:find( '%%' ) then
if moduleName:find( '%%' ) then
            return formatDynamicQueryLink( moduleName )
return formatDynamicQueryLink( moduleName )
        elseif builtins[moduleName] then
elseif builtins[moduleName] then
            return '[[' .. builtins[moduleName].link .. '|' .. moduleName .. ']]'
return '[[' .. builtins[moduleName].link .. '|' .. moduleName .. ']]'
        else
else
            return '[[' .. moduleName .. ']]'
return '[[' .. moduleName .. ']]'
        end
end
    end )
end )


    local loadDataList = arr.map( lists.loadDataList, function ( moduleName )
local loadDataList = arr.map( lists.loadDataList, function ( moduleName )
        if moduleName:find( '%%' ) then
if moduleName:find( '%%' ) then
            return formatDynamicQueryLink( moduleName )
return formatDynamicQueryLink( moduleName )
        else
else
            return '[[' .. moduleName .. ']]'
return '[[' .. moduleName .. ']]'
        end
end
    end )
end )


    local loadJsonDataList = arr.map( lists.loadJsonDataList, function ( moduleName )
local loadJsonDataList = arr.map( lists.loadJsonDataList, function ( moduleName )
        if moduleName:find( '%%' ) then
if moduleName:find( '%%' ) then
            return formatDynamicQueryLink( moduleName )
return formatDynamicQueryLink( moduleName )
        else
else
            return '[[' .. moduleName .. ']]'
return '[[' .. moduleName .. ']]'
        end
end
    end )
end )


    local usedTemplateList = arr.map( lists.usedTemplateList, function( templateName )
local usedTemplateList = arr.map( lists.usedTemplateList, function( templateName )
        if string.find( templateName, ':' ) then -- Real templates are prefixed by a namespace, magic words are not
if string.find( templateName, ':' ) then -- Real templates are prefixed by a namespace, magic words are not
            return '[['..templateName..']]'
return '[['..templateName..']]'
        else
else
            return "'''&#123;&#123;"..templateName.."&#125;&#125;'''" -- Magic words don't have a page so make them bold instead
return "'''&#123;&#123;"..templateName.."&#125;&#125;'''" -- Magic words don't have a page so make them bold instead
        end
end
    end )
end )


    local res = {}
local res = {}


    table.insert( res, formatInvokedByList( currentPageName, addCategories, whatTemplatesLinkHere ) )
table.insert( res, formatInvokedByList( currentPageName, addCategories, whatTemplatesLinkHere ) )
    table.insert( res, formatImportList( currentPageName, requireList, 'require', "'''%s''' requires %s.", addCategories and 'Modules requiring modules' ) )
table.insert( res, formatImportList( currentPageName, requireList, 'require', "'''%s''' requires %s.", addCategories and 'Modules requiring modules' ) )
    table.insert( res, formatImportList( currentPageName, loadDataList, 'loadData', "'''%s''' loads data from %s.", addCategories and 'Modules using data' ) )
table.insert( res, formatImportList( currentPageName, loadDataList, 'loadData', "'''%s''' loads data from %s.", addCategories and 'Modules using data' ) )
    table.insert( res, formatImportList( currentPageName, loadJsonDataList, 'loadJsonData', "'''%s''' loads data from %s.", addCategories and 'Modules using data' ) )
table.insert( res, formatImportList( currentPageName, loadJsonDataList, 'loadJsonData', "'''%s''' loads data from %s.", addCategories and 'Modules using data' ) )
    table.insert( res, formatUsedTemplatesList( currentPageName, addCategories, usedTemplateList ) )
table.insert( res, formatUsedTemplatesList( currentPageName, addCategories, usedTemplateList ) )
    table.insert( res, formatRequiredByList( currentPageName, addCategories, whatModulesLinkHere ) )
table.insert( res, formatRequiredByList( currentPageName, addCategories, whatModulesLinkHere ) )


    if addCategories then
if addCategories then
        local extraCategories = arr.map( lists.extraCategories, function( categoryName )
local extraCategories = arr.map(lists.extraCategories, function( categoryName)
            return "[[Category:" .. categoryName .. "]]"
return "[[Category:" .. categoryName .. "]]";
        end )
end);


        table.insert( res, table.concat( extraCategories ) )
table.insert(res, table.concat(extraCategories));
    end
end


    if not moduleIsUsed then
if not moduleIsUsed then
        table.insert( res, 1, messageBoxUnused( currentPageName:gsub( 'Module:', '' ), addCategories ) )
table.insert( res, 1, messageBoxUnused( currentPageName:gsub( 'Module:', '' ), addCategories ) )
    end
end


    return table.concat( res )
return table.concat( res )
end
end


return p
return p