Jump to content

Module:Get article date format

From Wikipedia, the free encyclopedia

-- TODO allow influence of the form of the output?
local DMY = 'j F Y'
local MDY = 'F j, Y'

local _getTemplates = require('Module:Find templates in use').main

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

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

local function _implicitDateFormat(page_name)
	-- Of all our currently templated engvars, only the US uses mdy exclusively.
	local templates = _getTemplates({
		page = page_name,
		templates = table.concat({
			'Use American English',
			-- Redirects:
				'Use US English',
				'Use U.S. English',
				'EngvarA',
				'En-US',
				'Use United States English',
				'Use american English',
				'Use american english',
				'En-us',
				'Enus',
				'US-en',
				'Use USA English',
				'Use American',
				'Use American ENGLISH',
				'Use Mexican American English',
				'Use American spelling'
		}, '#')
	})

	if type(templates) ~= 'table' then
		mw.addWarning(templates)
		return nil
	end

	for k, v in pairs(templates) do
		return MDY
	end

	return DMY
end

local function _explicitDateFormat(page_name)
	local title_table = mw.title.new(page_name)
	if _isEmpty(title_table) or not title_table:inNamespace(0) then
		return DMY
	end

	local templates = _getTemplates({
		page = page_name,
		templates = table.concat({
			'Use mdy dates',
			-- Redirects:
				'Mdy',
				'MDY',
				'Use MDY dates',
				'Usemdy',
				'Usemdydates',
				'Use MDY',
				'Use mdy',
				'Use mdy date',

			'Use dmy dates',
			-- Redirects:
				'Dmy',
				'DMY',
				'Use DMY dates',
				'Usedmy',
				'Use dmy',
				'Use DMY',
				'Usedmydates'
		}, '#')
	})

	if type(templates) ~= 'table' then
		mw.addWarning(templates)
		return nil
	end

	local date_format = nil

	for k, v in pairs(templates) do
		-- TODO handle multiples and conflicts

		date_format = mw.ustring.match(k, '[Dd][Mm][Yy]')
		if date_format then
			return DMY
		end

		date_format = mw.ustring.match(k, '[Mm][Dd][Yy]')
		if date_format then
			return MDY
		end

	end

	return date_format
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

	local page_name = args.page or ''

	return _explicitDateFormat(page_name) or _implicitDateFormat(page_name)
end

return p