]> git.donarmstrong.com Git - debbugs.git/blob - Debbugs/Status.pm
merge changes from dla source branch
[debbugs.git] / Debbugs / Status.pm
1 # This module is part of debbugs, and is released
2 # under the terms of the GPL version 2, or any later
3 # version at your option.
4 # See the file README and COPYING for more information.
5 #
6 # [Other people have contributed to this file; their copyrights should
7 # go here too.]
8 # Copyright 2007 by Don Armstrong <don@donarmstrong.com>.
9
10 package Debbugs::Status;
11
12 =head1 NAME
13
14 Debbugs::Status -- Routines for dealing with summary and status files
15
16 =head1 SYNOPSIS
17
18 use Debbugs::Status;
19
20
21 =head1 DESCRIPTION
22
23 This module is a replacement for the parts of errorlib.pl which write
24 and read status and summary files.
25
26 It also contains generic routines for returning information about the
27 status of a particular bug
28
29 =head1 FUNCTIONS
30
31 =cut
32
33 use warnings;
34 use strict;
35 use vars qw($VERSION $DEBUG %EXPORT_TAGS @EXPORT_OK @EXPORT);
36 use base qw(Exporter);
37
38 use Params::Validate qw(validate_with :types);
39 use Debbugs::Common qw(:util :lock :quit :misc);
40 use Debbugs::Config qw(:config);
41 use Debbugs::MIME qw(decode_rfc1522 encode_rfc1522);
42 use Debbugs::Packages qw(makesourceversions getversions get_versions binarytosource);
43 use Debbugs::Versions;
44 use Debbugs::Versions::Dpkg;
45 use POSIX qw(ceil);
46
47 use List::Util qw(min max);
48
49
50 BEGIN{
51      $VERSION = 1.00;
52      $DEBUG = 0 unless defined $DEBUG;
53
54      @EXPORT = ();
55      %EXPORT_TAGS = (status => [qw(splitpackages get_bug_status buggy bug_archiveable),
56                                 qw(isstrongseverity bug_presence),
57                                ],
58                      read   => [qw(readbug read_bug lockreadbug lockreadbugmerge)],
59                      write  => [qw(writebug makestatus unlockwritebug)],
60                      versions => [qw(addfoundversions addfixedversions),
61                                   qw(removefoundversions removefixedversions)
62                                  ],
63                      hook     => [qw(bughook bughook_archive)],
64                     );
65      @EXPORT_OK = ();
66      Exporter::export_ok_tags(qw(status read write versions hook));
67      $EXPORT_TAGS{all} = [@EXPORT_OK];
68 }
69
70
71 =head2 readbug
72
73      readbug($bug_num,$location)
74      readbug($bug_num)
75
76 Reads a summary file from the archive given a bug number and a bug
77 location. Valid locations are those understood by L</getbugcomponent>
78
79 =cut
80
81
82 my %fields = (originator     => 'submitter',
83               date           => 'date',
84               subject        => 'subject',
85               msgid          => 'message-id',
86               'package'      => 'package',
87               keywords       => 'tags',
88               done           => 'done',
89               forwarded      => 'forwarded-to',
90               mergedwith     => 'merged-with',
91               severity       => 'severity',
92               owner          => 'owner',
93               found_versions => 'found-in',
94               found_date     => 'found-date',
95               fixed_versions => 'fixed-in',
96               fixed_date     => 'fixed-date',
97               blocks         => 'blocks',
98               blockedby      => 'blocked-by',
99               unarchived     => 'unarchived',
100              );
101
102 # Fields which need to be RFC1522-decoded in format versions earlier than 3.
103 my @rfc1522_fields = qw(originator subject done forwarded owner);
104
105 sub readbug {
106      return read_bug(bug => $_[0],
107                      (@_ > 1)?(location => $_[1]):()
108                     );
109 }
110
111 =head2 read_bug
112
113      read_bug(bug => $bug_num,
114               location => 'archive',
115              );
116      read_bug(summary => 'path/to/bugnum.summary');
117      read_bug($bug_num);
118
119 A more complete function than readbug; it enables you to pass a full
120 path to the summary file instead of the bug number and/or location.
121
122 =head3 Options
123
124 =over
125
126 =item bug -- the bug number
127
128 =item location -- optional location which is passed to getbugcomponent
129
130 =item summary -- complete path to the .summary file which will be read
131
132 =back
133
134 One of C<bug> or C<summary> must be passed. This function will return
135 undef on failure, and will die if improper arguments are passed.
136
137 =cut
138
139 sub read_bug{
140     if (@_ == 1) {
141          unshift @_, 'bug';
142     }
143     my %param = validate_with(params => \@_,
144                               spec   => {bug => {type => SCALAR,
145                                                  optional => 1,
146                                                  # something really
147                                                  # stupid passes
148                                                  # negative bugnumbers
149                                                  regex    => qr/^-?\d+/,
150                                                 },
151                                          location => {type => SCALAR|UNDEF,
152                                                       optional => 1,
153                                                      },
154                                          summary  => {type => SCALAR,
155                                                       optional => 1,
156                                                      },
157                                         },
158                              );
159     die "One of bug or summary must be passed to read_bug"
160          if not exists $param{bug} and not exists $param{summary};
161     my $status;
162     my $log;
163     my $location;
164     if (not defined $param{summary}) {
165          my $lref;
166          ($lref,$location) = @param{qw(bug location)};
167          if (not defined $location) {
168               $location = getbuglocation($lref,'summary');
169               return undef if not defined $location;
170          }
171          $status = getbugcomponent($lref, 'summary', $location);
172          $log    = getbugcomponent($lref, 'log'    , $location);
173          return undef unless defined $status;
174     }
175     else {
176          $status = $param{summary};
177          $log = $status;
178          $log =~ s/\.summary$/.log/;
179          ($location) = $status =~ m/(db-h|db|archive)/;
180     }
181     my $status_fh = new IO::File $status, 'r' or
182          warn "Unable to open $status for reading: $!" and return undef;
183
184     my %data;
185     my @lines;
186     my $version = 2;
187     local $_;
188
189     while (<$status_fh>) {
190         chomp;
191         push @lines, $_;
192         $version = $1 if /^Format-Version: ([0-9]+)/i;
193     }
194
195     # Version 3 is the latest format version currently supported.
196     return undef if $version > 3;
197
198     my %namemap = reverse %fields;
199     for my $line (@lines) {
200         if ($line =~ /(\S+?): (.*)/) {
201             my ($name, $value) = (lc $1, $2);
202             $data{$namemap{$name}} = $value if exists $namemap{$name};
203         }
204     }
205     for my $field (keys %fields) {
206         $data{$field} = '' unless exists $data{$field};
207     }
208
209     $data{severity} = $config{default_severity} if $data{severity} eq '';
210     for my $field (qw(found_versions fixed_versions found_date fixed_date)) {
211          $data{$field} = [split ' ', $data{$field}];
212     }
213     for my $field (qw(found fixed)) {
214          # create the found/fixed hashes which indicate when a
215          # particular version was marked found or marked fixed.
216          @{$data{$field}}{@{$data{"${field}_versions"}}} =
217               (('') x (@{$data{"${field}_date"}} - @{$data{"${field}_versions"}}),
218                @{$data{"${field}_date"}});
219     }
220
221     if ($version < 3) {
222         for my $field (@rfc1522_fields) {
223             $data{$field} = decode_rfc1522($data{$field});
224         }
225     }
226     # Add log last modified time
227     $data{log_modified} = (stat($log))[9];
228     $data{location} = $location;
229
230     return \%data;
231 }
232
233 =head2 lockreadbug
234
235      lockreadbug($bug_num,$location)
236
237 Performs a filelock, then reads the bug; the bug is unlocked if the
238 return is undefined, otherwise, you need to call unfilelock or
239 unlockwritebug.
240
241 See readbug above for information on what this returns
242
243 =cut
244
245 sub lockreadbug {
246     my ($lref, $location) = @_;
247     &filelock("lock/$lref");
248     my $data = read_bug(bug => $lref, location => $location);
249     &unfilelock unless defined $data;
250     return $data;
251 }
252
253 =head2 lockreadbugmerge
254
255      my ($locks, $data) = lockreadbugmerge($bug_num,$location);
256
257 Performs a filelock, then reads the bug. If the bug is merged, locks
258 the merge lock. Returns a list of the number of locks and the bug
259 data.
260
261 =cut
262
263 sub lockreadbugmerge {
264      my ($bug_num,$location) = @_;
265      my $data = lockreadbug(@_);
266      if (not defined $data) {
267           return (0,undef);
268      }
269      if (not length $data->{mergedwith}) {
270           return (1,$data);
271      }
272      unfilelock();
273      filelock('lock/merge');
274      $data = lockreadbug(@_);
275      if (not defined $data) {
276           unfilelock();
277           return (0,undef);
278      }
279      return (2,$data);
280 }
281
282
283 my @v1fieldorder = qw(originator date subject msgid package
284                       keywords done forwarded mergedwith severity);
285
286 =head2 makestatus
287
288      my $content = makestatus($status,$version)
289      my $content = makestatus($status);
290
291 Creates the content for a status file based on the $status hashref
292 passed.
293
294 Really only useful for writebug
295
296 Currently defaults to version 2 (non-encoded rfc1522 names) but will
297 eventually default to version 3. If you care, you should specify a
298 version.
299
300 =cut
301
302 sub makestatus {
303     my ($data,$version) = @_;
304     $version = 2 unless defined $version;
305
306     my $contents = '';
307
308     my %newdata = %$data;
309     for my $field (qw(found fixed)) {
310          if (exists $newdata{$field}) {
311               $newdata{"${field}_date"} =
312                    [map {$newdata{$field}{$_}||''} keys %{$newdata{$field}}];
313          }
314     }
315
316     for my $field (qw(found_versions fixed_versions found_date fixed_date)) {
317          $newdata{$field} = join ' ', @{$newdata{$field}||[]};
318     }
319
320     if ($version < 3) {
321         for my $field (@rfc1522_fields) {
322             $newdata{$field} = encode_rfc1522($newdata{$field});
323         }
324     }
325
326     if ($version == 1) {
327         for my $field (@v1fieldorder) {
328             if (exists $newdata{$field} and defined $newdata{$field}) {
329                 $contents .= "$newdata{$field}\n";
330             } else {
331                 $contents .= "\n";
332             }
333         }
334     } elsif ($version == 2 or $version == 3) {
335         # Version 2 or 3. Add a file format version number for the sake of
336         # further extensibility in the future.
337         $contents .= "Format-Version: $version\n";
338         for my $field (keys %fields) {
339             if (exists $newdata{$field} and defined $newdata{$field}
340                 and $newdata{$field} ne '') {
341                 # Output field names in proper case, e.g. 'Merged-With'.
342                 my $properfield = $fields{$field};
343                 $properfield =~ s/(?:^|(?<=-))([a-z])/\u$1/g;
344                 $contents .= "$properfield: $newdata{$field}\n";
345             }
346         }
347     }
348
349     return $contents;
350 }
351
352 =head2 writebug
353
354      writebug($bug_num,$status,$location,$minversion,$disablebughook)
355
356 Writes the bug status and summary files out.
357
358 Skips writting out a status file if minversion is 2
359
360 Does not call bughook if disablebughook is true.
361
362 =cut
363
364 sub writebug {
365     my ($ref, $data, $location, $minversion, $disablebughook) = @_;
366     my $change;
367
368     my %outputs = (1 => 'status', 2 => 'summary');
369     for my $version (keys %outputs) {
370         next if defined $minversion and $version < $minversion;
371         my $status = getbugcomponent($ref, $outputs{$version}, $location);
372         &quit("can't find location for $ref") unless defined $status;
373         open(S,"> $status.new") || &quit("opening $status.new: $!");
374         print(S makestatus($data, $version)) ||
375             &quit("writing $status.new: $!");
376         close(S) || &quit("closing $status.new: $!");
377         if (-e $status) {
378             $change = 'change';
379         } else {
380             $change = 'new';
381         }
382         rename("$status.new",$status) || &quit("installing new $status: $!");
383     }
384
385     # $disablebughook is a bit of a hack to let format migration scripts use
386     # this function rather than having to duplicate it themselves.
387     &bughook($change,$ref,$data) unless $disablebughook;
388 }
389
390 =head2 unlockwritebug
391
392      unlockwritebug($bug_num,$status,$location,$minversion,$disablebughook);
393
394 Writes a bug, then calls unfilelock; see writebug for what these
395 options mean.
396
397 =cut
398
399 sub unlockwritebug {
400     writebug(@_);
401     &unfilelock;
402 }
403
404 =head1 VERSIONS
405
406 The following functions are exported with the :versions tag
407
408 =head2 addfoundversions
409
410      addfoundversions($status,$package,$version,$isbinary);
411
412
413
414 =cut
415
416
417 sub addfoundversions {
418     my $data = shift;
419     my $package = shift;
420     my $version = shift;
421     my $isbinary = shift;
422     return unless defined $version;
423     undef $package if $package =~ m[(?:\s|/)];
424     my $source = $package;
425
426     if (defined $package and $isbinary) {
427         my @srcinfo = binarytosource($package, $version, undef);
428         if (@srcinfo) {
429             # We know the source package(s). Use a fully-qualified version.
430             addfoundversions($data, $_->[0], $_->[1], '') foreach @srcinfo;
431             return;
432         }
433         # Otherwise, an unqualified version will have to do.
434         undef $source;
435     }
436
437     # Strip off various kinds of brain-damage.
438     $version =~ s/;.*//;
439     $version =~ s/ *\(.*\)//;
440     $version =~ s/ +[A-Za-z].*//;
441
442     foreach my $ver (split /[,\s]+/, $version) {
443         my $sver = defined($source) ? "$source/$ver" : '';
444         unless (grep { $_ eq $ver or $_ eq $sver } @{$data->{found_versions}}) {
445             push @{$data->{found_versions}}, defined($source) ? $sver : $ver;
446         }
447         @{$data->{fixed_versions}} =
448             grep { $_ ne $ver and $_ ne $sver } @{$data->{fixed_versions}};
449     }
450 }
451
452 =head2 removefoundversions
453
454      removefoundversions($data,$package,$versiontoremove)
455
456 Removes found versions from $data
457
458 If a version is fully qualified (contains /) only versions matching
459 exactly are removed. Otherwise, all versions matching the version
460 number are removed.
461
462 Currently $package and $isbinary are entirely ignored, but accepted
463 for backwards compatibilty.
464
465 =cut
466
467 sub removefoundversions {
468     my $data = shift;
469     my $package = shift;
470     my $version = shift;
471     my $isbinary = shift;
472     return unless defined $version;
473
474     foreach my $ver (split /[,\s]+/, $version) {
475          if ($ver =~ m{/}) {
476               # fully qualified version
477               @{$data->{found_versions}} =
478                    grep {$_ ne $ver}
479                         @{$data->{found_versions}};
480          }
481          else {
482               # non qualified version; delete all matchers
483               @{$data->{found_versions}} =
484                    grep {$_ !~ m[(?:^|/)\Q$ver\E$]}
485                         @{$data->{found_versions}};
486          }
487     }
488 }
489
490
491 sub addfixedversions {
492     my $data = shift;
493     my $package = shift;
494     my $version = shift;
495     my $isbinary = shift;
496     return unless defined $version;
497     undef $package if defined $package and $package =~ m[(?:\s|/)];
498     my $source = $package;
499
500     if (defined $package and $isbinary) {
501         my @srcinfo = binarytosource($package, $version, undef);
502         if (@srcinfo) {
503             # We know the source package(s). Use a fully-qualified version.
504             addfixedversions($data, $_->[0], $_->[1], '') foreach @srcinfo;
505             return;
506         }
507         # Otherwise, an unqualified version will have to do.
508         undef $source;
509     }
510
511     # Strip off various kinds of brain-damage.
512     $version =~ s/;.*//;
513     $version =~ s/ *\(.*\)//;
514     $version =~ s/ +[A-Za-z].*//;
515
516     foreach my $ver (split /[,\s]+/, $version) {
517         my $sver = defined($source) ? "$source/$ver" : '';
518         unless (grep { $_ eq $ver or $_ eq $sver } @{$data->{fixed_versions}}) {
519             push @{$data->{fixed_versions}}, defined($source) ? $sver : $ver;
520         }
521         @{$data->{found_versions}} =
522             grep { $_ ne $ver and $_ ne $sver } @{$data->{found_versions}};
523     }
524 }
525
526 sub removefixedversions {
527     my $data = shift;
528     my $package = shift;
529     my $version = shift;
530     my $isbinary = shift;
531     return unless defined $version;
532     undef $package if $package =~ m[(?:\s|/)];
533     my $source = $package;
534
535     if (defined $package and $isbinary) {
536         my @srcinfo = binarytosource($package, $version, undef);
537         if (@srcinfo) {
538             # We know the source package(s). Use a fully-qualified version.
539             removefixedversions($data, $_->[0], $_->[1], '') foreach @srcinfo;
540             return;
541         }
542         # Otherwise, an unqualified version will have to do.
543         undef $source;
544     }
545
546     foreach my $ver (split /[,\s]+/, $version) {
547         my $sver = defined($source) ? "$source/$ver" : '';
548         @{$data->{fixed_versions}} =
549             grep { $_ ne $ver and $_ ne $sver } @{$data->{fixed_versions}};
550     }
551 }
552
553
554
555 =head2 splitpackages
556
557      splitpackages($pkgs)
558
559 Split a package string from the status file into a list of package names.
560
561 =cut
562
563 sub splitpackages {
564     my $pkgs = shift;
565     return unless defined $pkgs;
566     return map lc, split /[ \t?,()]+/, $pkgs;
567 }
568
569
570 =head2 bug_archiveable
571
572      bug_archiveable(bug => $bug_num);
573
574 Options
575
576 =over
577
578 =item bug -- bug number (required)
579
580 =item status -- Status hashref returned by read_bug or get_bug_status (optional)
581
582 =item version -- Debbugs::Version information (optional)
583
584 =item days_until -- return days until the bug can be archived
585
586 =back
587
588 Returns 1 if the bug can be archived
589 Returns 0 if the bug cannot be archived
590
591 If days_until is true, returns the number of days until the bug can be
592 archived, -1 if it cannot be archived. 0 means that the bug can be
593 archived the next time the archiver runs.
594
595 Returns undef on failure.
596
597 =cut
598
599 # This will eventually need to be fixed before we start using mod_perl
600 our $version_cache = {};
601 sub bug_archiveable{
602      my %param = validate_with(params => \@_,
603                                spec   => {bug => {type => SCALAR,
604                                                   regex => qr/^\d+$/,
605                                                  },
606                                           status => {type => HASHREF,
607                                                      optional => 1,
608                                                     },
609                                           days_until => {type => BOOLEAN,
610                                                          default => 0,
611                                                         },
612                                           ignore_time => {type => BOOLEAN,
613                                                           default => 0,
614                                                          },
615                                          },
616                               );
617      # This is what we return if the bug cannot be archived.
618      my $cannot_archive = $param{days_until}?-1:0;
619      # read the status information
620      my $status = $param{status};
621      if (not exists $param{status} or not defined $status) {
622           $status = read_bug(bug=>$param{bug});
623           return undef if not defined $status;
624      }
625      # Bugs can be archived if they are
626      # 1. Closed
627      return $cannot_archive if not defined $status->{done} or not length $status->{done};
628      # If we just are checking if the bug can be archived, we'll not even bother
629      # checking the versioning information if the bug has been -done for less than 28 days.
630      my $log_file = getbugcomponent($param{bug},'log');
631      if (not defined $log_file) {
632           print STDERR "Cannot archive $param{bug} because the log doesn't exist\n" if $DEBUG;
633           return $cannot_archive;
634      }
635      my $max_log_age = max(map {$config{remove_age} - -M $_}
636                            $log_file, map {my $log = getbugcomponent($_,'log');
637                                            defined $log ? ($log) : ();
638                                       }
639                            split / /, $status->{mergedwith}
640                        );
641      if (not $param{days_until} and not $param{ignore_time}
642          and $max_log_age > 0
643         ) {
644           print STDERR "Cannot archive $param{bug} because of time\n" if $DEBUG;
645           return $cannot_archive;
646      }
647      # At this point, we have to get the versioning information for this bug.
648      # We examine the set of distribution tags. If a bug has no distribution
649      # tags set, we assume a default set, otherwise we use the tags the bug
650      # has set.
651
652      # In cases where we are assuming a default set, if the severity
653      # is strong, we use the strong severity default; otherwise, we
654      # use the normal default.
655
656      # There must be fixed_versions for us to look at the versioning
657      # information
658      my $min_fixed_time = time;
659      my $min_archive_days = 0;
660      if (@{$status->{fixed_versions}}) {
661           my %dist_tags;
662           @dist_tags{@{$config{removal_distribution_tags}}} =
663                (1) x @{$config{removal_distribution_tags}};
664           my %dists;
665           for my $tag (split ' ', ($status->{tags}||'')) {
666                next unless exists $config{distribution_aliases}{$tag};
667                next unless $dist_tags{$config{distribution_aliases}{$tag}};
668                $dists{$config{distribution_aliases}{$tag}} = 1;
669           }
670           if (not keys %dists) {
671                if (isstrongseverity($status->{severity})) {
672                     @dists{@{$config{removal_strong_severity_default_distribution_tags}}} =
673                          (1) x @{$config{removal_strong_severity_default_distribution_tags}};
674                }
675                else {
676                     @dists{@{$config{removal_default_distribution_tags}}} =
677                          (1) x @{$config{removal_default_distribution_tags}};
678                }
679           }
680           my %source_versions;
681           my @sourceversions = get_versions(package => $status->{package},
682                                             dist => [keys %dists],
683                                             source => 1,
684                                            );
685           @source_versions{@sourceversions} = (1) x @sourceversions;
686           # If the bug has not been fixed in the versions actually
687           # distributed, then it cannot be archived.
688           if ('found' eq max_buggy(bug => $param{bug},
689                                    sourceversions => [keys %source_versions],
690                                    found          => $status->{found_versions},
691                                    fixed          => $status->{fixed_versions},
692                                    version_cache  => $version_cache,
693                                    package        => $status->{package},
694                                   )) {
695                print STDERR "Cannot archive $param{bug} because it's found\n" if $DEBUG;
696                return $cannot_archive;
697           }
698           # Since the bug has at least been fixed in the architectures
699           # that matters, we check to see how long it has been fixed.
700
701           # If $param{ignore_time}, then we should ignore time.
702           if ($param{ignore_time}) {
703                return $param{days_until}?0:1;
704           }
705
706           # To do this, we order the times from most recent to oldest;
707           # when we come to the first found version, we stop.
708           # If we run out of versions, we only report the time of the
709           # last one.
710           my %time_versions = get_versions(package => $status->{package},
711                                            dist    => [keys %dists],
712                                            source  => 1,
713                                            time    => 1,
714                                           );
715           for my $version (sort {$time_versions{$b} <=> $time_versions{$a}} keys %time_versions) {
716                my $buggy = buggy(bug => $param{bug},
717                                  version        => $version,
718                                  found          => $status->{found_versions},
719                                  fixed          => $status->{fixed_versions},
720                                  version_cache  => $version_cache,
721                                  package        => $status->{package},
722                                 );
723                last if $buggy eq 'found';
724                $min_fixed_time = min($time_versions{$version},$min_fixed_time);
725           }
726           $min_archive_days = max($min_archive_days,ceil($config{remove_age} - (time - $min_fixed_time)/(60*60*24)));
727      }
728      # If $param{ignore_time}, then we should ignore time.
729      if ($param{ignore_time}) {
730           return $param{days_until}?0:1;
731      }
732      # 6. at least 28 days have passed since the last action has occured or the bug was closed
733      my $age = ceil($max_log_age);
734      if ($age > 0 or $min_archive_days > 0) {
735           return $param{days_until}?max($age,$min_archive_days):0;
736      }
737      else {
738           return $param{days_until}?0:1;
739      }
740 }
741
742
743 =head2 get_bug_status
744
745      my $status = get_bug_status(bug => $nnn);
746
747      my $status = get_bug_status($bug_num)
748
749 =head3 Options
750
751 =over
752
753 =item bug -- scalar bug number
754
755 =item status -- optional hashref of bug status as returned by readbug
756 (can be passed to avoid rereading the bug information)
757
758 =item bug_index -- optional tied index of bug status infomration;
759 currently not correctly implemented.
760
761 =item version -- optional version(s) to check package status at
762
763 =item dist -- optional distribution(s) to check package status at
764
765 =item arch -- optional architecture(s) to check package status at
766
767 =item bugusertags -- optional hashref of bugusertags
768
769 =item sourceversion -- optional arrayref of source/version; overrides
770 dist, arch, and version. [The entries in this array must be in the
771 "source/version" format.] Eventually this can be used to for caching.
772
773 =back
774
775 Note: Currently the version information is cached; this needs to be
776 changed before using this function in long lived programs.
777
778 =cut
779
780 sub get_bug_status {
781      if (@_ == 1) {
782           unshift @_, 'bug';
783      }
784      my %param = validate_with(params => \@_,
785                                spec   => {bug       => {type => SCALAR,
786                                                         regex => qr/^\d+$/,
787                                                        },
788                                           status    => {type => HASHREF,
789                                                         optional => 1,
790                                                        },
791                                           bug_index => {type => OBJECT,
792                                                         optional => 1,
793                                                        },
794                                           version   => {type => SCALAR|ARRAYREF,
795                                                         optional => 1,
796                                                        },
797                                           dist       => {type => SCALAR|ARRAYREF,
798                                                          optional => 1,
799                                                         },
800                                           arch       => {type => SCALAR|ARRAYREF,
801                                                          optional => 1,
802                                                         },
803                                           bugusertags   => {type => HASHREF,
804                                                             optional => 1,
805                                                            },
806                                           sourceversions => {type => ARRAYREF,
807                                                              optional => 1,
808                                                             },
809                                          },
810                               );
811      my %status;
812
813      if (defined $param{bug_index} and
814          exists $param{bug_index}{$param{bug}}) {
815           %status = %{ $param{bug_index}{$param{bug}} };
816           $status{pending} = $status{ status };
817           $status{id} = $param{bug};
818           return \%status;
819      }
820      if (defined $param{status}) {
821           %status = %{$param{status}};
822      }
823      else {
824           my $location = getbuglocation($param{bug}, 'summary');
825           return {} if not defined $location or not length $location;
826           %status = %{ readbug( $param{bug}, $location ) };
827      }
828      $status{id} = $param{bug};
829
830      if (defined $param{bugusertags}{$param{bug}}) {
831           $status{keywords} = "" unless defined $status{keywords};
832           $status{keywords} .= " " unless $status{keywords} eq "";
833           $status{keywords} .= join(" ", @{$param{bugusertags}{$param{bug}}});
834      }
835      $status{tags} = $status{keywords};
836      my %tags = map { $_ => 1 } split ' ', $status{tags};
837
838      $status{"package"} =~ s/\s*$//;
839      $status{"package"} = 'unknown' if ($status{"package"} eq '');
840      $status{"severity"} = 'normal' if ($status{"severity"} eq '');
841
842      $status{"pending"} = 'pending';
843      $status{"pending"} = 'forwarded'       if (length($status{"forwarded"}));
844      $status{"pending"} = 'pending-fixed'    if ($tags{pending});
845      $status{"pending"} = 'fixed'           if ($tags{fixed});
846
847
848      my $presence = bug_presence(map{(exists $param{$_})?($_,$param{$_}):()}
849                                  qw(bug sourceversions arch dist version found fixed package)
850                                 );
851      if (defined $presence) {
852           if ($presence eq 'fixed') {
853                $status{pending} = 'done';
854           }
855           elsif ($presence eq 'absent') {
856                $status{pending} = 'absent';
857           }
858      }
859      return \%status;
860 }
861
862 =head2 bug_presence
863
864      my $precence = bug_presence(bug => nnn,
865                                  ...
866                                 );
867
868 Returns 'found', 'absent', 'fixed' or undef based on whether the bug
869 is found, absent, fixed, or no information is available in the
870 distribution (dist) and/or architecture (arch) specified.
871
872
873 =head3 Options
874
875 =over
876
877 =item bug -- scalar bug number
878
879 =item status -- optional hashref of bug status as returned by readbug
880 (can be passed to avoid rereading the bug information)
881
882 =item bug_index -- optional tied index of bug status infomration;
883 currently not correctly implemented.
884
885 =item version -- optional version to check package status at
886
887 =item dist -- optional distribution to check package status at
888
889 =item arch -- optional architecture to check package status at
890
891 =item sourceversion -- optional arrayref of source/version; overrides
892 dist, arch, and version. [The entries in this array must be in the
893 "source/version" format.] Eventually this can be used to for caching.
894
895 =back
896
897 =cut
898
899 sub bug_presence {
900      my %param = validate_with(params => \@_,
901                                spec   => {bug       => {type => SCALAR,
902                                                         regex => qr/^\d+$/,
903                                                        },
904                                           status    => {type => HASHREF,
905                                                         optional => 1,
906                                                        },
907                                           version   => {type => SCALAR|ARRAYREF,
908                                                         optional => 1,
909                                                        },
910                                           dist       => {type => SCALAR|ARRAYREF,
911                                                          optional => 1,
912                                                         },
913                                           arch       => {type => SCALAR|ARRAYREF,
914                                                          optional => 1,
915                                                         },
916                                           sourceversions => {type => ARRAYREF,
917                                                              optional => 1,
918                                                             },
919                                          },
920                               );
921      my %status;
922      if (defined $param{status}) {
923          %status = %{$param{status}};
924      }
925      else {
926           my $location = getbuglocation($param{bug}, 'summary');
927           return {} if not length $location;
928           %status = %{ readbug( $param{bug}, $location ) };
929      }
930
931      my @sourceversions;
932      my $pseudo_desc = getpseudodesc();
933      if (not exists $param{sourceversions}) {
934           my %sourceversions;
935           # pseudopackages do not have source versions by definition.
936           if (exists $pseudo_desc->{$status{package}}) {
937                # do nothing.
938           }
939           elsif (defined $param{version}) {
940                foreach my $arch (make_list($param{arch})) {
941                     for my $package (split /\s*,\s*/, $status{package}) {
942                          my @temp = makesourceversions($package,
943                                                        $arch,
944                                                        make_list($param{version})
945                                                       );
946                          @sourceversions{@temp} = (1) x @temp;
947                     }
948                }
949           } elsif (defined $param{dist}) {
950                foreach my $arch (make_list($param{arch})) {
951                     my @versions;
952                     for my $package (split /\s*,\s*/, $status{package}) {
953                          foreach my $dist (make_list($param{dist})) {
954                               push @versions, getversions($package, $dist, $arch);
955                          }
956                          my @temp = makesourceversions($package,
957                                                        $arch,
958                                                        @versions
959                                                       );
960                          @sourceversions{@temp} = (1) x @temp;
961                     }
962                }
963           }
964
965           # TODO: This should probably be handled further out for efficiency and
966           # for more ease of distinguishing between pkg= and src= queries.
967           # DLA: src= queries should just pass arch=source, and they'll be happy.
968           @sourceversions = keys %sourceversions;
969      }
970      else {
971           @sourceversions = @{$param{sourceversions}};
972      }
973      my $maxbuggy = 'undef';
974      if (@sourceversions) {
975           $maxbuggy = max_buggy(bug => $param{bug},
976                                    sourceversions => \@sourceversions,
977                                    found => $status{found_versions},
978                                    fixed => $status{fixed_versions},
979                                    package => $status{package},
980                                    version_cache => $version_cache,
981                                   );
982      }
983      elsif (defined $param{dist} and
984             not exists $pseudo_desc->{$status{package}}) {
985           return 'absent';
986      }
987      if (length($status{done}) and
988          (not @sourceversions or not @{$status{fixed_versions}})) {
989           return 'fixed';
990      }
991      return $maxbuggy;
992 }
993
994
995 =head2 max_buggy
996
997      max_buggy()
998
999 =head3 Options
1000
1001 =over
1002
1003 =item bug -- scalar bug number
1004
1005 =item sourceversion -- optional arrayref of source/version; overrides
1006 dist, arch, and version. [The entries in this array must be in the
1007 "source/version" format.] Eventually this can be used to for caching.
1008
1009 =back
1010
1011 Note: Currently the version information is cached; this needs to be
1012 changed before using this function in long lived programs.
1013
1014
1015 =cut
1016 sub max_buggy{
1017      my %param = validate_with(params => \@_,
1018                                spec   => {bug       => {type => SCALAR,
1019                                                         regex => qr/^\d+$/,
1020                                                        },
1021                                           sourceversions => {type => ARRAYREF,
1022                                                              default => [],
1023                                                             },
1024                                           found          => {type => ARRAYREF,
1025                                                              default => [],
1026                                                             },
1027                                           fixed          => {type => ARRAYREF,
1028                                                              default => [],
1029                                                             },
1030                                           package        => {type => SCALAR,
1031                                                             },
1032                                           version_cache  => {type => HASHREF,
1033                                                              default => {},
1034                                                             },
1035                                          },
1036                               );
1037      # Resolve bugginess states (we might be looking at multiple
1038      # architectures, say). Found wins, then fixed, then absent.
1039      my $maxbuggy = 'absent';
1040      for my $package (split /\s*,\s*/, $param{package}) {
1041           for my $version (@{$param{sourceversions}}) {
1042                my $buggy = buggy(bug => $param{bug},
1043                                  version => $version,
1044                                  found => $param{found},
1045                                  fixed => $param{fixed},
1046                                  version_cache => $param{version_cache},
1047                                  package => $package,
1048                                 );
1049                if ($buggy eq 'found') {
1050                     return 'found';
1051                } elsif ($buggy eq 'fixed') {
1052                     $maxbuggy = 'fixed';
1053                }
1054           }
1055      }
1056      return $maxbuggy;
1057 }
1058
1059
1060 =head2 buggy
1061
1062      buggy(bug => nnn,
1063            found => \@found,
1064            fixed => \@fixed,
1065            package => 'foo',
1066            version => '1.0',
1067           );
1068
1069 Returns the output of Debbugs::Versions::buggy for a particular
1070 package, version and found/fixed set. Automatically turns found, fixed
1071 and version into source/version strings.
1072
1073 Caching can be had by using the version_cache, but no attempt to check
1074 to see if the on disk information is more recent than the cache is
1075 made. [This will need to be fixed for long-lived processes.]
1076
1077 =cut
1078
1079 sub buggy {
1080      my %param = validate_with(params => \@_,
1081                                spec   => {bug => {type => SCALAR,
1082                                                   regex => qr/^\d+$/,
1083                                                  },
1084                                           found => {type => ARRAYREF,
1085                                                     default => [],
1086                                                    },
1087                                           fixed => {type => ARRAYREF,
1088                                                     default => [],
1089                                                    },
1090                                           version_cache => {type => HASHREF,
1091                                                             optional => 1,
1092                                                            },
1093                                           package => {type => SCALAR,
1094                                                      },
1095                                           version => {type => SCALAR,
1096                                                      },
1097                                          },
1098                               );
1099      my @found = @{$param{found}};
1100      my @fixed = @{$param{fixed}};
1101      if (grep {$_ !~ m{/}} (@{$param{found}}, @{$param{fixed}})) {
1102           # We have non-source version versions
1103           @found = makesourceversions($param{package},undef,
1104                                       @found
1105                                      );
1106           @fixed = makesourceversions($param{package},undef,
1107                                       @fixed
1108                                      );
1109      }
1110      if ($param{version} !~ m{/}) {
1111           my ($version) = makesourceversions($param{package},undef,
1112                                              $param{version}
1113                                             );
1114           $param{version} = $version if defined $version;
1115      }
1116      # Figure out which source packages we need
1117      my %sources;
1118      @sources{map {m{(.+)/}; $1} @found} = (1) x @found;
1119      @sources{map {m{(.+)/}; $1} @fixed} = (1) x @fixed;
1120      @sources{map {m{(.+)/}; $1} $param{version}} = 1 if
1121           $param{version} =~ m{/};
1122      my $version;
1123      if (not defined $param{version_cache} or
1124          not exists $param{version_cache}{join(',',sort keys %sources)}) {
1125           $version = Debbugs::Versions->new(\&Debbugs::Versions::Dpkg::vercmp);
1126           foreach my $source (keys %sources) {
1127                my $srchash = substr $source, 0, 1;
1128                my $version_fh = IO::File->new("$config{version_packages_dir}/$srchash/$source", 'r');
1129                if (not defined $version_fh) {
1130                     # We only want to warn if it's a package which actually has a maintainer
1131                     my $maints = getmaintainers();
1132                     next if not exists $maints->{$source};
1133                     warn "Bug $param{bug}: unable to open $config{version_packages_dir}/$srchash/$source: $!";
1134                     next;
1135                }
1136                $version->load($version_fh);
1137           }
1138           if (defined $param{version_cache}) {
1139                $param{version_cache}{join(',',sort keys %sources)} = $version;
1140           }
1141      }
1142      else {
1143           $version = $param{version_cache}{join(',',sort keys %sources)};
1144      }
1145      return $version->buggy($param{version},\@found,\@fixed);
1146 }
1147
1148 sub isstrongseverity {
1149     my $severity = shift;
1150     $severity = $config{default_severity} if
1151          not defined $severity or $severity eq '';
1152     return grep { $_ eq $severity } @{$config{strong_severities}};
1153 }
1154
1155
1156 =head1 PRIVATE FUNCTIONS
1157
1158 =cut
1159
1160 sub update_realtime {
1161         my ($file, %bugs) = @_;
1162
1163         # update realtime index.db
1164
1165         return () unless keys %bugs;
1166         my $idx_old = IO::File->new($file,'r')
1167              or die "Couldn't open ${file}: $!";
1168         my $idx_new = IO::File->new($file.'.new','w')
1169              or die "Couldn't open ${file}.new: $!";
1170
1171         my $min_bug = min(keys %bugs);
1172         my $line;
1173         my @line;
1174         my %changed_bugs;
1175         while($line = <$idx_old>) {
1176              @line = split /\s/, $line;
1177              # Two cases; replacing existing line or adding new line
1178              if (exists $bugs{$line[1]}) {
1179                   my $new = $bugs{$line[1]};
1180                   delete $bugs{$line[1]};
1181                   $min_bug = min(keys %bugs);
1182                   if ($new eq "NOCHANGE") {
1183                        print {$idx_new} $line;
1184                        $changed_bugs{$line[1]} = $line;
1185                   } elsif ($new eq "REMOVE") {
1186                        $changed_bugs{$line[1]} = $line;
1187                   } else {
1188                        print {$idx_new} $new;
1189                        $changed_bugs{$line[1]} = $line;
1190                   }
1191              }
1192              else {
1193                   while ($line[1] > $min_bug) {
1194                        print {$idx_new} $bugs{$min_bug};
1195                        delete $bugs{$min_bug};
1196                        last unless keys %bugs;
1197                        $min_bug = min(keys %bugs);
1198                   }
1199                   print {$idx_new} $line;
1200              }
1201              last unless keys %bugs;
1202         }
1203         print {$idx_new} map {$bugs{$_}} sort keys %bugs;
1204
1205         print {$idx_new} <$idx_old>;
1206
1207         close($idx_new);
1208         close($idx_old);
1209
1210         rename("$file.new", $file);
1211
1212         return %changed_bugs;
1213 }
1214
1215 sub bughook_archive {
1216         my @refs = @_;
1217         &filelock("debbugs.trace.lock");
1218         &appendfile("debbugs.trace","archive ".join(',',@refs)."\n");
1219         my %bugs = update_realtime("$config{spool_dir}/index.db.realtime",
1220                                    map{($_,'REMOVE')} @refs);
1221         update_realtime("$config{spool_dir}/index.archive.realtime",
1222                         %bugs);
1223         &unfilelock;
1224 }
1225
1226 sub bughook {
1227         my ( $type, %bugs_temp ) = @_;
1228         &filelock("debbugs.trace.lock");
1229
1230         my %bugs;
1231         for my $bug (keys %bugs_temp) {
1232              my $data = $bugs_temp{$bug};
1233              &appendfile("debbugs.trace","$type $bug\n",makestatus($data, 1));
1234
1235              my $whendone = "open";
1236              my $severity = $config{default_severity};
1237              (my $pkglist = $data->{package}) =~ s/[,\s]+/,/g;
1238              $pkglist =~ s/^,+//;
1239              $pkglist =~ s/,+$//;
1240              $whendone = "forwarded" if defined $data->{forwarded} and length $data->{forwarded};
1241              $whendone = "done" if defined $data->{done} and length $data->{done};
1242              $severity = $data->{severity} if length $data->{severity};
1243
1244              my $k = sprintf "%s %d %d %s [%s] %s %s\n",
1245                   $pkglist, $bug, $data->{date}, $whendone,
1246                        $data->{originator}, $severity, $data->{keywords};
1247              $bugs{$bug} = $k;
1248         }
1249         update_realtime("$config{spool_dir}/index.db.realtime", %bugs);
1250
1251         &unfilelock;
1252 }
1253
1254
1255 1;
1256
1257 __END__