examples/mime-type.lua
author Myhailo Danylenko <isbear@ukrpost.net>
Fri, 02 Apr 2010 19:58:18 +0300
changeset 101 98488a7e6a48
child 102 f3d9d9e67ee4
permissions -rw-r--r--
Add missing mime-type script

#! /usr/bin/lua

--[[ Copyright 2010 Myhailo Danylenko

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>. ]]

--
-- Simple mime type detector
--

local F = { }

local options = {
	database = '/etc/mime.types',
	default  = 'application/octet-stream',
}

local db = { }

local h = io.open ( options['database'], 'r' )
if not h then
	print ( ("mime-type: error loading database from %s"):format ( options['database'] ) )
else
	for l in h:lines () do
		local mtype, exts = l:match ( '^([%S]+)%s+(%S.*)$' )
		if mtype then
			for ext in exts:gmatch ( '%S+' ) do
				print ( ("Adding type %s for extension %s"):format ( mtype, ext ) )
				db[ext] = mtype
			end
		end
	end
	h:close ()
end

function F.type ( filename )
	local ext = filename:match ( "^.-%.([%w%d]+)$" )
	if ext then
		local mtype = db[ext]
		if mtype then
			return mtype
		end
	end
	return options['default']
end

return F

-- vim: se ts=4 sw=4: --