stow_record_data uses named captures now instead of oldstyle automagic capture vars...
[migration-tools.git] / marc-cleanup
index 834331e..f40babb 100755 (executable)
@@ -9,36 +9,40 @@ use Term::ReadLine;
 my $term = new Term::ReadLine 'yaz-cleanup';
 my $OUT = $term->OUT || \*STDOUT;
 
+$| = 1;
+
 # initialization and setup
 my $conf = {};
 initialize($conf);
-populate_trash() if ($conf->{trash});
+populate_trash() if ($conf->{trashfile});
+
+# set up files, since everything appears to be in order
+open MARC, '<:utf8', (shift || 'incoming.marc.xml')
+  or die "Can't open input file $!\n";
+open my $NUMARC, '>:utf8', $conf->{output}
+  or die "Can't open output file $!\n";
+open my $OLD2NEW, '>', 'old2new.map'
+  if ($conf->{'renumber-from'} and $conf->{'original-subfield'});
+my $EXMARC = 'EX';
+
 
 my @record  = (); # current record storage
 my %recmeta = (); # metadata about current record
 my $ptr  = 0;  # record index pointer
 
-my $input = shift || 'incoming.marc.xml';
-
-open MARC, '<:utf8', $input;
-open my $NUMARC, '>:utf8', $conf->{output};
-print $NUMARC '<?xml version="1.0" encoding="UTF-8"?>',"\n";
-print $NUMARC '<collection xmlns="http://www.loc.gov/MARC21/slim">',"\n";
-
-open my $EXMARC, '>:utf8', $conf->{exception};
-
 # this is the dispatch table which drives command selection in
 # edit(), below
-my %commands = ( c => \&print_context,
-                 C => \&print_linecontext,
-                 o => \&show_original,
-                 O => \&insert_original,
-                 f => \&flip_lines,
+my %commands = ( c => \&print_fullcontext,
+                 n => \&next_line,
+                 p => \&prev_line,
+                 '<' => \&widen_window,
+                 '>' => \&narrow_window,
+                 d => \&display_lines,
+                 o => \&insert_original,
                  k => \&kill_line,
                  y => \&yank_line,
+                 f => \&flip_line,
                  m => \&merge_lines,
-                 n => \&next_line,
-                 p => \&prev_line,
                  s => \&substitute,
                  t => \&commit_edit,
                  x => \&dump_record,
@@ -65,13 +69,20 @@ while ( buildrecord() ) {
         if ($record[$ptr] =~ /&/ && $record[$ptr] !~ /&\w+?;/)
           { edit("Naked ampersand"); $ptr= 0; next }
 
-        # tags must be numeric
         if ($record[$ptr] =~ /<datafield tag="(.+?)"/) {
             my $match = $1;
+            # tags must be numeric
             if ($match =~ /\D/) {
-                edit("Non-numerics in tag");
+                edit("Non-numerics in tag") unless $conf->{autoscrub};
                 next;
             }
+            # test for existing 901/903 unless we're autocleaning them
+            unless ($conf->{'strip-nines'}) {
+                if ($match == 901 or $match == 903) {
+                    edit("Incoming 901/903 found in data");
+                    next;
+                }
+            }
         }
 
         # subfields can't be non-alphanumeric
@@ -82,11 +93,12 @@ while ( buildrecord() ) {
                 next;
             }
         }
+
         $ptr++;
     }
     write_record($NUMARC);
 }
-print $NUMARC "</collection>\n";
+#print $NUMARC "</collection>\n";
 print $OUT "\nDone.               \n";
 
 
@@ -97,8 +109,11 @@ print $OUT "\nDone.               \n";
 sub do_automated_cleanups {
     $ptr = 0;
     until ($ptr == $#record) {
+        # get datafield/tag data if we have it
+        stow_record_data();
+
         # catch empty datafield elements
-        if ($record[$ptr] =~ m/<datafield tag="..." ind1="." ind2=".">/) {
+        if ($record[$ptr] =~ m/<datafield tag="..."/) {
             if ($record[$ptr + 1] =~ m|</datafield>|) {
                 my @a = @record[0 .. $ptr - 1];
                 my @b = @record[$ptr + 2 .. $#record];
@@ -157,24 +172,48 @@ sub do_automated_cleanups {
         $record[$ptr] =~ s/tag="-/tag="0/g;
         $record[$ptr] =~ s/tag="(\d\d) /tag="0$1/g;
 
-        # stow tag data if we're looking at it
-        if ($record[$ptr] =~ m/<datafield tag="(.{3})" ind1="(.)" ind2="(.)">/) {
-            $recmeta{tag}  = $1;
-            $recmeta{ind1} = $2;
-            $recmeta{ind2} = $3;
-        }
-
         # automatable subfield maladies
         $record[$ptr] =~ s/code=" ">c/code="c">/;
         $record[$ptr] =~ s/code=" ">\$/code="c"$>/;
     }
 }
 
+sub stow_record_data {
+    # get tag data if we're looking at it
+    
+    if ($record[$ptr] =~ m/<datafield tag="(?<TAG>.{3})"/) {
+        $recmeta{tag} = $+{TAG};
+        $record[$ptr] =~ m/ind1="(?<IND1>.)"/;
+        $recmeta{ind1} = $+{IND1} || '';
+        $record[$ptr] =~ m/ind2="(?<IND2>.)"/;
+        $recmeta{ind2} = $+{IND2} || '';
+        
+        unless (defined $recmeta{tag}) {
+            message("Autokill record: no detectable tag");
+            dump_record("No detectable tag") ;
+        }
+
+        # and since we are looking at a tag, see if it's the original id
+        if ($conf->{'original-subfield'} and
+            $recmeta{tag} == $conf->{'original-tag'}) {
+            my $line = $record[$ptr]; my $lptr = $ptr;
+            my $osub = $conf->{'original-subfield'};
+            $recmeta{oid} = 'NONE';
+
+            until ($line =~ m|</record>|) {
+                $lptr++;
+                $line = $record[$lptr];
+                $recmeta{oid} = $+{TAG}
+                  if ($line =~ /<subfield code="$osub">(.+?)</);
+            }
+        }
+    }
+}
+
 #-----------------------------------------------------------------------------------
 # driver routines
 #-----------------------------------------------------------------------------------
 
-
 =head2 edit
 
 Handles the Term::ReadLine loop
@@ -185,27 +224,35 @@ sub edit {
     my ($msg) = @_;
 
     return if $conf->{trash}{ $recmeta{tag} };
-    message($msg, 1);
-    print_context();
+    $conf->{editmsg} = $msg;
+    print_fullcontext();
 
     # stow original problem line
-    $conf->{origline} = $record[$ptr];
+    $recmeta{origline} = $record[$ptr];
 
     while (1) {
         my $line = $term->readline('marc-cleanup>');
         my @chunks = split /\s+/, $line;
 
-        if (length $chunks[0] == 1)
-          { next unless (defined $commands{$chunks[0]}) }
+        # lines with single-character first chunks are commands.
+        # make sure they exist.
+        if (length $chunks[0] == 1) {
+            unless (defined $commands{$chunks[0]}) {
+                print $OUT "No such command '", $chunks[0], "'\n";
+                next;
+            }
+        }
 
         if (defined $commands{$chunks[0]}) {
             my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
             last if $term;
         } else {
+            $recmeta{prevline} = $record[$ptr];
             $record[$ptr] = "$line\n";
-            print_linecontext();
+            print_context();
         }
     }
+    # set pointer to top on the way out
     $ptr = 0;
 }
 
@@ -220,7 +267,7 @@ sub buildrecord {
     my $l = '';
     $l = <MARC> while (defined $l and $l !~ /<record>/);
     return $l unless defined $l;
-    @record = ($l);
+    @record = ();
     %recmeta = ();
     $conf->{ricount}++;
 
@@ -234,6 +281,13 @@ sub write_record {
     my ($FH) = @_;
     my $trash = $conf->{trash};
 
+    if ($FH eq 'EX') {
+        $EXMARC = undef;
+        open $EXMARC, '>:utf8', $conf->{exception}
+          or die "Can't open exception file $!\n";
+        $FH = $EXMARC;
+    }
+
     $conf->{rocount}++ if ($FH eq $NUMARC);
     print $FH '<!-- ', $recmeta{explanation}, " -->\n"
       if(defined $recmeta{explanation});
@@ -259,47 +313,69 @@ sub write_record {
         @record = @trimmed;
     }
 
-    # scrub newlines
-    unless ($conf->{nocollapse}) {
-        s/\n// for (@record);
-    }
-
     # add 903(?) with new record id
     my $renumber = '';
     if ($conf->{'renumber-from'}) {
-        $renumber = join('', '<datafield tag="', $conf->{'renumber-tag'},
-                         '" ind1=" " ind2=" ">',
-                         '<subfield code="', $conf->{'renumber-subfield'}, '">',
-                         $conf->{'renumber-from'}, '</subfield></datafield>');
-        $renumber .= "\n" if $conf->{nocollapse};
-        push @record, $renumber;
+        $recmeta{nid} = $conf->{'renumber-from'};
+        $renumber = join('', ' <datafield tag="', $conf->{'renumber-tag'},
+                         '" ind1=" " ind2=" "> <subfield code="',
+                         $conf->{'renumber-subfield'},
+                         '">', $recmeta{nid}, "</subfield></datafield>\n");
+        my @tmp = @record[0 .. $#record - 1];
+        my $last = $record[$#record];
+        @record = (@tmp, $renumber, $last);
         $conf->{'renumber-from'}++;
     }
 
-    print $FH @record;
-    print $FH "</record>\n";
+    # scrub newlines (unless told not to or writing exception record)
+    unless ($conf->{nocollapse} or $FH eq $EXMARC)
+      { s/\n// for (@record) }
+
+    # write to old->new map file if needed
+    if ($conf->{'renumber-from'} and $conf->{'original-subfield'}) {
+        unless (defined $recmeta{oid}) {
+            my $msg = join(' ', "No old id num found");
+            dump_record($msg);
+        } else {
+            print $OLD2NEW $recmeta{oid}, "\t", $recmeta{nid}, "\n"
+        }
+    }
+
+    # actually write the record
+    print $FH @record,"\n";
+
+    # if we were dumping to exception file, nuke the record and set ptr
+    # to terminate processing loop
+    @record = ('a');
+    $ptr = 0;
 }
 
-sub print_context {
-    print "    Tag:",$recmeta{tag}, " Ind1:'",
-      $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'\n";
-    print_linecontext();
+sub print_fullcontext {
+    print $OUT "\r", ' ' x 72, "\n";
+    print $OUT $conf->{editmsg},"\n";
+    print $OUT "\r    Tag:",$recmeta{tag}, " Ind1:'",
+      $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
+    print $OUT " @ ", $conf->{ricount}, "/", $conf->{rocount} + 1;
+    print_context();
     return 0;
 }
 
-sub print_linecontext {
-    my $low = ($ptr - 3 < 0) ? 0 : $ptr - 3;
-    print $OUT '    |', $record[$_] for ($low .. $ptr - 1);
+sub print_context {
+    my $upper = int($conf->{window} / 2) + 1;
+    my $lower = int($conf->{window} / 2) - 1;
+    my $start = ($ptr - $upper < 0) ? 0 : $ptr - $upper;
+    my $stop  = ($ptr + $lower > $#record) ? $#record : $ptr + $lower;
+    print $OUT "\n";
+    print $OUT '    |', $record[$_] for ($start .. $ptr - 1);
     print $OUT '==> |', $record[$ptr];
-    print $OUT '    |', $record[$ptr + 1], "\n" unless ($ptr == $#record);
+    print $OUT '    |', $record[$_] for ($ptr + 1 .. $stop);
+    print $OUT "\n";
     return 0;
 }
 
 sub message {
-    my ($msg, $new) = @_;
-    print $OUT "\r", ' ' x 72, "\n" if $new;
+    my ($msg) = @_;
     print $OUT "\r$msg at ",$conf->{ricount},"/",$conf->{rocount} + 1,"\n";
-
 }
 
 #-----------------------------------------------------------------------------------
@@ -307,11 +383,11 @@ sub message {
 #-----------------------------------------------------------------------------------
 
 sub substitute {
-    my ($line_in, @chunks) = @_;
+    my (@chunks) = @_;
 
     my $ofrom = shift @chunks;
-    if ($ofrom =~ /^'/ or !@chunks) {
-        until ($ofrom =~ /'$/)
+    if ($ofrom =~ /^'/) {
+        until ($ofrom =~ /'$/ or !@chunks)
           { $ofrom .= join(' ','',shift @chunks) }
         $ofrom =~ s/^'//; $ofrom =~ s/'$//;
     }
@@ -328,14 +404,14 @@ sub substitute {
         $from = join('', $from, $char);
     }
 
-    $conf->{prevline} = $record[$ptr];
+    $recmeta{prevline} = $record[$ptr];
     $record[$ptr] =~ s/$from/$to/;
-    print_linecontext();
+    print_context();
     return 0;
 }
 
 sub merge_lines {
-    $conf->{prevline} = $record[$ptr];
+    $recmeta{prevline} = $record[$ptr];
     # remove <subfield stuff; extract (probably wrong) subfield code
     $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
     # and move to front of line
@@ -350,43 +426,56 @@ sub merge_lines {
     @record = (@a, @b);
     # move record pointer to previous line
     prev_line();
-    print_linecontext();
+    print_context();
     return 0;
 }
 
 sub flip_line {
+    unless ($recmeta{prevline})
+      { print $OUT "No previously edited line to flip\n"; return }
     my $temp = $record[$ptr];
-    $record[$ptr] = $conf->{prevline};
-    $conf->{prevline} = $temp;
-    print_linecontext();
+    $record[$ptr] = $recmeta{prevline};
+    $recmeta{prevline} = $temp;
+    print_context();
     return 0;
 }
 
 sub kill_line {
-    $conf->{prevline} = $record[$ptr];
+    $recmeta{killline} = $record[$ptr];
     my @a = @record[0 .. $ptr - 1];
     my @b = @record[$ptr + 1 .. $#record];
     @record = (@a, @b);
-    print_linecontext();
+    print_context();
     return 0;
 }
 
 sub yank_line {
+    unless ($recmeta{killline})
+      { print $OUT "No killed line to yank\n"; return }
     my @a = @record[0 .. $ptr - 1];
     my @b = @record[$ptr .. $#record];
-    @record = (@a, $conf->{prevline}, @b);
-    print_linecontext();
+    @record = (@a, $conf->{killline}, @b);
+    print_context();
     return 0;
 }
 
-sub show_original {
-    my ($line_in) = @_;
-    print $OUT "\n", $conf->{origline}, "\n";
+sub insert_original {
+    $record[$ptr] = $recmeta{origline};
+    print_context();
+    return 0;
+}
+
+sub display_lines {
+    print $OUT "\nOrig. edit line  :", $recmeta{origline};
+    print $OUT "Current flip line:", $recmeta{prevline} if $recmeta{prevline};
+    print $OUT "Last killed line :", $recmeta{killline} if $recmeta{killline};
+    print $OUT "\n";
     return 0;
 }
 
 sub dump_record {
-    my ($line_in, @explanation) = @_;
+    my (@explanation) = @_;
+    print $OUT @explanation;
     $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
     write_record($EXMARC);
     return 1;
@@ -394,31 +483,49 @@ sub dump_record {
 
 sub next_line {
     $ptr++ unless ($ptr == $#record);;
-    print_linecontext();
+    print_context();
     return 0;
 }
 
 sub prev_line {
     $ptr-- unless ($ptr == 0);
-    print_linecontext();
+    print_context();
     return 0;
 }
 
 sub commit_edit { return 1 }
 
+sub widen_window {
+    if ($conf->{window} == 15)
+      { print $OUT "Window can't be bigger than 15 lines\n"; return }
+    $conf->{window} += 2;
+    print_context;
+}
+
+sub narrow_window {
+    if ($conf->{window} == 5)
+      { print $OUT "Window can't be smaller than 5 lines\n"; return }
+    $conf->{window} -= 2;
+    print_context;
+}
+
 sub help {
 print $OUT <<HELP;
-
 Type a replacement for the indicated line, or enter a command.
 
-Commands: c  Show record context again ('C' for brief context)
-          k  Kill indicated line (remove from record)
-          m  Merge indicated line with previous line
-          o  Show original line
-          s  Substitute ARG1 for ARG2 in indicated line
-          t  Commit changes and resume stream edit
-          x  Write this record to the exception file instead of output
-          q  Quit
+DISPLAY COMMANDS             | LINE AUTO-EDIT COMMANDS
+<  Expand context window     | k  Kill current line
+>  Contract context window   | y  Yank last killed line
+p  Move pointer to prev line | m  Merge current line into preceding line
+n  Move pointer to next line | o  Insert original line
+c  Print line context        | f  Flip current line and last edited line
+d  Print current saved lines |
+-----------------------------+-------------------------------------------
+s  Subtitute; replace ARG1 in current line with ARG2. If either ARG
+   contains spaces, it must be single-quoted
+t  Commit changes and resume automated operations
+x  Dump record to exception file
+q  Quit
 
 HELP
 return 0;
@@ -448,7 +555,7 @@ sub quit { exit }
 
 sub populate_trash {
     print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
-    open TRASH, '<', $conf->{trash}
+    open TRASH, '<', $conf->{trashfile}
       or die "Can't open trash tags file!\n";
     while (<TRASH>) {
         my $lastwasrange = 0;
@@ -544,39 +651,101 @@ sub initialize {
                          'autoscrub|a',
                          'exception|x=s',
                          'output|o=s',
+                         'prefix|p=s',
                          'nocollapse|n',
                          'renumber-from|rf=i',
-                         'original-tag|ot=i',
                          'renumber-tag|rt=i',
-                         'renumber-subfield|rt=i',
-                         'trash|t=s',
+                         'renumber-subfield|rs=s',
+                         'original-tag|ot=i',
+                         'original-subfield|os=s',
+                         'script',
+                         'strip-nines',
+                         'trashfile|t=s',
+                         'trashhelp',
                          'help|h',
                        );
     show_help() unless $rc;
     show_help() if ($c->{help});
+    show_trashhelp() if ($c->{trashhelp});
 
     # defaults
-    $c->{output} = 'incoming.cleaned.marc.xml' unless defined $c->{output};
-    $c->{exception} = 'incoming.exception.marc.xml' unless defined $c->{exception};
+    if ($c->{prefix}) {
+        $c->{output} = join('.',$c->{prefix},'marc','xml');
+        $c->{exception} = join('.',$c->{prefix},'marc','ex');
+    }
     $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
     $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
+    $c->{window} = 5;
+
+    # autotrash 901, 903 if strip-nines
+    if ($c->{'strip-nines'}) {
+        $c->{trash}{901} = 1;
+        $c->{trash}{903} = 1;
+    }
 
     my @keys = keys %{$c};
     show_help() unless (@ARGV and @keys);
-    #for my $key ('runtype', 'tag', 'subfield', 'output', 'exception')
-    #  { push @missing, $key unless $c->{$key} }
-    #if (@missing) {
-    #    print "Required option: ", join(', ', @missing), " missing!\n";
-    #    show_help();
-    #}
 }
 
 sub show_help {
     print <<HELP;
-Usage is: $0 [OPTIONS] <filelist>
+Usage is: marc-cleanup [OPTIONS] <filelist>
 Options
-  --output     -o  Cleaned MARCXML output filename (default: incoming.cleaned.marc.xml)
-  --exception  -x  Exception (dumped records) MARCXML filename (incoming.exception.marc.xml)
+  --output     -o  Cleaned MARCXML output filename
+  --exception  -x  Exception (dumped records) MARCXML filename
+       or
+  --prefix=<PREFIX>>   -p  Shared prefix for output/exception files. Will
+                           produce PREFIX.marc.xml and PREFIX.ex.xml
+
+  --trashfile  -t  File containing trash tag data (see --trashhelp)
+
+  --renumber-from     -rf  Begin renumbering id sequence with this number
+  --renumber-tag      -rt  Tag to use in renumbering (default: 903)
+  --renumber-subfield -rs  Subfield code to use in renumbering (default: a)
+  --original-tag      -ot  Original id tag; will be kept in output even if
+                           it appears in the trash file
+  --original-subfield -os  Original id subfield code. If this is specified
+                           and renumbering is in effect, an old-to-new mapping
+                           file (old2new.map) will be generated.
+
+  --nocollapse -n  Don't compress records to one line on output
+  --autoscrub  -a  Automatically remove non-numeric tags in data
+  --strip-nines    Automatically remove any existing 901/903 tags in data
+
+  --script         Store human-initiated ops in scriptfile (.mcscript)
+                   Not yet implemented
+HELP
+exit;
+}
+
+sub show_trashhelp {
+    print <<HELP;
+The marc-cleanup trash tags file is a simple plaintext file. It is a
+line oriented format. There are three basic tokens:
+
+  * The tag
+  * The tag range
+  * The "except" clause
+
+Any number of tags and/or tag ranges can appear on a single line. A
+tag cannot appear twice in the file, either alone or as part of a
+range. This is to prevent errors in the trash tag listing. Items do
+not have to be sorted within a line. These following lines are valid:
+
+  850 852 870..879 886 890 896..899
+  214 696..699 012
+
+Ranges must be ordered internally. That is, "870..879" is valid while
+"879..870" is not.
+
+Finally, there can be only one "except" clause on a line. It is
+composed of the word "except" followed by one or more tags or
+ranges. Except clauses must follow a range, and all tags within the
+clause must be within the range which the clause follows.
+
+  900..997 except 935 950..959 987 994
+
+is a valid example.
 HELP
 exit;
 }