#!/usr/bin/env perl # # mimetypes - refilter / convert existing mime.types files # # $Id$ # # Usage: locate mime.types | grep 'mime\.types$' | xargs $me use strict; use warnings; use Getopt::Std; my $me = $0; $me =~ s#.*/##; my %opt; getopts( 'h?sw', \%opt ); if ( $opt{'h'} || $opt{'?'} ) { print STDERR < MIME/type my %conflicts; # *.ext -> MIME/type -> 1 sub insert { my ( $pat, $mt ) = @_; if ( !defined( $pat2mt{$pat} ) ) { # first occurrence of this extension $pat2mt{$pat} = $mt; #warn "$pat -> $mt\n"; } elsif ( $opt{'w'} && ( $pat2mt{$pat} ne $mt ) ) { #warn "conflict for $mt $pat\n"; $conflicts{$pat}->{$mt} = 1; } } while (<>) { chomp; my @words = split; next if scalar(@words) < 2; if ( grep { /^svn:/ } @words ) { # try to read a line in ~/.subversion/config format my $pat = shift(@words); next if shift(@words) ne '='; foreach (@words) { if (m#^svn:mime-type=(.+/.+);?$#) { &insert( $pat, $1 ); } } } else { # try to read a line in mime.types format my ( $mt, @ext ) = @words; next if $mt !~ m#^[a-z]+/[a-z.+-]+$#; next if grep { /[^a-z]/ } @ext; foreach my $pat ( map { "*.$_" } @ext ) { &insert( $pat, $mt ); } } } if ( $opt{'w'} ) { # report on any conflicting MIME type assignments foreach my $pat ( sort keys %conflicts ) { my $mt = $pat2mt{$pat}; warn "for $pat, using $mt, ignoring ", join( ', ', sort keys %{ $conflicts{$pat} } ), "\n"; } } # ready for output generation if ( $opt{'s'} ) { # output in ~/.subversion/config format # determine the longest extension, so we can align properly my $maxlen = 0; map { $maxlen = length if $maxlen < length; } keys %pat2mt; # print each pattern,mimetype pair in the correct format map { my $mt = $pat2mt{$_}; print $_, ' ' x ( $maxlen - length ), ' = ', ( $mt =~ m#^text/# ? 'svn:keywords=Id; ' : '' ), 'svn:mime-type=', $mt, "\n"; } sort { $pat2mt{$a} cmp $pat2mt{$b} } keys %pat2mt; } else { # output in mime.types format # reverse the pattern -> MIME type mapping # using only patterns of the form *.ext my %mt2exts; # MIME/type -> ext -> 1 foreach ( keys %pat2mt ) { my $mt = $pat2mt{$_}; if ( s/^\*\.// && !/[^a-z]/ ) { $mt2exts{$mt}->{$_} = 1; } } # determine the longest MIME type, so we can align properly my $maxlen = 0; map { $maxlen = length if $maxlen < length; } keys %mt2exts; # print each mimetype,extension pair in the correct format foreach my $mt ( sort keys %mt2exts ) { print $mt, ' ' x ( 2 + $maxlen - length($mt) ), join( ' ', sort keys %{ $mt2exts{$mt} } ), "\n"; } }