Module:DependencyList

From [N8]
Revision as of 17:00, 17 February 2020 by Banri (talk | contribs) (Created page with "local p = {} local libraryUtil = require( 'libraryUtil' ) local enum = require( 'Module:Enum' ) local yn = require( 'Module:Yesno' ) local param = require( 'Module:Paramtest'...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Lua error at line 155: attempt to index a nil value.

Place {{No documentation}} at the top of the documentation page.

This template should be used when there is no documentation for a Module. The template will attempt to auto detect and link the require()/mw.loadData() depedency list. If you want to supress the auto generated dependency list, use {{No documentation|DependencyList=no}}


local p = {}
local libraryUtil = require( 'libraryUtil' )
local enum = require( 'Module:Enum' )
local yn = require( 'Module:Yesno' )
local param = require( 'Module:Paramtest' )
local moduleIsUsed = false
local MAX_DYNAMIC_REQUIRE_LIST_LENGTH = 30
local dynamicRequireListQueryCache = {}

--- Used in case 'require( varName )' is found. Attempts to find a string value stored in 'varName'.
---@param content string    @The content of the module to look in as a string
---@param varName string
---@return string
local function substVarValue( content, varName )
    if varName:find( "%b''" ) or varName:find( '%b""' ) then -- Look for balanced quotes
        return varName -- Is already a string
    else
    	local res = content:match( varName .. '%s*=%s*(%b""%s-%.*)' ) or content:match( varName .. "%s*=%s*(%b''%s-%.*)" ) or ''
    	if res:find( '^[Mm]odule:[%w%s_]+$' ) and not res:find( '%.' ) then
    		return mw.text.trim( res )
    	else
        	return ''
        end
    end
end

--- Used in case a construct like 'require( "Module:wowee/" .. isTheBest )' is found.
--- Will return a list of pages which satisfy this pattern where 'isTheBest' can take any value.
---@param query string
---@return string[]     @Sequence of strings
local function getDynamicRequireList( query )
    query = mw.text.split( query, '..', true )
    query = enum.map( query, function(x) return mw.text.trim(x) end )
    query = enum.map( query, function(x) return (x:match('^[\'\"]([^\'\"]+)[\'\"]$') or '%') end )
    query = table.concat( query )
    query = query:gsub( '^[Mm]odule:', '' )

    if query:lower():find( '^exchange/' ) then
        return { 'Module:' .. query }   -- This format will later be used by formatDynamicQueryLink()
    end

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

    local getDynamicRequireListDpl =
[=[
{{#dpl:
|namespace = Module
|titlematch = %s
|nottitlematch = %%/doc¦%%sandbox%%¦%s/%%
|format = ,@@%%PAGE%%,,
|noresultsheader = @@
|distinct = strict
|ignorecase = true
|ordermethod = title
|allowcachedresults = true
|count = %d
|skipthispage = no
}}]=]

    getDynamicRequireListDpl = getDynamicRequireListDpl:format( query, query, MAX_DYNAMIC_REQUIRE_LIST_LENGTH + 1 )
    local list = mw.getCurrentFrame():preprocess( getDynamicRequireListDpl )
    list = mw.text.split( list, '@@', true )
    list = enum.reject( list, function(x) return x=='' end )

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

    dynamicRequireListQueryCache[ query ] = list

    return list
end

--- Returns a list of modules loaded and required by module 'moduleName'.
---@param moduleName string
---@return string[], string[]
local function getRequireList( moduleName )
    local content = mw.title.new( moduleName ):getContent()
    local requireList = {}
    local loadDataList = {}

    assert( param.has_content( content ), string.format( '%s does not exist', moduleName ) )
    
    content = content:gsub( '%-%-%[(=-)%[.-%]%1%]', '' ):gsub( '%-%-[^\n]*', '' )

    for match in string.gmatch( content, 'require%s*%(([^%)]+)' ) do
        match = mw.text.trim( match )
        match = substVarValue( content, match )

        if match:find( '%.%.' ) then
            for _, x in ipairs( getDynamicRequireList( match ) ) do
                table.insert( requireList, x )
            end
        elseif match ~= '' then
            match = match:gsub( '[\"\']', '' ):gsub( '_', ' ' )

            if match == 'libraryUtil' then
                match = 'Module:LibraryUtil'
            end

            table.insert( requireList, match )
        end
    end

    for match in string.gmatch( content, 'mw%.loadData%s*%(([^%)]+)' ) do
        match = mw.text.trim( match )
        match = substVarValue( content, match )

        if match:find( '%.%.' ) then
            for _, x in ipairs( getDynamicRequireList( match ) ) do
                table.insert( loadDataList, x )
            end
        elseif match ~= '' then
            match = match:gsub( '[\"\']', '' ):gsub( '_', ' ' )
            table.insert( loadDataList, match )
        end
    end

    for func, match in string.gmatch( content, 'pcall%s*%(([^,]+),([^%),]+)' ) do
        func = mw.text.trim( func )
        match = mw.text.trim( match )

        if func == 'require' then
            for _, x in ipairs( getDynamicRequireList( match ) ) do
                table.insert( requireList, x )
            end
        elseif func == 'mw.loadData' then
            for _, x in ipairs( getDynamicRequireList( match ) ) do
                table.insert( loadDataList, x )
            end
        end
    end

    requireList = enum.unique( requireList )
    loadDataList = enum.unique( loadDataList )
    table.sort( requireList )
    table.sort( loadDataList )

    return requireList, loadDataList
end

--- Makes the first letter of the input string upper case
---@param str string
---@return string
local function ucfirst( str )
    return str:gsub( '^.', function(c) return c:upper() end )
end

--- Returns a list with module and function names used in all '{{#Invoke:moduleName|funcName}}' found on page 'templateName'.
---@param templateName string
---@return table<string, string>[]
local function getInvokeCallList( templateName )
    local content = mw.title.new( templateName ):getContent()
    local invokeList = {}

    assert( param.has_content( content ), string.format( '%s does not exist', templateName ) )

    for moduleName, funcName in string.gmatch( content, '{{[{|safeubt:}]-#[Ii]nvoke:([^|]+)|([^}|]+)[^}]*}}' ) do
        moduleName = ucfirst( moduleName )
        moduleName = string.format( 'Module:%s', moduleName )
        moduleName = moduleName:gsub( '_', ' ' )
        table.insert( invokeList, {moduleName=moduleName, funcName=funcName} )
    end

    invokeList = enum.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 )

    return invokeList
end

---@param pageName string
---@param addCategories boolean
---@return string
local function messageBoxUnused( pageName, addCategories )
    local html = mw.html.create( 'table' ):addClass( 'messagebox obsolete plainlinks' )
    html:tag( 'td' )
        :attr( 'width', '40xp' )
        :wikitext( '[[File:Iron full helm detail old.png|center|30px|link=]]' )
    :done()
    :tag( 'td' )
        :wikitext( "'''This module is unused.'''" )
        :tag( 'div' )
            :css{ ['font-size']='0.85em', ['line-height']='1.45em' }
            :wikitext( string.format( 'This module is neither invoked by a template nor required/loaded be 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 '' )
        :done()
    :done()

    return tostring( html )
end

--- Creates a link to [[Special:Search]] showing all pages found by getDynamicRequireList() in case it found more than MAX_DYNAMIC_REQUIRE_LIST_LENGTH pages.
---@param query string      @This will be in a format like 'Module:Wowee/%' or 'Module:Wowee/%/data'
---@return string
local function formatDynamicQueryLink( query )
    local prefix = query:match( '^([^/]+)' )
    local linkText = query:gsub( '%%', '&lt; ... &gt;' )

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

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

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

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

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

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

    if compact then
        invokeList = enum.map( invokeList, function(x) return '[['..x.moduleName..']]' end )

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

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

    return table.concat( res )
end

---@param moduleName string
---@param compact boolean
---@param addCategories boolean
---@param whatLinksHere string    @A list generated by a dpl of pages in the Template or Calculator namespace which link to moduleName. Pages are delimited by @@.
---@return string
local function formatInvokedByList( moduleName, compact, addCategories, whatLinksHere )
    local category = addCategories and '[[Category:Template invoked modules]]' or ''
    whatLinksHere = mw.text.split( whatLinksHere, '@@' )
    whatLinksHere = enum.reject( whatLinksHere, function(x) return not x:find('%S') end )
    whatLinksHere = enum.reject( whatLinksHere, function(x) return x:find('/doc$') end )
    local templateData = enum.map( whatLinksHere, function(x) return {templateName=x, invokeList=getInvokeCallList(x)} end )
    templateData = enum.filter( templateData, function(x) return enum.any( x.invokeList, function(y) return y.moduleName==moduleName end ) end )

    if #templateData > 0 then
        moduleIsUsed = true

        if compact then
            templateData = enum.map( templateData, function(x) return ('[['..x.templateName..']]') end )
            templateData = enum.unique( templateData )

            return string.format(
                "<div class='seealso'>'''''%s''' is invoked by %s''.</div>%s",
                moduleName,
                mw.text.listToText( whatLinksHere, ', ', ' and ' ),
                category
            )
        else
            local res = {}

            for _, template in ipairs( templateData ) do
                for _, invoke in ipairs( template.invokeList ) do
                    table.insert( res, string.format(
                        "<div class='seealso'>'''''%s's''' function '''%s''' is invoked by [[%s]]''.</div>",
                        moduleName,
                        invoke.funcName,
                        template.templateName
                    ) )
                end
            end

            table.sort( res )
            table.insert( res, category )

            return table.concat( res )
        end
    end

    return ''
end

---@param moduleName string
---@param compact boolean
---@param addCategories boolean
---@param whatLinksHere string      @A list generated by a dpl of pages in the Module namespace which link to moduleName. Pages are delimited by @@.
---@return string
local function formatRequiredByList( moduleName, compact, addCategories, whatLinksHere )
    whatLinksHere = mw.text.split( whatLinksHere, '@@' )
    whatLinksHere = enum.reject( whatLinksHere, function(x) return not x:find('%S') end )

    local childModuleData = enum.map( whatLinksHere, function ( title )
        local requireList, loadDataList = getRequireList( title )
        return {name=title, requireList=requireList, loadDataList=loadDataList}
    end )

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

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

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

    if compact then
        local res = ''

        if #requiredByList > 0 then
            res = string.format(
                "<div class='seealso'>'''''%s''' is required by %s''.</div>%s",
                moduleName,
                mw.text.listToText( requiredByList, ', ', ' and ' ),
                (addCategories and '[[Category:Modules required by modules]]' or '')
            )
        end

        if #loadedByList > 0 then
            res = res .. string.format(
                "<div class='seealso'>'''''%s''' is loaded by %s''.</div>%s",
                moduleName,
                mw.text.listToText( loadedByList, ', ', ' and ' ),
                (addCategories and '[[Category:Module data]]' or '')
            )
        end

        return res
    else
        local res = {}

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

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

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

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

        return table.concat( res )
    end

    return ''
end

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

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

    local title = mw.title.getCurrentTitle()

    if param.is_empty( currentPageName ) and (
    ( title.nsText ~= 'Module'  and title.nsText ~= 'Template' and title.nsText ~= 'Calculator') or
    ( title.nsText == 'Module' and ( title.text:find( '^Exchange/' ) or title.text:find( '^Exchange historical/' ) or title.text:find( '^Sandbox/' ) ) ) ) then
        return ''
    end

    currentPageName = param.default_to( currentPageName, title.fullText )
    currentPageName = string.gsub( currentPageName, '/[Dd]oc$', '' )
    currentPageName = string.gsub( currentPageName, '_', ' ' )
    currentPageName = ucfirst( currentPageName:gsub( ':(.)', function(c) return ':'..c:upper() end ) )
    addCategories = yn( param.default_to( addCategories, title.subpageText~='doc' ) )
    compact = yn( param.default_to( compact, false ) )
    moduleIsUsed = yn( param.default_to( isUsed, false ) )

    if currentPageName:find( '^Template:' ) or currentPageName:find( '^Calculator:' ) then
        local invokeList = getInvokeCallList( currentPageName )
        return formatInvokeCallList( currentPageName, compact, addCategories, invokeList )
    end

    local invokedByDpl =
[=[
{{#dpl:
|namespace = Template¦Calculator
|linksto = %s
|format = ,@@%%PAGE%%,,
|noresultsheader = @@
|distinct = strict
|ignorecase = true
|ordermethod = title
|allowcachedresults = true
}}]=]

    local requiredByDpl =
[=[
{{#dpl:
|namespace = Module
|linksto = %s
|nottitlematch = %%/doc¦%%sandbox%%¦Exchange/%%¦Exchange historical/%%¦%s
|format = ,@@%%PAGE%%,,
|noresultsheader = @@
|distinct = strict
|ignorecase = true
|ordermethod = title
|allowcachedresults = true
}}]=]

    invokedByDpl = invokedByDpl:format( currentPageName )
    requiredByDpl = requiredByDpl:format( currentPageName, currentPageName:gsub( 'Module:', '' ) )

    local data = mw.getCurrentFrame():preprocess( invokedByDpl .. '$$' .. requiredByDpl )
    local invokedByList, requiredByList = unpack( mw.text.split( data, '$$', true ) )
    invokedByList = formatInvokedByList( currentPageName, compact, addCategories, invokedByList )
    requiredByList = formatRequiredByList( currentPageName, compact, addCategories, requiredByList )

    local requireList, loadDataList = getRequireList( currentPageName )

    requireList = enum.map( requireList, function ( moduleName )
        if moduleName:find( '%%' ) then
            return formatDynamicQueryLink( moduleName )
        else
            return '[[' .. moduleName .. ']]'
        end
    end )

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

    local res = {}

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

    table.insert( res, invokedByList )

    if compact then
        if #requireList > 0 then
            table.insert( res, string.format(
                "<div class='seealso'>'''''%s''' requires %s.''</div>%s",
                currentPageName,
                mw.text.listToText( requireList, ', ', ' and ' ),
                (addCategories and '[[Category:Modules requiring modules]]' or '')
            ) )
        end

        if #loadDataList > 0 then
            table.insert( res, string.format(
                "<div class='seealso'>'''''%s''' loads data from %s.''</div>%s",
                currentPageName,
                mw.text.listToText( loadDataList, ', ', ' and ' ),
                (addCategories and '[[Category:Modules using data]]' or '')
            ) )
        end
    else
        for _, requiredModuleName in ipairs( requireList ) do
            table.insert( res, string.format(
                "<div class='seealso'>'''''%s''' requires %s.''</div>",
                currentPageName,
                requiredModuleName
            ) )
        end

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

        for _, loadedModuleName in ipairs( loadDataList ) do
            table.insert( res, string.format(
                "<div class='seealso'>'''''%s''' loads data from %s.''</div>",
                currentPageName,
                loadedModuleName
            ) )
        end

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

    table.insert( res, requiredByList )

    return table.concat( res )
end

return p