Open main menu

Documentation for this module may be created at Module:FilePage/doc

-- Module for formating file titles (Origin: Wikimedia Commons, used in Template:Rename)
-- Removes possible file-namespace (like {{PAGENAME:...}}) and set "File:".
-- Removes possible file-extension and set lowercase from current page title.

-- Helpers
local h = {}
-- Retrieve file page title from page name
local title = mw.title.getCurrentTitle().text


-- "Foo.bar.SVG"
-- @return "svg"
-- Original author: Rillke at [[Module:File]]
h.getExtension = function()
	-- Retrieve "file name extension" from page title or name
	local parts = mw.text.split(title, '.', true)
	return parts[#parts]:lower()
end


-- =p.File("Foo.bar.svg").woExtension()
-- @return "Foo.bar"
-- Original author: Bawolff at [[Module:FileName]]
h.woExtension = function(title)
	local parts = mw.text.split(title , '.', true)
	local upTo = #parts - 1
	if upTo == 0 then upTo = 1 end
	return table.concat(parts, '.', 1, upTo)
end


h.getTitle = function ( ask )
	-- Precondition:
	--	 ask  -- file name; string, or nil
	-- Postcondition:
	--	 Returns string, or false if not a valid file
	ask = mw.text.trim( ask )
	local r = false
	--local lucky, s = ask:match( "^([Ff]ile:)(.+)$" )
	if ask:match( "^[Ff]ile:" ) or ask:match( "^[Ii]mage:" ) then
		r = ask:match( "^[^:]+:(.+)$" )
	else
		r = ask
	end

	r = h.woExtension( r )

	return mw.text.trim( r )
end -- h.getTitle()


-- Export
local p = { }

p.exists = function ( frame )
	-- Retrieve file title from page title or name
	--	 1  -- file title or name
	--	 Returns 1 or ''
	local lucky, r = pcall( h.getTitle, frame.args[ 1 ] )
	if not lucky then return '' end
	r = r .. '.' .. h.getExtension()
	r = mw.title.makeTitle( "File", r ).exists
	if r then r = 1 else r = '' end
	return r
end -- p.exists


p.name = function ( frame )
	-- Retrieve file title from page title or name
	--	 1  -- file title or name
	--	 Returns file name with namespace
	local lucky, r = pcall( h.getTitle, frame.args[ 1 ] )
	if not r then return '' end
	return 'File:' .. r .. '.' .. h.getExtension()
end -- p.name


p.title = function ( frame )
	-- Retrieve file title from page title or name
	--	 1  -- file title or name
	--	 Returns file title without namespace
	local lucky, r = pcall( h.getTitle, frame.args[ 1 ] )
	if not r then return '' end
	return r .. '.' .. h.getExtension()
end -- p.title

return p