Jump to content

Module:Format work

From Wikipedia, the free encyclopedia

local MONTH_NAMES = {
	'January', 'February', 'March', 'April', 'May', 'June',
	'July', 'August', 'September', 'October', 'November', 'December'
}

local function _isEmpty(value) return value == nil or value == '' end

local function _notEmpty(value) return not _isEmpty(value) end

local function _unnilify(value) return value or '' end

local function _alarmingMessage(message)
	return '<span class="error">[[Module:Format work]] '..message..'.</span>'
	-- TODO .. '[[Category:Pages displaying alarming messages about Module:Format work]]'
end

-- TODO option to disable automatic linking in the event the result is incorrect
local function _link(name)
	if mw.ustring.match(name, '%[%[.-%]%]') then
		return name
	end

	-- Checking if there's content is cheaper than testing title_table.exists,
	-- but still don't getContent of non-article title_tables.
	local title_table = mw.title.new(name)
	if _isEmpty(title_table) or not title_table:inNamespace(0) or _isEmpty(title_table:getContent()) then
		return name
	end

	return '[['..name..']]'
end

local function _formatWork(args)
	local act = _link(args.act)
	local title = _link(args.title)

	local release_type = args.type
	if _isEmpty(release_type) or release_type:lower() == 'major' then
		title = "''"..title.."''"
	else
		title = '"'..title..'"'
	end

	local parenthesized = {}

	local label_distributor = _unnilify(args.label or args.distributor)
	if _notEmpty(label_distributor) then
		table.insert(parenthesized, _link(label_distributor))
	end

	local full_date = _unnilify(args.year)
	if _notEmpty(full_date) then
		local month = tonumber(args.month)
		if month then
			if _notEmpty(args.day) then
				full_date = mw.getCurrentFrame():callParserFunction{
					name = '#time',
					args = {
						require('Module:Get article date format').main({
							page = args.page
						}),
						full_date..'-'..month..'-'..args.day
					}
				}
			else
				full_date = MONTH_NAMES[month]..' '..full_date
			end
		end
		table.insert(parenthesized, full_date)
	end

	if #parenthesized > 0 then
		parenthesized = ' ('..table.concat(parenthesized, ', ')..')'
	else
		parenthesized = ''
	end

	local notes = _unnilify(args.notes)
	if _notEmpty(notes) then
		notes = '&nbsp;– '..notes
	end

	return act..': '..title..parenthesized..notes
end

local function _main(args)
	if _isEmpty(args.act) then
		return _alarmingMessage('requires an |act= value')
	end

	if _isEmpty(args.title) then
		return _alarmingMessage('requires a |title= value')
	end

	-- TODO allow a format_string to sculpt the output?

	return _formatWork(args)
end

local p = {}

function p.main(frame)
	local args = require('Module:Arguments').getArgs(frame)
	if _isEmpty(args) then
		return _alarmingMessage('could not getArgs') -- This really would be alarming.
	end

	return _main(args)
end

return p