Module:Redirect: Difference between revisions
(handle apostrophes and other characters escaped by {{TALKPAGENAME}}, per protected edit request by User:Jackmcbarn) |
m (45 revisions imported from wikipedia:Module:Redirect: see Topic:Vtixlm0q28eo6jtf) |
||
| (8 intermediate revisions by 5 users not shown) | |||
| Line 1: | Line 1: | ||
-- | -- This module provides functions for getting the target of a redirect page. | ||
-- | local p = {} | ||
-- [[ | |||
-- Gets a mw.title object, using pcall to avoid generating script errors if we | |||
-- are over the expensive function count limit (among other possible causes). | |||
local function getTitle(...) | |||
local success, titleObj = pcall(mw.title.new, ...) | |||
if success then | |||
return titleObj | |||
else | |||
return nil | |||
end | |||
end | |||
-- Gets the name of a page that a redirect leads to, or nil if it isn't a | |||
-- redirect. | |||
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*%[%[([^%[%]|]-)|[^%[%]]-%]%]" | |||
) | |||
return target and mw.uri.decode(target, 'PATH') | |||
end | |||
-- Gets the target of a redirect. If the page specified is not a redirect, | |||
-- returns nil. | |||
function p.getTarget(page, fulltext) | |||
-- 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 or not titleObj.isRedirect then | |||
return nil | |||
end | |||
-- Find the target by using string matching on the page content. | |||
local target = p.getTargetFromText(titleObj:getContent() or "") | |||
if target then | |||
local targetTitle = getTitle(target) | |||
if targetTitle then | |||
if fulltext then | |||
return targetTitle.fullText | |||
else | |||
return targetTitle.prefixedText | |||
end | |||
else | |||
return nil | |||
end | |||
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"', | |||
fulltext and titleObj.fullText or titleObj.prefixedText | |||
)) | |||
end | |||
end | |||