Jump to content

Module:Highest archive number

Permanently protected module
From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Mr. Stradivarius (talk | contribs) at 15:35, 5 October 2014 (fix a bug in the recursion algorithm, try to guess the prefix if we are not provided with one, and make this usable from wikitext). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

-- This module finds the highest existing archive number for a set of talk
-- archive pages.

local p = {}

local function pageExists(page)
	local success, title = pcall(mw.title.new, page)
	return success and title and title.exists
end

local function findHighestArchive(prefix, i, lower, upper)
	if i < 1 then
		return nil
	elseif pageExists(prefix .. tostring(i)) then
		lower = i
		if upper and i + 1 == upper then
			return i
		elseif upper then
			i = math.floor(lower + (upper - lower) / 2)
		else
			i = i * 2
		end
		return findHighestArchive(prefix, i, lower, upper)
	else
		upper = i
		lower = lower or 0
		i = math.floor(lower + (upper - lower) / 2)
		return findHighestArchive(prefix, i, lower, upper)
	end
end

function p._main(prefix)
	if not prefix then
		-- Try to detect whether we are on an archive page or not and create
		-- the prefix accordingly.
		local title = mw.title.getCurrentTitle()
		prefix = title.prefixedText:match('^(.*/Archive )[0-9]+$')
		prefix = prefix or title.prefixedText .. '/Archive '
	end
	return findHighestArchive(prefix, 10)
end

function p.main(frame)
	local args = require('Module:Arguments').getArgs(frame, {
		trim = false,
		removeBlanks = false,
		wrappers = 'Template:Highest archive number'
	})
	local prefix = args[1]
	return p._main(prefix)
end

return p