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.
6 # [Other people have contributed to this file; their copyrights should
8 # Copyright 2007 by Don Armstrong <don@donarmstrong.com>.
10 package Debbugs::Common;
14 Debbugs::Common -- Common routines for all of Debbugs
18 use Debbugs::Common qw(:url :html);
23 This module is a replacement for the general parts of errorlib.pl.
24 subroutines in errorlib.pl will be gradually phased out and replaced
25 with equivalent (or better) functionality here.
33 use vars qw($VERSION $DEBUG %EXPORT_TAGS @EXPORT_OK @EXPORT);
34 use base qw(Exporter);
38 $DEBUG = 0 unless defined $DEBUG;
41 %EXPORT_TAGS = (util => [qw(getbugcomponent getbuglocation getlocationpath get_hashname),
42 qw(appendfile overwritefile buglog getparsedaddrs getmaintainers),
44 qw(getmaintainers_reverse),
46 qw(package_maintainer),
49 misc => [qw(make_list globify_scalar english_join checkpid),
50 qw(cleanup_eval_fail),
53 date => [qw(secs_to_english)],
55 lock => [qw(filelock unfilelock lockpid)],
58 Exporter::export_ok_tags(keys %EXPORT_TAGS);
59 $EXPORT_TAGS{all} = [@EXPORT_OK];
62 #use Debbugs::Config qw(:globals);
67 use Debbugs::Config qw(:config);
70 use Debbugs::MIME qw(decode_rfc1522);
73 use Storable qw(dclone);
75 use Params::Validate qw(validate_with :types);
77 use Fcntl qw(:DEFAULT :flock);
79 our $DEBUG_FH = \*STDERR if not defined $DEBUG_FH;
83 The following functions are exported by the C<:util> tag
85 =head2 getbugcomponent
87 my $file = getbugcomponent($bug_number,$extension,$location)
89 Returns the path to the bug file in location C<$location>, bug number
90 C<$bugnumber> and extension C<$extension>
95 my ($bugnum, $ext, $location) = @_;
97 if (not defined $location) {
98 $location = getbuglocation($bugnum, $ext);
99 # Default to non-archived bugs only for now; CGI scripts want
100 # archived bugs but most of the backend scripts don't. For now,
101 # anything that is prepared to accept archived bugs should call
102 # getbuglocation() directly first.
103 return undef if defined $location and
104 ($location ne 'db' and $location ne 'db-h');
106 my $dir = getlocationpath($location);
107 return undef if not defined $dir;
108 if (defined $location and $location eq 'db') {
109 return "$dir/$bugnum.$ext";
111 my $hash = get_hashname($bugnum);
112 return "$dir/$hash/$bugnum.$ext";
116 =head2 getbuglocation
118 getbuglocation($bug_number,$extension)
120 Returns the the location in which a particular bug exists; valid
121 locations returned currently are archive, db-h, or db. If the bug does
122 not exist, returns undef.
127 my ($bugnum, $ext) = @_;
128 my $archdir = get_hashname($bugnum);
129 return 'archive' if -r getlocationpath('archive')."/$archdir/$bugnum.$ext";
130 return 'db-h' if -r getlocationpath('db-h')."/$archdir/$bugnum.$ext";
131 return 'db' if -r getlocationpath('db')."/$bugnum.$ext";
136 =head2 getlocationpath
138 getlocationpath($location)
140 Returns the path to a specific location
144 sub getlocationpath {
146 if (defined $location and $location eq 'archive') {
147 return "$config{spool_dir}/archive";
148 } elsif (defined $location and $location eq 'db') {
149 return "$config{spool_dir}/db";
151 return "$config{spool_dir}/db-h";
160 Returns the hash of the bug which is the location within the archive
165 return "" if ( $_[ 0 ] < 0 );
166 return sprintf "%02d", $_[ 0 ] % 100;
173 Returns the path to the logfile corresponding to the bug.
175 Returns undef if the bug does not exist.
181 my $location = getbuglocation($bugnum, 'log');
182 return getbugcomponent($bugnum, 'log', $location) if ($location);
183 $location = getbuglocation($bugnum, 'log.gz');
184 return getbugcomponent($bugnum, 'log.gz', $location) if ($location);
193 Returns the path to the summary file corresponding to the bug.
195 Returns undef if the bug does not exist.
201 my $location = getbuglocation($bugnum, 'summary');
202 return getbugcomponent($bugnum, 'summary', $location) if ($location);
208 appendfile($file,'data','to','append');
210 Opens a file for appending and writes data to it.
215 my ($file,@data) = @_;
216 my $fh = IO::File->new($file,'a') or
217 die "Unable top open $file for appending: $!";
218 print {$fh} @data or die "Unable to write to $file: $!";
219 close $fh or die "Unable to close $file: $!";
224 ovewritefile($file,'data','to','append');
226 Opens file.new, writes data to it, then moves file.new to file.
231 my ($file,@data) = @_;
232 my $fh = IO::File->new("${file}.new",'w') or
233 die "Unable top open ${file}.new for writing: $!";
234 print {$fh} @data or die "Unable to write to ${file}.new: $!";
235 close $fh or die "Unable to close ${file}.new: $!";
236 rename("${file}.new",$file) or
237 die "Unable to rename ${file}.new to $file: $!";
244 =head2 getparsedaddrs
246 my $address = getparsedaddrs($address);
247 my @address = getparsedaddrs($address);
249 Returns the output from Mail::Address->parse, or the cached output if
250 this address has been parsed before. In SCALAR context returns the
251 first address parsed.
259 return () unless defined $addr;
260 return wantarray?@{$_parsedaddrs{$addr}}:$_parsedaddrs{$addr}[0]
261 if exists $_parsedaddrs{$addr};
263 # don't display the warnings from Mail::Address->parse
264 local $SIG{__WARN__} = sub { };
265 @{$_parsedaddrs{$addr}} = Mail::Address->parse($addr);
267 return wantarray?@{$_parsedaddrs{$addr}}:$_parsedaddrs{$addr}[0];
270 =head2 getmaintainers
272 my $maintainer = getmaintainers()->{debbugs}
274 Returns a hashref of package => maintainer pairs.
278 our $_maintainer = undef;
279 our $_maintainer_rev = undef;
281 return $_maintainer if defined $_maintainer;
282 package_maintainer(rehash => 1);
286 =head2 getmaintainers_reverse
288 my @packages = @{getmaintainers_reverse->{'don@debian.org'}||[]};
290 Returns a hashref of maintainer => [qw(list of packages)] pairs.
294 sub getmaintainers_reverse{
295 return $_maintainer_rev if defined $_maintainer_rev;
296 package_maintainer(rehash => 1);
297 return $_maintainer_rev;
300 =head2 package_maintainer
302 my @s = package_maintainer(source => [qw(foo bar baz)],
303 binary => [qw(bleh blah)],
308 =item source -- scalar or arrayref of source package names to return
309 maintainers for, defaults to the empty arrayref.
311 =item binary -- scalar or arrayref of binary package names to return
312 maintainers for; automatically returns source package maintainer if
313 the package name starts with 'src:', defaults to the empty arrayref.
315 =item reverse -- whether to return the source/binary packages a
316 maintainer maintains instead
318 =item rehash -- whether to reread the maintainer and source maintainer
325 our $_source_maintainer = undef;
326 our $_source_maintainer_rev = undef;
327 sub package_maintainer {
328 my %param = validate_with(params => \@_,
329 spec => {source => {type => SCALAR|ARRAYREF,
332 binary => {type => SCALAR|ARRAYREF,
335 maintainer => {type => SCALAR|ARRAYREF,
338 rehash => {type => BOOLEAN,
341 reverse => {type => BOOLEAN,
346 my @binary = make_list($param{binary});
347 my @source = make_list($param{source});
348 my @maintainers = make_list($param{maintainer});
349 if ((@binary or @source) and @maintainers) {
350 croak "It is nonsensical to pass both maintainers and source or binary";
352 if ($param{rehash}) {
353 $_source_maintainer = undef;
354 $_source_maintainer_rev = undef;
355 $_maintainer = undef;
356 $_maintainer_rev = undef;
358 if (not defined $_source_maintainer or
359 not defined $_source_maintainer_rev) {
360 $_source_maintainer = {};
361 $_source_maintainer_rev = {};
362 for my $fn (@config{('source_maintainer_file',
363 'source_maintainer_file_override',
364 'pseudo_maint_file')}) {
365 next unless defined $fn;
367 warn "Missing source maintainer file '$fn'";
370 __add_to_hash($fn,$_source_maintainer,
371 $_source_maintainer_rev);
374 if (not defined $_maintainer or
375 not defined $_maintainer_rev) {
377 $_maintainer_rev = {};
378 for my $fn (@config{('maintainer_file',
379 'maintainer_file_override',
380 'pseudo_maint_file')}) {
381 next unless defined $fn;
383 warn "Missing maintainer file '$fn'";
386 __add_to_hash($fn,$_maintainer,
391 for my $binary (@binary) {
392 if (not $param{reverse} and $binary =~ /^src:/) {
393 push @source,$binary;
396 push @return,grep {defined $_} make_list($_maintainer->{$binary});
398 for my $source (@source) {
399 $source =~ s/^src://;
400 push @return,grep {defined $_} make_list($_source_maintainer->{$source});
402 for my $maintainer (grep {defined $_} @maintainers) {
403 push @return,grep {defined $_}
404 make_list($_maintainer_rev->{$maintainer});
405 push @return,map {$_ !~ /^src:/?'src:'.$_:$_}
407 make_list($_source_maintainer_rev->{$maintainer});
412 #=head2 __add_to_hash
414 # __add_to_hash($file,$forward_hash,$reverse_hash,'address');
416 # Reads a maintainer/source maintainer/pseudo desc file and adds the
417 # maintainers from it to the forward and reverse hashref; assumes that
418 # the forward is unique; makes no assumptions of the reverse.
423 my ($fn,$forward,$reverse,$type) = @_;
424 if (ref($forward) ne 'HASH') {
425 croak "__add_to_hash must be passed a hashref for the forward";
427 if (defined $reverse and not ref($reverse) eq 'HASH') {
428 croak "if reverse is passed to __add_to_hash, it must be a hashref";
431 my $fh = IO::File->new($fn,'r') or
432 die "Unable to open $fn for reading: $!";
433 binmode($fh,':encoding(UTF-8)');
436 next unless m/^(\S+)\s+(\S.*\S)\s*$/;
437 my ($key,$value)=($1,$2);
439 $forward->{$key}= $value;
440 if (defined $reverse) {
441 if ($type eq 'address') {
442 for my $m (map {lc($_->address)} (getparsedaddrs($value))) {
443 push @{$reverse->{$m}},$key;
447 push @{$reverse->{$value}}, $key;
456 my $pseudopkgdesc = getpseudodesc(...);
458 Returns the entry for a pseudo package from the
459 $config{pseudo_desc_file}. In cases where pseudo_desc_file is not
460 defined, returns an empty arrayref.
462 This function can be used to see if a particular package is a
463 pseudopackage or not.
467 our $_pseudodesc = undef;
469 return $_pseudodesc if defined $_pseudodesc;
471 __add_to_hash($config{pseudo_desc_file},$_pseudodesc) if
472 defined $config{pseudo_desc_file};
478 sort_versions('1.0-2','1.1-2');
480 Sorts versions using AptPkg::Versions::compare if it is available, or
481 Debbugs::Versions::Dpkg::vercmp if it isn't.
487 use Debbugs::Versions::Dpkg;
488 $vercmp=\&Debbugs::Versions::Dpkg::vercmp;
490 # eventually we'll use AptPkg:::Version or similar, but the current
491 # implementation makes this *super* difficult.
494 # use AptPkg::Version;
495 # $vercmp=\&AptPkg::Version::compare;
500 return sort {$vercmp->($a,$b)} @_;
506 my $english = secs_to_english($seconds);
507 my ($days,$english) = secs_to_english($seconds);
509 XXX This should probably be changed to use Date::Calc
516 my $days = int($seconds / 86400);
517 my $years = int($days / 365);
521 push @age, "1 year" if ($years == 1);
522 push @age, "$years years" if ($years > 1);
523 push @age, "1 day" if ($days == 1);
524 push @age, "$days days" if ($days > 1);
525 $result .= join(" and ", @age);
527 return wantarray?(int($seconds/86400),$result):$result;
533 These functions are exported with the :lock tag
538 filelock($lockfile,$locks);
540 FLOCKs the passed file. Use unfilelock to unlock it.
542 Can be passed an optional $locks hashref, which is used to track which
543 files are locked (and how many times they have been locked) to allow
544 for cooperative locking.
553 # NB - NOT COMPATIBLE WITH `with-lock'
554 my ($lockfile,$locks) = @_;
555 if ($lockfile !~ m{^/}) {
556 $lockfile = cwd().'/'.$lockfile;
558 # This is only here to allow for relocking bugs inside of
559 # Debbugs::Control. Nothing else should be using it.
560 if (defined $locks and exists $locks->{locks}{$lockfile} and
561 $locks->{locks}{$lockfile} >= 1) {
562 if (exists $locks->{relockable} and
563 exists $locks->{relockable}{$lockfile}) {
564 $locks->{locks}{$lockfile}++;
565 # indicate that the bug for this lockfile needs to be reread
566 $locks->{relockable}{$lockfile} = 1;
567 push @{$locks->{lockorder}},$lockfile;
572 confess "Locking already locked file: $lockfile\n".Data::Dumper->Dump([$lockfile,$locks],[qw(lockfile locks)]);
576 $count= 10; $errors= '';
579 my $fh2 = IO::File->new($lockfile,'w')
580 or die "Unable to open $lockfile for writing: $!";
581 flock($fh2,LOCK_EX|LOCK_NB)
582 or die "Unable to lock $lockfile $!";
589 push @filelocks, {fh => $fh, file => $lockfile};
590 if (defined $locks) {
591 $locks->{locks}{$lockfile}++;
592 push @{$locks->{lockorder}},$lockfile;
599 croak "failed to get lock on $lockfile -- $errors".
600 (defined $locks?Data::Dumper->Dump([$locks],[qw(locks)]):'');
606 # clean up all outstanding locks at end time
619 Unlocks the file most recently locked.
621 Note that it is not currently possible to unlock a specific file
622 locked with filelock.
628 if (@filelocks == 0) {
629 carp "unfilelock called with no active filelocks!\n";
632 if (defined $locks and ref($locks) ne 'HASH') {
633 croak "hash not passsed to unfilelock";
635 if (defined $locks and exists $locks->{lockorder} and
636 @{$locks->{lockorder}} and
637 exists $locks->{locks}{$locks->{lockorder}[-1]}) {
638 my $lockfile = pop @{$locks->{lockorder}};
639 $locks->{locks}{$lockfile}--;
640 if ($locks->{locks}{$lockfile} > 0) {
643 delete $locks->{locks}{$lockfile};
645 my %fl = %{pop(@filelocks)};
646 flock($fl{fh},LOCK_UN)
647 or warn "Unable to unlock lockfile $fl{file}: $!";
649 or warn "Unable to close lockfile $fl{file}: $!";
651 or warn "Unable to unlink lockfile $fl{file}: $!";
657 lockpid('/path/to/pidfile');
659 Creates a pidfile '/path/to/pidfile' if one doesn't exist or if the
660 pid in the file does not respond to kill 0.
662 Returns 1 on success, false on failure; dies on unusual errors.
669 my $pid = checkpid($pidfile);
670 die "Unable to read pidfile $pidfile: $!" if not defined $pid;
671 return 0 if $pid != 0;
673 die "Unable to unlink stale pidfile $pidfile $!";
675 my $pidfh = IO::File->new($pidfile,O_CREAT|O_EXCL|O_WRONLY) or
676 die "Unable to open $pidfile for writing: $!";
677 print {$pidfh} $$ or die "Unable to write to $pidfile $!";
678 close $pidfh or die "Unable to close $pidfile $!";
684 checkpid('/path/to/pidfile');
686 Checks a pid file and determines if the process listed in the pidfile
687 is still running. Returns the pid if it is, 0 if it isn't running, and
688 undef if the pidfile doesn't exist or cannot be read.
695 my $pidfh = IO::File->new($pidfile, 'r') or
700 ($pid) = $pid =~ /(\d+)/;
701 if (defined $pid and kill(0,$pid)) {
714 These functions are exported with the :quit tag.
720 Exits the program by calling die.
722 Usage of quit is deprecated; just call die instead.
727 print {$DEBUG_FH} "quitting >$_[0]<\n" if $DEBUG;
728 carp "quit() is deprecated; call die directly instead";
734 These functions are exported with the :misc tag
738 LIST = make_list(@_);
740 Turns a scalar or an arrayref into a list; expands a list of arrayrefs
743 That is, make_list([qw(a b c)]); returns qw(a b c); make_list([qw(a
744 b)],[qw(c d)] returns qw(a b c d);
749 return map {(ref($_) eq 'ARRAY')?@{$_}:$_} @_;
755 print english_join(list => \@list);
756 print english_join(\@list);
758 Joins list properly to make an english phrase.
762 =item normal -- how to separate most values; defaults to ', '
764 =item last -- how to separate the last two values; defaults to ', and '
766 =item only_two -- how to separate only two values; defaults to ' and '
768 =item list -- ARRAYREF values to join; if the first argument is an
769 ARRAYREF, it's assumed to be the list of values to join
773 In cases where C<list> is empty, returns ''; when there is only one
774 element, returns that element.
779 if (ref $_[0] eq 'ARRAY') {
780 return english_join(list=>$_[0]);
782 my %param = validate_with(params => \@_,
783 spec => {normal => {type => SCALAR,
786 last => {type => SCALAR,
789 only_two => {type => SCALAR,
792 list => {type => ARRAYREF,
796 my @list = @{$param{list}};
798 return @list?$list[0]:'';
801 return join($param{only_two},@list);
803 my $ret = $param{last} . pop(@list);
804 return join($param{normal},@list) . $ret;
808 =head2 globify_scalar
810 my $handle = globify_scalar(\$foo);
812 if $foo isn't already a glob or a globref, turn it into one using
813 IO::Scalar. Gives a new handle to /dev/null if $foo isn't defined.
815 Will carp if given a scalar which isn't a scalarref or a glob (or
816 globref), and return /dev/null. May return undef if IO::Scalar or
817 IO::File fails. (Check $!)
824 if (defined $scalar) {
825 if (defined ref($scalar)) {
826 if (ref($scalar) eq 'SCALAR' and
827 not UNIVERSAL::isa($scalar,'GLOB')) {
828 open $handle, '>:scalar:encoding(UTF-8)', $scalar;
835 elsif (UNIVERSAL::isa(\$scalar,'GLOB')) {
839 carp "Given a non-scalar reference, non-glob to globify_scalar; returning /dev/null handle";
842 return IO::File->new('/dev/null','>:encoding(UTF-8)');
845 =head2 cleanup_eval_fail()
847 print "Something failed with: ".cleanup_eval_fail($@);
849 Does various bits of cleanup on the failure message from an eval (or
850 any other die message)
852 Takes at most two options; the first is the actual failure message
853 (usually $@ and defaults to $@), the second is the debug level
854 (defaults to $DEBUG).
856 If debug is non-zero, the code at which the failure occured is output.
860 sub cleanup_eval_fail {
861 my ($error,$debug) = @_;
862 if (not defined $error or not @_) {
863 $error = $@ // 'unknown reason';
866 $debug = $DEBUG // 0;
868 $debug = 0 if not defined $debug;
873 # ditch the "at foo/bar/baz.pm line 5"
874 $error =~ s/\sat\s\S+\sline\s\d+//;
875 # ditch croak messages
876 $error =~ s/^\t+.+\n?//g;
877 # ditch trailing multiple periods in case there was a cascade of
879 $error =~ s/\.+$/\./;
885 hash_slice(%hash,qw(key1 key2 key3))
887 For each key, returns matching values and keys of the hash if they exist
892 # NB: We use prototypes here SPECIFICALLY so that we can be passed a
893 # hash without uselessly making a reference to first. DO NOT USE
894 # PROTOTYPES USELESSLY ELSEWHERE.
895 sub hash_slice(\%@) {
896 my ($hashref,@keys) = @_;
897 return map {exists $hashref->{$_}?($_,$hashref->{$_}):()} @keys;