Модуль:Cat main

Сүлөөтэ Нэбтэрхы Толи — Википеэдиһээ

Для документации этого модуля может быть создана страница Модуль:Cat main/doc

local p = {}
local get_args = require('Module:Arguments').getArgs
local mHatnote = require('Module:Hatnote')
local category_ns_number = 14

local function get_property(args)
	local res = mw.getCurrentFrame():expandTemplate{title = 'wikidata', args = args}
	return res ~= '' and res or nil
end

local function get_link_target(wikitext)
	local target = wikitext:match('%[%[([^%]%|]+)%]') or wikitext:match('%[%[([^%|]+)%|')
	return {
		target = target or wikitext,
		contains_link = target ~= nil
	}
end

local function get_catmain_from_wikidata(properties)
	local values = {}
	for _, property in pairs(properties) do
		values[#values + 1] = get_property{property}
		values[#values + 1] = get_property{property, plain = true}
	end
	
	if #values > 0 then
		for _, value in pairs(values) do
			local link_target = get_link_target(value)
			local title = mw.title.new(link_target.target)
			if title and title.exists then
				return {
					title = value, 
					exists = true,
					missed = not link_target.contains_link
				}
			end
		end
		
		return {title = values[1], exists = false}
	end
	
	return nil
end

function p.main(frame)
	local args = get_args(frame)
	local current_title = mw.title.getCurrentTitle()
	local categories = mHatnote.define_categories{
		by_wikidata = 'Википедия:Категории с основной статьёй из Викиданных',
		by_pagename = 'Википедия:Категории c основной статьёй, которая не указана явно',
		missed = 'Википедия:Категории с существующей основной статьёй, не указанной в Викиданных'
	}
	local hatnote_args = setmetatable({
		prefix = 'Основная статья:',
		prefix_plural = 'Основные статьи:',
		bold_links = true
	}, { __index = args })
	local overridden_categories = {}
	local nocat = args.nocat
	
	if current_title.namespace == category_ns_number then
		hatnote_args.id = 'catmore'
		overridden_categories.red_link = 'Википедия:Категории без основных статей'
		
		local first_title_exists
		if not hatnote_args[1] then
			local catmain = get_catmain_from_wikidata{'p301', 'p1753'}
			local title
			
			if catmain then
				title = catmain.title
				first_title_exists = catmain.exists
			
				categories:add('by_wikidata', nocat)
				if catmain.missed then
					categories:add('missed')
				end
			else
				title = current_title.text
				categories:add('by_pagename', nocat)
			end
			hatnote_args[1] = title
		end
		
		if first_title_exists == nil then
			link = mHatnote.parse_link{hatnote_args[1]}
			first_title_exists = not link or mw.title.new(link).exists
		end
		
		if not first_title_exists then
			hatnote_args.prefix = 'У этой категории нет основной статьи —'
		end
	end
	
	return mHatnote.main(hatnote_args, overridden_categories) .. categories
end

return p