]> diplodocus.org Git - minc/blobdiff - minc
(get_headers): Check errors on open.
[minc] / minc
diff --git a/minc b/minc
index c2e522c..d008d66 100755 (executable)
--- a/minc
+++ b/minc
@@ -4,11 +4,15 @@
 
 =head1 NAME
 
-B<minc> - Incorporate mail from a maildir into mh folders.
+B<minc> - incorporate mail from a maildir into mh folders
 
 =head1 SYNOPSIS
 
-B<minc> [-B<dfhnps>]
+B<minc> [B<-m> I<MAX>] [B<-n>] [B<-p>]
+
+B<minc> B<-d>
+
+B<minc> B<-h>
 
 =head1 DESCRIPTION
 
@@ -29,15 +33,12 @@ use Data::Dumper;
 use Errno;
 use Fcntl qw(O_WRONLY O_EXCL O_CREAT);
 use FileHandle;
-use File::Basename;
 use File::stat;
-use Getopt::Std;
-use Log::Dispatch;
-use Log::Dispatch::File;
+use Getopt::Long qw(:config gnu_getopt no_ignore_case);
 use POSIX qw(strftime WEXITSTATUS WIFEXITED);
+use Pod::Usage;
 
-# Autoflush STDOUT for the benefit of the status reporting in kill_spam().
-STDOUT->autoflush(1);
+our $VERSION = 1;
 
 # If a filter set's header is $MAGIC_TO_TOKEN, that set is compared
 # against headers matching this regex (taken from procmail).
@@ -61,6 +62,10 @@ for testing the syntax of .mincfilter.
 
 Show help.
 
+=item B<-m> I<MAX>
+
+Stop processing after I<MAX> messages.
+
 =item B<-n>
 
 Dry run; do not actually incorporate the mail, but log and report to
@@ -76,31 +81,23 @@ problem.
 
 =cut
 
-my $dumpfilters = 0;
-our $run = 1;
-my $printfilenames = 0;
-
-our $opt_d;
-our $opt_h;
-our $opt_n;
-our $opt_p;
-
-if (not getopts('dfhnps')) {
-    exit(2);
-}
+my $dumpfilters;
+my $help;
+my $maxmsgs;
+my $norun;
+my $printfilenames;
 
-if ($opt_d) {
-    $dumpfilters = 1;
-} elsif ($opt_h) {
-    print("Sorry bub, no help.\n");
-    exit;
-} elsif ($opt_n) {
-    $run = 0;
-}
+GetOptions(
+           'd' => \$dumpfilters,
+           'h|help' => \$help,
+           'm=i' => \$maxmsgs,
+           'n' => \$norun,
+           'p' => \$printfilenames,
+          ) or pod2usage();
+$help and pod2usage(-exitstatus=>0, -verbose=>1);
+@ARGV == 0 or pod2usage();
 
-if ($opt_p) {
-    $printfilenames = 1;
-}
+our $run = !$norun;
 
 =head1 ENVIRONMENT
 
@@ -186,14 +183,6 @@ marked unseen.
 our @FILTERS;
 require "$HOME/.mincfilter";
 
-if (-f "$HOME/.mincspam") {
-    require "$HOME/.mincspam";
-} else {
-    eval "sub spam_start_hook { return (); }";
-    eval "sub spam_stop_hook { }";
-    eval "sub spam_check { return 0; }";
-}
-
 my $mh;
 my $logfile;
 
@@ -212,29 +201,7 @@ $ENV{"MHCONTEXT"} = $mh . '/.minc.context';
 ###############################################################################
 # Logging
 
-# debuglevels for the logger
-use constant LOG_DEBUGLEVEL     => 'info';
-use constant SCREEN_DEBUGLEVEL  => 'debug';
-
-# characters used to wrap around the id field in the log so I can more
-# easily parse the msg flow
-use constant DEBUGCHAR          => '%';
-use constant INFOCHAR           => '=';
-use constant INCOMINGCHAR       => '<';
-use constant SAVECHAR           => '>';
-use constant WARNCHAR           => 'W';
-use constant ERRORCHAR          => 'E';
-
-my $logger = new Log::Dispatch;
-$logger->add(new Log::Dispatch::File (name=>'logfile',
-                                      filename=>$logfile,
-                                      min_level=>'info',
-                                      mode=>'append'));
-
-# log alias, handles getting passed vars that are undef
 sub mylog {
-    my $level = shift;
-    my $act = shift;
     my $timestamp = strftime('%b %e %H:%M:%S', localtime);
     my $msg;
     foreach my $part (@_) {
@@ -244,21 +211,13 @@ sub mylog {
     }
     # no newlines in the log message, thanks
     $msg =~ s/\n/ /gm;
-    $msg = sprintf("%s %s%s %s\n", $timestamp, $act, $act, $msg);
-    $logger->log(level=>$level, message=>$msg);
 
-    if ($act eq SAVECHAR) {
-        $logger->log(level=>$level, message=>"\n");
-    }
+    open(LOG, ">>$logfile") or die("open(>>$logfile): $!");
+    print(LOG "$timestamp $msg\n") or die("print(>>$logfile): $!");
+    close(LOG) or die("close($logfile): $!");
 }
 
-sub logsave { mylog('notice', SAVECHAR, @_); }
-sub loginfo { mylog('info', INFOCHAR, @_); }
-sub logdebug { mylog('debug', DEBUGCHAR, @_); }
-sub logwarn { mylog('warning', WARNCHAR, @_); }
-sub logerr { mylog('error', ERRORCHAR, @_); }
-
-sub logincoming {
+sub logheader {
     my ($text, @contents) = @_;
     my $last;
 
@@ -268,7 +227,7 @@ sub logincoming {
         $last = '';
     }
 
-    mylog('info', INCOMINGCHAR, $text, $last);
+    mylog('<< ', $text, $last);
 }
 
 sub log_headers {
@@ -276,10 +235,10 @@ sub log_headers {
 
     # For an explanation of the %headers structure, see the
     # get_headers function below.
-    logincoming('From:       ', @{$headers{'return-path'}});
-    logincoming('To:         ', @{$headers{'to'}});
-    logincoming('Subject:    ', @{$headers{'subject'}});
-    logincoming('Message-Id: ', @{$headers{'message-id'}});
+    logheader('From:       ', @{$headers{'return-path'}});
+    logheader('To:         ', @{$headers{'to'}});
+    logheader('Subject:    ', @{$headers{'subject'}});
+    logheader('Message-Id: ', @{$headers{'message-id'}});
 }
 
 \f
@@ -287,25 +246,14 @@ sub log_headers {
 # Utility procedures
 
 sub mkfolder {
-    my $mhfolder = shift;
-    my $folder;
+    my $folder = shift;
     my $target;
     my $component;
 
-    $folder = $mh . '/' . $mhfolder;
-    $target = '';
-
-    if (not -d $folder) {
-        foreach $component (split('/', $folder)) {
-            if (defined($component) and length($component) >= 1) {
-                $target = $target . '/' . $component;
-                if (-d $target or mkdir($target)) {
-                    next;
-                } else {
-                    die("Failed to create +$mhfolder ($component)");
-                }
-            }
-        }
+    $target = $mh;
+    foreach $component (split('/', $folder)) {
+        $target = join('/', $target, $component);
+        -d $target or mkdir($target) or die("mkdir($target): $!");
     }
 }
 
@@ -314,7 +262,7 @@ sub getfiles {
     my @result;
 
     if (not opendir(DIR, $dir)) {
-        die("Failed opendir($dir)");
+        die("opendir($dir): $!");
     }
 
     # Initialize $! to 0 (success) because stupid stupid Perl provides
@@ -329,13 +277,16 @@ sub getfiles {
       } readdir(DIR);
 
     if ($! != 0) {
-        die("Failed readdir($dir)");
+        die("readdir($dir): $!");
     }
 
-    if (scalar(@result) == 0) {
+    if (@result == 0) {
         exit(0);
     }
 
+    STDOUT->autoflush(1);
+    print(scalar(@result), " messages...");
+
     closedir(DIR);
 
     return @result;
@@ -350,14 +301,15 @@ sub get_highest_msgnum {
 
     $dir = "$mh/$mhfolder";
     if (not opendir(DIR, $dir)) {
-        die("Failed opendir($dir)");
+        die("opendir($dir): $!");
     }
 
+    # Insert rant from getfiles here.
     $! = 0;
     @list = readdir(DIR);
 
     if ($! != 0) {
-        die("Failed readdir($dir)");
+        die("readdir($dir): $!");
     }
 
     closedir(DIR);
@@ -436,12 +388,12 @@ sub store_message {
     }
 
     if ($mhfolder ne 'SPAM') {
-        logsave("+$mhfolder");
+        mylog('+', $mhfolder);
     }
 
     if ($run) {
         if (not rename($msg, $mhmsg)) {
-            die("Failed rename($msg, $mhmsg)");
+            die("rename($msg, $mhmsg): $!");
         }
 
         # Mark each message as soon as we store it and bomb if that
@@ -453,6 +405,8 @@ sub store_message {
         } else {
             $status = system('mark', "+$mhfolder", "$msgnum", '-sequence',
                              'unseen', '-add');
+            # XXX need to handle signalled and stopped, and print
+            # the exit code or signal number.
             if (not WIFEXITED($status)) {
                 die("Failed to run mark");
             } elsif (WEXITSTATUS($status) != 0) {
@@ -478,7 +432,7 @@ sub get_headers {
     my $fieldname;              # unmolested header name
     my $contents;               # contents of header
 
-    open(MSG, $msg);
+    open(MSG, $msg) or die("open(MSG, $msg): $!");
     while (<MSG>) {
         chomp;
         if (length == 0) {
@@ -581,7 +535,8 @@ sub find_mh_folder {
 
 sub filter_mail {
     my @msglist = @_;
-    my $msgcount = scalar(@msglist);
+    my $msgcount = @msglist;
+    my $msgcountlen = length($msgcount);
     my @baton;
     my $msg;
     my $mhfolder;
@@ -589,13 +544,24 @@ sub filter_mail {
     my $saved = 0;
     my %FOLDERS = ('SPAM'=>1);
 
+    if (-f "$HOME/.mincspam") {
+        require "$HOME/.mincspam";
+    } else {
+        eval "sub spam_start_hook { return (); }";
+        eval "sub spam_stop_hook { }";
+        eval "sub spam_check { return 0; }";
+    }
+
     @baton = spam_start_hook();
 
-    print("$msgcount messages...");
     foreach $msg (@msglist) {
+        if ($printfilenames) {
+            print("$msg\n");
+        }
+
         if (spam_check($msg, @baton)) {
             $mhfolder = 'SPAM';
-            $spam = scalar(@SPAM)+ 1;
+            $spam = @SPAM + 1;
         } else {
             $mhfolder = find_mh_folder($msg);
             $saved++;
@@ -605,13 +571,15 @@ sub filter_mail {
 
         print("\r");
         if (not $FOLDERS{$mhfolder}) {
-            print(' ' x length($msgcount));
+            print(' ' x $msgcountlen);
             print("                                \r+$mhfolder\n");
             $FOLDERS{$mhfolder} = 1;
         }
 
         printf('%6d SPAM %6d saved %6d/%1d',
                $spam, $saved, $spam + $saved, $msgcount);
+
+        defined($maxmsgs) and ($spam + $saved < $maxmsgs or last);
     }
     print("\n");
 
@@ -716,14 +684,15 @@ list such as dev@httpd.apache.org, this filter will create the folder
 name l/apache/httpd/dev.
 
 For an example B<spam_check> function, see
-L<http:E<047>E<047>pretzelnet.orgE<047>cvsE<047>dotfilesE<047>.mincspam>
+L<http://pretzelnet.org/cvs/dotfiles/.mincspam>
 
 =head1 AUTHORS
 
-Written by Eric Gillespie <epg@pretzelnet.org> with logging code
-stolen from Adam Lazur <adam@lazur.org>.
+Written by Eric Gillespie <epg@pretzelnet.org>.  Design by Eric
+Gillespie and Doug Porter <dsp@waterspout.com>.
 
-Design by Eric Gillespie and Doug Porter <dsp@waterspout.com>.
+This program is free software; you can redistribute it and/or modify
+it under the same terms as Perl itself.
 
 =cut