לדלג לתוכן

יחידה:ParamValidator

מתוך צפונות ויקי

This module is based on idea and original code of User:IKhitron.
the source of this module is in //he.wikipedia.org/wiki/Module:ParamValidator

This module exports two functions: calculateViolations( frame, subpages ), and validateParams( frame ).

calculateViolations( frame, subpages ) finds templatedata, in template page or in one of its subpages in the list, if provided. it returns a table with the violations. if there are none, the table is empty. otherwise it has the structure

{
	violation1 = { param1 = value1, param2 = value2 },
	violation2 = { ... },
	...
}

violation1, violation2 etc. are one of the names of specific violations, as described below. param1, param2 etc. are either the names of parameter passed to the template, or defined in templatedata. value1, value2 etc. are the values passed to the template, or an empty string if no such parameter was passed.

the different violations are as follow:

  • no-templatedata
    no valid tempaltedata was found in tempalte page, or documentation subpage
  • undeclared
    named parameters with non-empty value, does not exist in templatedata
  • empty-undeclared
    named parameters with empty value, does not exist in templatedata
  • undeclared-numeric
    numeric parameters with non-empty value, does not exist in templatedata
  • empty-undeclared-numeric
    numeric parameters with empty value, does not exist in templatedata
  • deprecated
    parameters with non-empty value, marked as "deprecated" in tempaltedata
  • empty-deprecated
    parameters with empty value, marked as "deprecated" in tempaltedata
  • empty-required
    missing or empty parameter marked as "required" in tempaltedata
  • incompatible
    a non-empty parameter passed to the template, incompatible with the parameter type defined in templatedata


The second function, validateParams( frame ), can be called from the tempalte' using #invoke. it expects a parameter named "options", which contains the definition of the output. typically, it's used by placing something like so:

<includeonly>{{#invoke:ParamValidator | validateParams | options = {{PV default options}} }}</includeonly>

at the top of the template (be mindful not to add extra spaces and newlines to the template).

the options parameter should be a JSON-encoded string, defining the output, and some special behaviors. the example above assumes that a wiki page named Template:PV default options exists, and contains valid JSON string. for each of the violations defined above, "options" may define an output string, so basically, "options" looks like so:

{
	violation1: outputstring1,
	violation2: outputstring2,
	.... ,
	behavior1: some value,
	....
}

not all violations have to be defined. a violation not defined in "options" will be ignored.

when invoked, it extract "subpages" from the options parameter, and calls:

  • calculateViolations( frame, subpages )

if the returned table is empty, no violation were found, and an empty string is returned and nothing else happens.

otherwise, for each of the violations, i.e., the keys of the returned table, when "options" contains this key, the corresonding value is appended to the output.

some further processing is done:

  1. several tokens are replaced with calculated values. these are described below.
  2. some "meta" violations are calculated: when any none-ignored violation occured, the "any" meta-violation is added to the output in the same way, i.e. the string keyed by "any" in the options is appended to output with appropriate substitutions. similarly, "multiple" meta-violation is created when more than one type of non-ignored violations occured.
  3. if the output is not empty, a prefix and suffix strings are prepended and appended to it.

these are the tokens and the replacement.

  • templatename
    full template name, including namespace.
  • tname_naked
    template name without namespace.
  • paramname
    comma-separated list of parameters
  • paramandvalue
    is replaced by comma-separated list of "name: value" pairs of parameters and values

the first two are applied to the whole output, including the suffux and prefix, and the rest are applied to the individual violations, each with its own list of offending parameters and values.


the rest of the if the value of some keys is null, this error condition will be ignored, and not counted when calculating "any" and "multiple" conditions.

some other optional fields can be passed via options:

  • doc-subpage
    can be either a string, or a list (in square bracktes) of strings, indicating subpages of the template that may contain templatedata.
  • ignore
    list of patterns. any parameter whose name matches any pattern, will not considered in violation of any of the rules.
  • skip-empty-numeric
    if a quoted number, the module will ignore non-declared empty numeric parameters up to this number
  • wrapper-prefix
    openning wrapper element of outpot (defaults to <div class = 'paramvalidator-wrapper'>)
  • wrapper-suffix
    closing wrapper element of output (defaults to "</div>")

additional option parameters, named options1, options2, etc. can be passed. any entry defined in these options will override the previous value. a typical use may be like so:


typically, this JSON structure will be placed in a separate template, and retrieved for the module-use as shown above.

<includeonly>{{#invoke:ParamValidator | validateParams | options = {{PV default options}} | options1 = {"key":"value"} }}</includeonly>

"key" can override any of the options fields described above.


--[[
this unit contains a single function.
it gets 2 optional parameters: 
	base = options base name, for the inbuilt options. if not passed, "default" is assumed.
		ATM, the only other viable value is "quiet" (without quotes). this is useful when complete substitution of all the outputs is desired.
	options = json-coded string that describes the desired output for each error condition, and some more site-specific settings,
	such as the default "Documentation" subpage, so the function can try to look for tempaltedata in the correct subpages.
	
	there are several error conditions, and a the options define the desired output for each. 
	if no output is desired for specific option, give the appropriate key empty string value.
	the error conditions are: 
		* "no-templatedata": no valid tempaltedata was found in tempalte page, or documentation subpage 
		* "undeclared": parameters with non-empty value, which do not exist in templatedata
		* "empty-undeclared": parameters with empty value, which do not exist in templatedata
		* "empty-required": parameters marked as "required" in tempaltedata have no value
		* "deprecated":  parameters with non-empty value, marked as "deprecated" in tempaltedata
		* "any": any of the above conditions is true. deprecated and empty-undeclared will be ignored if corresponding option is null.

	for each condition that evaluates to true, the value of the corresponding options field is used to add to the output of the function.
	before appending this value to the output, 2 substitutions occur: the tokens "templatename" and "paramname" in the value are 
	substituted with the actual template name, and a comma-joined list of the parameters violating the , where relevant.

	there is one more useful option: 
		* "doc-subpage": use this field to tell what is the default "Documentation" subpage on your wiki. this enable the system to 
			look for tempalatedata in the appropriate subpage.
usage:
place 
<includeonly>{{#invoke:ParamValidator | validateParams }}</includeonly>
at the very bigining of the tempalate (not mandatory - it can be in any part of the template, but it's recommended).
	
<includeonly>{{#invoke:ParamValidator | validateParams | base = quiet }}</includeonly>
will use the "quiet" inbuilt option. the default behavior in this case is to only emit a html comment to the page if any error exists.


you can pass your own options. these options will be applied above the selected (or default) inbuilt.
the options value is supplied as a json-encoded string. it is recommended to create one or two tempaltes that will return 
the desired options (in valid json format) so the use will be like so: 

<
includeonly>{{#invoke:ParamValidator | validateParams | options = {{validator-options}} }}</includeonly>
use the "default" option as template for the template to be used on your site.

]]

local inbuilt_options = {
	['default'] = [=[
	{ 
		"no-templatedata": "[[Category:Parametererror invalid templatedata]]",
		"undeclared": "[[Category:Parametererror undeclared]][[Category:parameter undeclared templatename]]<p class='paramvalidator-error'>templatename has undeclared parameters: paramname</p>",
		"empty-undeclared": "",
		"empty-required": "[[Category:Parametererror empty required]][[Category:Parametererror empty equired templatename]]<p class='paramvalidator-error'>templatename misses required parameters: paramname</p>",
		"deprecated": "[[Category:Parametererror deprecated]][[Category:Parametererror deprecated templatename]]<p class='paramvalidator-error'>templatename uses deprecated parameters: (paramname)</p>",
		"any": "[[Category:Parametererror]]",
		"doc-subpage": "Documentation"
	}
	]=]
	,
	['cat-only'] = [=[
	{ 
		"no-templatedata": "[[Category:Parametererror invalid templatedata]]",
		"undeclared": "[[Category:Parametererror undeclared]][[Category:parameter undeclared templatename]]",
		"empty-undeclared": "",
		"empty-required": "[[Category:Parametererror empty required]][[Category:Parametererror empty equired templatename]]",
		"deprecated": "[[Category:Parametererror deprecated]][[Category:Parametererror deprecated templatename]]",
		"any": "[[Category:Parametererror]]",
		"doc-subpage": "Documentation"
	}
	]=]
	,
	['message-only'] = [=[
	{ 
		"no-templatedata": "<p class='paramvalidator-error'>Missing tempatedata in templatename</p>",
		"undeclared": "<p class='paramvalidator-error'>templatename has undeclared parameters: (paramname)</p>",
		"empty-undeclared": "<p class='paramvalidator-error'>templatename has empty undeclared parameters: (paramname)</p>",
		"empty-required": "<p class='paramvalidator-error'>templatename misses required parameters: (paramname)</p>",
		"deprecated": "<p class='paramvalidator-error'>templatename uses deprecated parameters: (paramname)</p>",
		"any": "<p class='paramvalidator-error'>Some errors found in templatename parameters</p>",
		"doc-subpage": "Documentation"
	}
	]=]
	,
	['comments'] = [=[
	{ 
		"no-templatedata": "<!-- Missing tempatedata in templatename -->",
		"undeclared": "<!-- templatename has undeclared parameters: (paramname) -->",
		"empty-undeclared": "<!-- templatename has empty undeclared parameters: (paramname) -->",
		"empty-required": "<!-- templatename misses required parameters: (paramname) -->",
		"deprecated": "<!-- templatename uses deprecated parameters: (paramname) -->",
		"any": "<!-- Some errors found in templatename parameters -->",
		"doc-subpage": "Documentation"
	}
	]=]
	,
	quiet = [[
	{ "any": "<!-- Some template parameters errors exist, for tempplate templatename -->" }
	]]
}

function extract_options( frame )
	local options
	local args = frame.args
	local base = args.base or 'default'
	
	local options = not empty( args.options ) and mw.text.jsonDecode( args.options ) or {}
 
	local base_options = not empty( inbuilt_options[base] ) and mw.text.jsonDecode( inbuilt_options[base] ) or {} 
	for k, v in pairs( base_options ) do
		options[k] = options[k] or v
	end
	local n = 1
	while not empty( args['options' .. n] ) do
		local more = mw.text.jsonDecode( inbuilt_options[base] )
		for k, v in pairs(more) do options[k] = v end
		n = n + 1
	end
	
	return options
end

function build_namelist( options, template_name )
	if options and options['doc-subpage'] then
		return { template_name, template_name .. '/' .. options['doc-subpage'] }
	end
	return template_name
end

function empty( s )
	return not s or type( s ) == 'string' and mw.text.trim( s ) == ''
end

function validateParams( frame )
	local report = ''
	local options = extract_options( frame )
	local t_frame = frame:getParent()

	local t_args, template_name = t_frame.args, t_frame:getTitle()
	local td_source = build_namelist( options, template_name )
	local templatedata = require( 'Module:ReadTd' ).ReadTemplateData( td_source )

	local wrapreport = function()
		return not empty( report ) and "<div class = 'paramvalidator-wrapper'>" .. report .. "</div>" or ''
	end


	local ignore = function( p_name )
		for _, p in ipairs( options.ignore or {} ) do
			if p == p_name then return true end
		end
		return false
	end
	
	local replace_macros = function( s, param_names )
		s = mw.ustring.gsub( s, 'templatename', template_name )
		
		if type( param_names ) == 'table' then 
			param_names = table.concat( param_names, ', ' ) 
		end
		
		if param_names then
			s = mw.ustring.gsub( s, 'paramname', param_names )
		end
		
		return s
	end
	
	local report_params = function( key, param_names )
		if type( key ) == 'string' and options[key] then 
			report = report .. replace_macros( options[key], param_names )
		elseif type( key ) == 'table' then -- recursive call for each of the values in the table.
			for i, k in ipairs( kay ) do report_params( k, param_names ) end
		end
	end
	
	if not templatedata then 
		report_params( { 'no-templatedata', 'any' } )
		return wrapreport() -- from this point on, we know templatedata is valid.
	end
	
	local td_p = templatedata.params
	
	-- undeclared and deprecated contains only non-empty parameters.
	-- empty_undeclared contains undeclared parameters with no value 
	local undeclared, empty_undeclared, empty_required, deprecated = {}, {}, {}, {}
	
	for p_name, value in pairs( t_args ) do
		if not td_p[p_name] and not ignore( p_name ) then
			if empty( value ) then
				if not empty( options['empty-undeclared'] ) then
					table.insert( empty_undeclared, p_name )
				end
			else
				table.insert( undeclared, p_name )
			end
		end
	end

	-- go over templetdata parameters, find unsatisfied (missing or empty) required parameters,  
	-- and optionally (if options.deprecated exists), use of non-empty deprecated parameters. 
	for p_name, param in pairs( td_p ) do
		if param.required and empty( t_args[p_name] ) and not ignore( p_name ) then
			table.insert( empty_required, p_name )
		end
		if options.deprecated and param.deprecated and not empty( t_args[p_name] ) and not ignore( p_name ) then
			table.insert( deprecated, p_name )
		end
	end
	
	if #empty_required ~= 0 then 
		report_params( 'empty-required', empty_required )
	end
		
	if #undeclared ~= 0 then 
		report_params( 'undeclared', undeclared )
	end
	
	if #deprecated ~= 0 then
		report_params( 'deprecated', deprecated )
	end
	
	if #empty_undeclared ~= 0 then
		report_params( 'empty-undeclared', empty_undeclared )
	end
	
	if #empty_required + #undeclared + #deprecated + #empty_undeclared ~= 0 then
		report_params( 'any' )
	end
	
	return wrapreport()
end



return { 
	['validateparams'] = validateParams 
}