Módulo:Testes/Gkiyoshinishimoto/Redirect

Origem: Wikipédia, a enciclopédia livre.
-- Este módulo fornece funções para obter o destino de uma página de redirecionamento.

local p = {}

-- Obtém um objeto "mw.title", usando "pcall" para evitar a geração de erros de 'script' se 
-- estivermos acima do limite de contagem de funções caras (entre outras possíveis causas).
local function getTitle(...)
	local success, titleObj = pcall(mw.title.new, ...)
	if success then
		return titleObj
	else
		return nil
	end
end

-- Obtém o nome de uma página à qual um redirecionamento leva ou "nil" se não for um 
-- redirecionamento.
function p.getTargetFromText(text)
	local target = string.match(
		text,
		"^%s*#[Rr][Ee][Dd][Ii][Rr][Ee][Cc][Tt]%s*:?%s*%[%[([^%[%]|]-)%]%]"
	) or string.match(
		text,
		"^%s*#[Rr][Ee][Dd][Ii][Rr][Ee][Cc][Tt]%s*:?%s*%[%[([^%[%]|]-)|[^%[%]]-%]%]"
	) or string.match(
		text,
		"^%s*#[Rr][Ee][Dd][Ii][Rr][Ee][Cc][Ii][Oo][Nn][Aa][Mm][Ee][Nn][Tt][Oo]%s*:?%s*%[%[([^%[%]|]-)%]%]"
	) or string.match(
		text,
		"^%s*#[Rr][Ee][Dd][Ii][Rr][Ee][Cc][Ii][Oo][Nn][Aa][Mm][Ee][Nn][Tt][Oo]%s*:?%s*%[%[([^%[%]|]-)|[^%[%]]-%]%]"
	)
	return target and mw.uri.decode(target, 'PATH')
end

-- Obtém o destino de um redirecionamento. Se a página especificada não for um 
-- redirecionamento, retorna "nil".
function p.getTarget(page, fulltext)
	-- Obtém o objeto de título. Ambos os nomes de página e objetos de título 
	-- são permitidos como entrada.
	local titleObj
	if type(page) == 'string' or type(page) == 'number' then
		titleObj = getTitle(page)
	elseif type(page) == 'table' and type(page.getContent) == 'function' then
		titleObj = page
	else
		error(string.format(
			"Argumento #1 inválido para 'getTarget'"
				.. " (sequência ('string'), número ou objeto de título esperado, obteve %s)",
			type(page)
		), 2)
	end
	if not titleObj then
		return nil
	end
	local targetTitle = titleObj.redirectTarget
	if targetTitle then
		if fulltext then
			return targetTitle.fullText
		else
			return targetTitle.prefixedText
		end
	else
		return nil
	end
end

--[[
-- Dado um único nome de página, determina para qual página ele redireciona e 
-- retorna o nome da página de destino ou o nome da página passada quando não 
-- for um redirecionamento. O nome de página passado pode ser fornecido como 
-- texto simples ou como uma ligação ('link') de página.
--
-- Retorna o nome da página como texto simples ou, quando o parâmetro colchete 
-- é fornecido, como uma ligação ('link') da página. Retorna uma mensagem de 
-- erro quando a página não existe ou o destino do redirecionamento não pode ser 
-- determinado por algum motivo.
--]]
function p.luaMain(rname, bracket, fulltext)
	if type(rname) ~= "string" or not rname:find("%S") then
		return nil
	end
	bracket = bracket and "[[%s]]" or "%s"
	rname = rname:match("%[%[(.+)%]%]") or rname
	local target = p.getTarget(rname, fulltext)
	local ret = target or rname
	ret = getTitle(ret)
	if ret then
		if fulltext then
			ret = ret.fullText
		else
			ret = ret.prefixedText
		end
		return bracket:format(ret)
	else
		return nil
	end
end

-- Fornece acesso à função "luaMain" a partir de texto wiki.
function p.main(frame)
	local args = require('Módulo:Testes/Gkiyoshinishimoto/Arguments').getArgs(frame, {frameOnly = true})
	return p.luaMain(args[1], args.bracket, args.fulltext) or ''
end

-- Retorna "true" se a página especificada for um redirecionamento, 
-- e "false" caso não.
function p.luaIsRedirect(page)
	local titleObj = getTitle(page)
	if not titleObj then
		return false
	end
	if titleObj.isRedirect then
		return true
	else
		return false
	end
end

-- Fornece acesso à função "luaIsRedirect" a partir de texto wiki, retornando
-- "yes" se a página especificada for um redirecionamento e a sequência ('string')
-- em branco caso não.
function p.isRedirect(frame)
	local args = require('Módulo:Testes/Gkiyoshinishimoto/Arguments').getArgs(frame, {frameOnly = true})
	if p.luaIsRedirect(args[1]) then
		return 'yes'
	else
		return ''
	end
end

return p