Module:Excerpt: Difference between revisions

Content deleted Content added
For lead, ignore all but the first unnamed argument
Improve error handling
Line 1:
local p = {}
local mRedirect = require('Module:Redirect')
local errors
 
-- Entry point for Lua callers
-- Returns a string value: text of the lead of a page
function p._lead(pagenames, options)
errors = options.errors
if not pagenames or #pagenames < 1 then return "" end -- Return blank text rather than an error splurge
--if 1 then return "options.errors=("..options.errors..") errors=("..errors..")" end
if not pagenames or #pagenames < 1 then return p.err(""No endpage --names Returngiven") blank text rather than an error splurgeend
local pagename = pagenames[1]
if #pagenames > 1 then -- we could do this even with one page, but it would be inefficient
Line 13 ⟶ 16:
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 title = mw.title.new(pagename) -- Find the lead section of the named page
if not title then return p.err("No title for page name " .. pagename) end
local redir = mRedirect.getTarget(title)
if redir then title = mw.title.new(redir) end
 
local text = title:getContent() or ""
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
Line 79 ⟶ 85:
if options.more then text = text .. " '''[[" .. pagename .. "|" .. options.more .. "]]'''" end
return text
end
 
-- Return blank text, or an error message if requested
function p.err(text, options)
if errors then error(text, 2) end
return ""
end
 
Line 117 ⟶ 129:
options.more = args["more"] or pargs["more"]
if options.more and options.more == "" then options.more = "Read more..." end -- more= is short for this default text
options.errors = args["errors"] or pargs["errors"]
 
local text = p._lead(pagenames, options)