Jump to content

Module:Redirect/sandbox

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Jackmcbarn (talk | contribs) at 12:19, 16 May 2014 (return a canonical output name any time the name is valid, even if it's not a redirect). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

-- Given a single page name determines what page it redirects to and returns the target page name, or the
-- passed page name when not a redirect. The passed page name can be given as plain text or as a page link.
-- Returns page name as plain text, or when the bracket parameter is given, as a page link. Returns an
-- error message when page does not exist or the redirect target cannot be determined for some reason.

-- Thus these are roughly the same:
-- [[{{#invoke:redirect|main|redirect-page-name}}]] and {{#invoke:redirect|main|redirect-page-name|bracket=yes}}

local p = {}

local function getTitle(...)
	local success, titleObj = pcall(mw.title.new, ...)
	if success then
		return titleObj
	else
		return nil
	end
end

function p.getTarget(page)
	-- Get the title object. Both page names and title objects are allowed
	-- as input.
	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(
			"bad argument #1 to 'getTarget'"
				.. " (string, number, or title object expected, got %s)",
			type(page)
		), 2)
	end
	if not titleObj then
		return nil
	elseif not titleObj.isRedirect then
		return titleObj.prefixedText
	end
	
	-- Find the target by using string matching on the page content.
	local target = string.match(
		titleObj:getContent() or "",
		"^%s*#[Rr][Ee][Dd][Ii][Rr][Ee][Cc][Tt]%s*:?%s*%[%[([^%[%]]-)%]%]"
	)
	if target then
		-- Decode html entities and percent encodings.
		target = mw.text.decode(target, true)
		target = mw.uri.decode(target, 'WIKI')
		return target
	else
		-- The page is a redirect, but matching failed. This indicates a bug in
		-- the redirect matching pattern, so throw an error.
		error(string.format(
			'could not parse redirect on page "%s"',
			titleObj.prefixedText
		))
	end
end

function p._main(rname, bracket)
	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)
	if target then
		return bracket:format(target)
	else
		return bracket:format(rname)
	end
end

function p.main(frame)
	local args = require('Module:Arguments').getArgs(frame)
	return p._main(args[1], args.bracket) or ''
end

return p