examples/mime-type.lua
changeset 101 98488a7e6a48
child 102 f3d9d9e67ee4
equal deleted inserted replaced
100:521c27baa387 101:98488a7e6a48
       
     1 #! /usr/bin/lua
       
     2 
       
     3 --[[ Copyright 2010 Myhailo Danylenko
       
     4 
       
     5 This program is free software: you can redistribute it and/or modify
       
     6 it under the terms of the GNU General Public License as published by
       
     7 the Free Software Foundation, either version 2 of the License, or
       
     8 (at your option) any later version.
       
     9 
       
    10 This program is distributed in the hope that it will be useful,
       
    11 but WITHOUT ANY WARRANTY; without even the implied warranty of
       
    12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
       
    13 GNU General Public License for more details.
       
    14 
       
    15 You should have received a copy of the GNU General Public License
       
    16 along with this program.  If not, see <http://www.gnu.org/licenses/>. ]]
       
    17 
       
    18 --
       
    19 -- Simple mime type detector
       
    20 --
       
    21 
       
    22 local F = { }
       
    23 
       
    24 local options = {
       
    25 	database = '/etc/mime.types',
       
    26 	default  = 'application/octet-stream',
       
    27 }
       
    28 
       
    29 local db = { }
       
    30 
       
    31 local h = io.open ( options['database'], 'r' )
       
    32 if not h then
       
    33 	print ( ("mime-type: error loading database from %s"):format ( options['database'] ) )
       
    34 else
       
    35 	for l in h:lines () do
       
    36 		local mtype, exts = l:match ( '^([%S]+)%s+(%S.*)$' )
       
    37 		if mtype then
       
    38 			for ext in exts:gmatch ( '%S+' ) do
       
    39 				print ( ("Adding type %s for extension %s"):format ( mtype, ext ) )
       
    40 				db[ext] = mtype
       
    41 			end
       
    42 		end
       
    43 	end
       
    44 	h:close ()
       
    45 end
       
    46 
       
    47 function F.type ( filename )
       
    48 	local ext = filename:match ( "^.-%.([%w%d]+)$" )
       
    49 	if ext then
       
    50 		local mtype = db[ext]
       
    51 		if mtype then
       
    52 			return mtype
       
    53 		end
       
    54 	end
       
    55 	return options['default']
       
    56 end
       
    57 
       
    58 return F
       
    59 
       
    60 -- vim: se ts=4 sw=4: --