Module:Excerpt: Difference between revisions

Content deleted Content added
Improve error handling
If the random page is unavailable, bring on a substitute
Line 7:
function p._lead(pagenames, options)
errors = options.errors
 
--if 1 then return "options.errors=("..options.errors..") errors=("..errors..")" end
if not pagenames or #pagenames < 1 then return p.err("No page names given") end
local pagename = pagenames[1]
if #pagenames > 1 then -- we could do this even with one page, but it would be inefficient
math.randomseed(os.time())
pagename = pagenames[math.random(#pagenames)] --pick a random title
end
pagename = mw.ustring.match(pagename, "%[%[%s*(.-)[]|#]") or pagename -- "[[Foo|Bar]]" → "Foo"
pagename = mw.ustring.match(pagename, "%S.*%S") -- strip leading and trailing white space
if not pagename then return p.err("Nil page name") end
if pagename == "" then return p.err("Blank page name") end
 
local pagename
local title = mw.title.new(pagename) -- Find the lead section of the named page
local text
if not title then return p.err("No title for page name " .. pagename) end
local redirpagecount = mRedirect.getTarget(title)#pagenames
local firstpage = pagenames[1] or "(nil)" -- save for error message, as it the name will be deleted
if redir then title = mw.title.new(redir) end
 
-- read the page, or a random one if multiple pages were provided
if pagecount > 1 then math.randomseed(os.time()) end
while not text and pagecount > 0 do
local pagenum = 1
pagenameif pagecount > 1 then pagenum = pagenames[math.random(#pagenamespagecount)] end -- pick a random title
local pagename = pagenames[1pagenum]
if pagename and pagename ~= "" then
pagename = mw.ustring.match(pagename, "%[%[%s*(.-)[]|#]") or pagename -- "[[Foo|Bar]]" → "Foo"
pagename = mw.ustring.match(pagename, "%S.*%S") -- strip leading and trailing white space
 
if pagename and pagename ~= "" then
local title = mw.title.new(pagename) -- Find the lead section of the named page
if not pagenametitle then return p.err("NilNo title for page name " .. pagename) end
local redir = mRedirect.getTarget(title)
if redir then title = mw.title.new(redir) end
 
local text = title:getContent()
end
end
if not text then table.remove(pagenames, pagenum) end -- this one didn't work; try another
pagecount = pagecount - 1 -- ensure that we exit the loop eventually
end
if pagenamenot == ""text then return p.err("BlankCannot read a valid page: first name is " .. firstpage) end
 
local text = title:getContent()
if not text then return p.err("No page for name " .. pagename) end
text = mw.ustring.gsub(text, "%c%s*==.*","") -- remove first heading and everything after it
text = mw.ustring.gsub(text, "<noinclude>.-</noinclude>", "") -- remove noinclude bits