יחידה:ParamValidator: הבדלים בין גרסאות בדף
מ עיצוב |
לדרישת הקהל |
||
| שורה 29: | שורה 29: | ||
after replacing the follwing tokens: | after replacing the follwing tokens: | ||
-- "templatename" is replaced with the actual template name, | -- "templatename" is replaced with the actual template name, | ||
-- "tname-naked" is replaced with the naked template name, i.e. without colon and namespace | |||
-- "paramname" is replaced by a comma-separated list of parameters offending the rule. | -- "paramname" is replaced by a comma-separated list of parameters offending the rule. | ||
-- "paramandvalue" is replaced by comma-separated list of "name: value" pairs of parameters and values | -- "paramandvalue" is replaced by comma-separated list of "name: value" pairs of parameters and values | ||
| שורה 92: | שורה 93: | ||
local td_p = templatedata and templatedata.params -- now we have options, template args, and td params metadata. we can work now. | local td_p = templatedata and templatedata.params -- now we have options, template args, and td params metadata. we can work now. | ||
local report = '' | local report = '' | ||
local wrap_report = function() | local wrap_report = function() | ||
if empty( report ) then return '' end | if empty( report ) then return '' end | ||
report = ( options['wrapper-prefix'] or "<div class = 'paramvalidator-wrapper'>" ) | |||
.. report | .. report | ||
.. ( options['wrapper-suffix'] or "</div>" ) | .. ( options['wrapper-suffix'] or "</div>" ) | ||
local naked = mw.title.new(template_name)['text'] | |||
report = mw.ustring.gsub( raw, 'tname-naked', template_name ) | |||
report = mw.ustring.gsub( report, 'templatename', template_name ) | |||
return report | |||
end | end | ||
| שורה 110: | שורה 115: | ||
local replace_macros = function( s, param_names ) | local replace_macros = function( s, param_names ) | ||
local paramstr, paramvaluestr, paramvaluetab = '', '', {} | local paramstr, paramvaluestr, paramvaluetab = '', '', {} | ||
if type( param_names ) == 'table' then | if type( param_names ) == 'table' then | ||
paramstr = table.concat( param_names, ', ' ) | paramstr = table.concat( param_names, ', ' ) | ||
גרסה מ־23:37, 29 במרץ 2016
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:
- several tokens are replaced with calculated values. these are described below.
- 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.
- 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 module is based on idea and original code of [[User:IKhitron]].
the source of this module is in //he.wikipedia.org/wiki/Module:ParamValidator
it exports a single function: validateParams, which expects a frame object
it retrieves the template's templatedata, and uses it to validate the parameters passed to the template.
if any violations found, it returns am appropriate string. this string will typically include some maintenance category, and/or error message.
the operation of the module is controlled by a single parameter passed to it. this string should be valid JSON describing the actions.
the fields of this structure has the following keys, with string or null value:
* "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
* "any": at least one of the above properies has non-empty value, and the corresponding error actually exists.
* "multiple": more than one of the above properies (not including "any") has non-empty value, and the corresponding error actually exists.
if any of these error-conditions exists, and "options" has non-empty value for the corresponding key, will be appended to the output,
after replacing the follwing tokens:
-- "templatename" is replaced with the actual template name,
-- "tname-naked" is replaced with the naked template name, i.e. without colon and namespace
-- "paramname" is replaced by a comma-separated list of parameters offending the rule.
-- "paramandvalue" is replaced by comma-separated list of "name: value" pairs of parameters and values
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:
* "ignore": list (in square brackets) of parameter names to ignore, both in templatedata and actual parameters. all names should be quoted.
* "doc-subpage": can be either a string, or a list (in square bracktes) of strings, indicating subpages of the template
that may contain templatedata.
* "skip-empty-numeric": if a quoted number, the module will ignore 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>")
typically, this JSON structure will be placed in a special template, and retrieved for the module-use like so:
<includeonly>{{#invoke:ParamValidatoe | validateParams | options = {{PV Default Values}} }}</includeonly>
this code is to be placed at the very beginning of the page of the template whose uses are to be validated.
several such options pages may exist, so the user can decide which validation regime to use with each template, by invoking it and passing
the appropriate one for the "options" parameter.
]=]
function extract_options( frame )
local options
local args = frame.args
local options = not empty( args.options ) and mw.text.jsonDecode( args.options ) or {}
local n = 1
while not empty( args['options' .. n] ) do
local more = mw.text.jsonDecode( args['options' .. n] )
for k, v in pairs(more) do options[k] = v end
n = n + 1
end
return options
end
function build_namelist( options, template_name )
local res = { template_name }
local sp = options and options['doc-subpage']
if sp then
if type( sp ) == 'string' then sp = { sp } end
for _, p in ipairs( sp ) do table.insert( res, template_name .. '/' .. p ) end
end
return res
end
function empty( s )
return not s or type( s ) == 'string' and mw.text.trim( s ) == ''
end
function validateParams( frame )
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 td_p = templatedata and templatedata.params -- now we have options, template args, and td params metadata. we can work now.
local report = ''
local wrap_report = function()
if empty( report ) then return '' end
report = ( options['wrapper-prefix'] or "<div class = 'paramvalidator-wrapper'>" )
.. report
.. ( options['wrapper-suffix'] or "</div>" )
local naked = mw.title.new(template_name)['text']
report = mw.ustring.gsub( raw, 'tname-naked', template_name )
report = mw.ustring.gsub( report, 'templatename', template_name )
return report
end
local ignore = function( p_name )
for _, p in ipairs( options.ignore or {} ) do
if tostring( p ) == tostring( p_name ) then return true end
end
return false
end
local replace_macros = function( s, param_names )
local paramstr, paramvaluestr, paramvaluetab = '', '', {}
if type( param_names ) == 'table' then
paramstr = table.concat( param_names, ', ' )
for _, param_name in ipairs( param_names ) do
if not empty( t_args[param_name] ) then
table.insert( paramvaluetab, param_name .. ': ' .. mw.text.trim( t_args[param_name] ) )
end
end
elseif type( param_names ) == 'string' then
paramstr = param_names
end
if param_names then
s = mw.ustring.gsub( s, 'paramname', paramstr )
end
if #paramvaluetab then
s = mw.ustring.gsub( s, 'paramandvalue', table.concat( paramvaluetab, ', ' ) )
end
return s
end
local report_params = function( key, param_names )
if options[key] then
report = report .. replace_macros( options[key], param_names )
end
end
local report_table = function( name, tbl )
if #tbl ~= 0 then report_params( name, tbl ) end
end
if not templatedata then
report_params( 'no-templatedata' )
report_params( 'any' )
return wrap_report()
end
-- from this point on, we know templatedata is valid.
-- undeclared and deprecated contains only non-empty parameters.
-- empty_undeclared contains undeclared parameters with no value
local undeclared, empty_undeclared, empty_required, deprecated, empty_deprecated = {}, {}, {}, {}, {}
local undeclared_numeric, empty_undeclared_numeric = {}, {}
local lists_and_names = {
[undeclared] = 'undeclared',
[empty_undeclared] = 'empty-undeclared',
[undeclared_numeric] = 'undeclared-numeric',
[empty_undeclared_numeric] = 'empty-undeclared-numeric',
[deprecated] = 'deprecated',
[empty_deprecated] = 'empty-deprecated',
[empty_required] = 'empty-required'
}
-- groups to make the loop simpler.
local undec = { [true] = { [true] = empty_undeclared_numeric, [false] = undeclared_numeric }, [false] = { [true] = empty_undeclared, [false] = undeclared } }
local dep = { [true] = empty_deprecated, [false] = deprecated }
local skip_empty_numeric = tonumber( options['skip-empty-numeric'] ) or 0
-- DO THE WORK: if paramete does not appear in TD, add it to undeclared or empty-undeclared.
-- if it does appear, check if it's deprecated, and if so, add it to deprecated or empty-deprecated
for p_name, value in pairs( t_args ) do
if not ignore( p_name ) then
local noval = empty( value )
if not td_p[p_name] then -- fill undeclared or undeclared_empty, depends on noval
local numeric = tonumber( p_name ) ~= nil
local skip = numeric and noval and tonumber( p_name ) <= skip_empty_numeric -- special request of bora
if not skip then
table.insert( undec[numeric][noval], p_name )
end
elseif td_p[p_name].deprecated then
table.insert( dep[noval], p_name )
end
end
end
-- DO MORE WORK: collect "required" parameters that do not exist, or have empty value.
for p_name, param in pairs( td_p ) do
if not ignore( p_name ) and param.required and empty( t_args[p_name] ) then
table.insert( empty_required, p_name )
end
end
-- WORK IS DONE. report the errors.
local offenders = 0
for list, name in pairs( lists_and_names ) do
if #list ~= 0 and not empty( options[name] ) then
offenders = offenders + 1
report_table( name, list )
end
end
if offenders ~= 0 then report_params( 'any' ) end
if offenders > 1 then report_params( 'multiple' ) end
return wrap_report()
end
return {
['validateparams'] = validateParams
}