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 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),
52 date => [qw(secs_to_english)],
54 lock => [qw(filelock unfilelock lockpid)],
57 Exporter::export_ok_tags(qw(lock quit date util misc));
58 $EXPORT_TAGS{all} = [@EXPORT_OK];
61 #use Debbugs::Config qw(:globals);
65 use Debbugs::Config qw(:config);
68 use Debbugs::MIME qw(decode_rfc1522);
72 use Params::Validate qw(validate_with :types);
76 our $DEBUG_FH = \*STDERR if not defined $DEBUG_FH;
80 The following functions are exported by the C<:util> tag
82 =head2 getbugcomponent
84 my $file = getbugcomponent($bug_number,$extension,$location)
86 Returns the path to the bug file in location C<$location>, bug number
87 C<$bugnumber> and extension C<$extension>
92 my ($bugnum, $ext, $location) = @_;
94 if (not defined $location) {
95 $location = getbuglocation($bugnum, $ext);
96 # Default to non-archived bugs only for now; CGI scripts want
97 # archived bugs but most of the backend scripts don't. For now,
98 # anything that is prepared to accept archived bugs should call
99 # getbuglocation() directly first.
100 return undef if defined $location and
101 ($location ne 'db' and $location ne 'db-h');
103 my $dir = getlocationpath($location);
104 return undef if not defined $dir;
105 if (defined $location and $location eq 'db') {
106 return "$dir/$bugnum.$ext";
108 my $hash = get_hashname($bugnum);
109 return "$dir/$hash/$bugnum.$ext";
113 =head2 getbuglocation
115 getbuglocation($bug_number,$extension)
117 Returns the the location in which a particular bug exists; valid
118 locations returned currently are archive, db-h, or db. If the bug does
119 not exist, returns undef.
124 my ($bugnum, $ext) = @_;
125 my $archdir = get_hashname($bugnum);
126 return 'archive' if -r getlocationpath('archive')."/$archdir/$bugnum.$ext";
127 return 'db-h' if -r getlocationpath('db-h')."/$archdir/$bugnum.$ext";
128 return 'db' if -r getlocationpath('db')."/$bugnum.$ext";
133 =head2 getlocationpath
135 getlocationpath($location)
137 Returns the path to a specific location
141 sub getlocationpath {
143 if (defined $location and $location eq 'archive') {
144 return "$config{spool_dir}/archive";
145 } elsif (defined $location and $location eq 'db') {
146 return "$config{spool_dir}/db";
148 return "$config{spool_dir}/db-h";
157 Returns the hash of the bug which is the location within the archive
162 return "" if ( $_[ 0 ] < 0 );
163 return sprintf "%02d", $_[ 0 ] % 100;
170 Returns the path to the logfile corresponding to the bug.
172 Returns undef if the bug does not exist.
178 my $location = getbuglocation($bugnum, 'log');
179 return getbugcomponent($bugnum, 'log', $location) if ($location);
180 $location = getbuglocation($bugnum, 'log.gz');
181 return getbugcomponent($bugnum, 'log.gz', $location) if ($location);
190 Returns the path to the summary file corresponding to the bug.
192 Returns undef if the bug does not exist.
198 my $location = getbuglocation($bugnum, 'summary');
199 return getbugcomponent($bugnum, 'summary', $location) if ($location);
205 appendfile($file,'data','to','append');
207 Opens a file for appending and writes data to it.
212 my ($file,@data) = @_;
213 my $fh = IO::File->new($file,'a') or
214 die "Unable top open $file for appending: $!";
215 print {$fh} @data or die "Unable to write to $file: $!";
216 close $fh or die "Unable to close $file: $!";
219 =head2 getparsedaddrs
221 my $address = getparsedaddrs($address);
222 my @address = getparsedaddrs($address);
224 Returns the output from Mail::Address->parse, or the cached output if
225 this address has been parsed before. In SCALAR context returns the
226 first address parsed.
234 return () unless defined $addr;
235 return wantarray?@{$_parsedaddrs{$addr}}:$_parsedaddrs{$addr}[0]
236 if exists $_parsedaddrs{$addr};
238 # don't display the warnings from Mail::Address->parse
239 local $SIG{__WARN__} = sub { };
240 @{$_parsedaddrs{$addr}} = Mail::Address->parse($addr);
242 return wantarray?@{$_parsedaddrs{$addr}}:$_parsedaddrs{$addr}[0];
245 =head2 getmaintainers
247 my $maintainer = getmaintainers()->{debbugs}
249 Returns a hashref of package => maintainer pairs.
253 our $_maintainer = undef;
254 our $_maintainer_rev = undef;
256 return $_maintainer if defined $_maintainer;
257 package_maintainer(rehash => 1);
261 =head2 getmaintainers_reverse
263 my @packages = @{getmaintainers_reverse->{'don@debian.org'}||[]};
265 Returns a hashref of maintainer => [qw(list of packages)] pairs.
269 sub getmaintainers_reverse{
270 return $_maintainer_rev if defined $_maintainer_rev;
271 package_maintainer(rehash => 1);
272 return $_maintainer_rev;
275 =head2 package_maintainer
277 my @s = package_maintainer(source => [qw(foo bar baz)],
278 binary => [qw(bleh blah)],
283 =item source -- scalar or arrayref of source package names to return
284 maintainers for, defaults to the empty arrayref.
286 =item binary -- scalar or arrayref of binary package names to return
287 maintainers for; automatically returns source package maintainer if
288 the package name starts with 'src:', defaults to the empty arrayref.
290 =item reverse -- whether to return the source/binary packages a
291 maintainer maintains instead
293 =item rehash -- whether to reread the maintainer and source maintainer
300 our $_source_maintainer = undef;
301 our $_source_maintainer_rev = undef;
302 sub package_maintainer {
303 my %param = validate_with(params => \@_,
304 spec => {source => {type => SCALAR|ARRAYREF,
307 binary => {type => SCALAR|ARRAYREF,
310 maintainer => {type => SCALAR|ARRAYREF,
313 rehash => {type => BOOLEAN,
316 reverse => {type => BOOLEAN,
321 my @binary = make_list($param{binary});
322 my @source = make_list($param{source});
323 my @maintainers = make_list($param{maintainer});
324 if ((@binary or @source) and @maintainers) {
325 croak "It is nonsensical to pass both maintainers and source or binary";
327 if ($param{rehash}) {
328 $_source_maintainer = undef;
329 $_source_maintainer_rev = undef;
330 $_maintainer = undef;
331 $_maintainer_rev = undef;
333 if (not defined $_source_maintainer or
334 not defined $_source_maintainer_rev) {
335 $_source_maintainer = {};
336 $_source_maintainer_rev = {};
337 for my $fn (@config{('source_maintainer_file',
338 'source_maintainer_file_override',
339 'pseudo_maint_file')}) {
340 next unless defined $fn;
342 warn "Missing source maintainer file '$fn'";
345 __add_to_hash($fn,$_source_maintainer,
346 $_source_maintainer_rev);
349 if (not defined $_maintainer or
350 not defined $_maintainer_rev) {
352 $_maintainer_rev = {};
353 for my $fn (@config{('maintainer_file',
354 'maintainer_file_override',
355 'pseudo_maint_file')}) {
356 next unless defined $fn;
358 warn "Missing maintainer file '$fn'";
361 __add_to_hash($fn,$_maintainer,
366 for my $binary (@binary) {
367 if (not $param{reverse} and $binary =~ /^src:/) {
368 push @source,$binary;
371 push @return,grep {defined $_} make_list($_maintainer->{$binary});
373 for my $source (@source) {
374 $source =~ s/^src://;
375 push @return,grep {defined $_} make_list($_source_maintainer->{$source});
377 for my $maintainer (grep {defined $_} @maintainers) {
378 push @return,grep {defined $_}
379 make_list($_maintainer_rev->{$maintainer});
380 push @return,map {$_ !~ /^src:/?'src:'.$_:$_}
382 make_list($_source_maintainer_rev->{$maintainer});
387 #=head2 __add_to_hash
389 # __add_to_hash($file,$forward_hash,$reverse_hash,'address');
391 # Reads a maintainer/source maintainer/pseudo desc file and adds the
392 # maintainers from it to the forward and reverse hashref; assumes that
393 # the forward is unique; makes no assumptions of the reverse.
398 my ($fn,$forward,$reverse,$type) = @_;
399 if (ref($forward) ne 'HASH') {
400 croak "__add_to_hash must be passed a hashref for the forward";
402 if (defined $reverse and not ref($reverse) eq 'HASH') {
403 croak "if reverse is passed to __add_to_hash, it must be a hashref";
406 my $fh = IO::File->new($fn,'r') or
407 die "Unable to open $fn for reading: $!";
410 next unless m/^(\S+)\s+(\S.*\S)\s*$/;
411 my ($key,$value)=($1,$2);
413 $forward->{$key}= $value;
414 if (defined $reverse) {
415 if ($type eq 'address') {
416 for my $m (map {lc($_->address)} (getparsedaddrs($value))) {
417 push @{$reverse->{$m}},$key;
421 push @{$reverse->{$value}}, $key;
430 my $pseudopkgdesc = getpseudodesc(...);
432 Returns the entry for a pseudo package from the
433 $config{pseudo_desc_file}. In cases where pseudo_desc_file is not
434 defined, returns an empty arrayref.
436 This function can be used to see if a particular package is a
437 pseudopackage or not.
441 our $_pseudodesc = undef;
443 return $_pseudodesc if defined $_pseudodesc;
445 __add_to_hash($config{pseudo_desc_file},$_pseudodesc) if
446 defined $config{pseudo_desc_file};
452 sort_versions('1.0-2','1.1-2');
454 Sorts versions using AptPkg::Versions::compare if it is available, or
455 Debbugs::Versions::Dpkg::vercmp if it isn't.
461 use Debbugs::Versions::Dpkg;
462 $vercmp=\&Debbugs::Versions::Dpkg::vercmp;
464 # eventually we'll use AptPkg:::Version or similar, but the current
465 # implementation makes this *super* difficult.
468 # use AptPkg::Version;
469 # $vercmp=\&AptPkg::Version::compare;
474 return sort {$vercmp->($a,$b)} @_;
480 my $english = secs_to_english($seconds);
481 my ($days,$english) = secs_to_english($seconds);
483 XXX This should probably be changed to use Date::Calc
490 my $days = int($seconds / 86400);
491 my $years = int($days / 365);
495 push @age, "1 year" if ($years == 1);
496 push @age, "$years years" if ($years > 1);
497 push @age, "1 day" if ($days == 1);
498 push @age, "$days days" if ($days > 1);
499 $result .= join(" and ", @age);
501 return wantarray?(int($seconds/86400),$result):$result;
507 These functions are exported with the :lock tag
513 FLOCKs the passed file. Use unfilelock to unlock it.
520 # NB - NOT COMPATIBLE WITH `with-lock'
522 if ($lockfile !~ m{^/}) {
523 $lockfile = cwd().'/'.$lockfile;
526 $count= 10; $errors= '';
529 my $fh2 = IO::File->new($lockfile,'w')
530 or die "Unable to open $lockfile for writing: $!";
531 flock($fh2,LOCK_EX|LOCK_NB)
532 or die "Unable to lock $lockfile $!";
539 push @filelocks, {fh => $fh, file => $lockfile};
544 die "failed to get lock on $lockfile -- $errors";
550 # clean up all outstanding locks at end time
562 Unlocks the file most recently locked.
564 Note that it is not currently possible to unlock a specific file
565 locked with filelock.
570 if (@filelocks == 0) {
571 warn "unfilelock called with no active filelocks!\n";
574 my %fl = %{pop(@filelocks)};
575 flock($fl{fh},LOCK_UN)
576 or warn "Unable to unlock lockfile $fl{file}: $!";
578 or warn "Unable to close lockfile $fl{file}: $!";
580 or warn "Unable to unlink lockfile $fl{file}: $!";
586 lockpid('/path/to/pidfile');
588 Creates a pidfile '/path/to/pidfile' if one doesn't exist or if the
589 pid in the file does not respond to kill 0.
591 Returns 1 on success, false on failure; dies on unusual errors.
598 my $pid = checkpid($pidfile);
599 die "Unable to read pidfile $pidfile: $!" if not defined $pid;
600 return 0 if $pid != 0;
602 die "Unable to unlink stale pidfile $pidfile $!";
604 my $pidfh = IO::File->new($pidfile,'w') or
605 die "Unable to open $pidfile for writing: $!";
606 print {$pidfh} $$ or die "Unable to write to $pidfile $!";
607 close $pidfh or die "Unable to close $pidfile $!";
613 checkpid('/path/to/pidfile');
615 Checks a pid file and determines if the process listed in the pidfile
616 is still running. Returns the pid if it is, 0 if it isn't running, and
617 undef if the pidfile doesn't exist or cannot be read.
624 my $pidfh = IO::File->new($pidfile, 'r') or
629 ($pid) = $pid =~ /(\d+)/;
630 if (defined $pid and kill(0,$pid)) {
643 These functions are exported with the :quit tag.
649 Exits the program by calling die.
651 Usage of quit is deprecated; just call die instead.
656 print {$DEBUG_FH} "quitting >$_[0]<\n" if $DEBUG;
657 carp "quit() is deprecated; call die directly instead";
663 These functions are exported with the :misc tag
667 LIST = make_list(@_);
669 Turns a scalar or an arrayref into a list; expands a list of arrayrefs
672 That is, make_list([qw(a b c)]); returns qw(a b c); make_list([qw(a
673 b)],[qw(c d)] returns qw(a b c d);
678 return map {(ref($_) eq 'ARRAY')?@{$_}:$_} @_;
684 print english_join(list => \@list);
685 print english_join(\@list);
687 Joins list properly to make an english phrase.
691 =item normal -- how to separate most values; defaults to ', '
693 =item last -- how to separate the last two values; defaults to ', and '
695 =item only_two -- how to separate only two values; defaults to ' and '
697 =item list -- ARRAYREF values to join; if the first argument is an
698 ARRAYREF, it's assumed to be the list of values to join
702 In cases where C<list> is empty, returns ''; when there is only one
703 element, returns that element.
708 if (ref $_[0] eq 'ARRAY') {
709 return english_join(list=>$_[0]);
711 my %param = validate_with(params => \@_,
712 spec => {normal => {type => SCALAR,
715 last => {type => SCALAR,
718 only_two => {type => SCALAR,
721 list => {type => ARRAYREF,
725 my @list = @{$param{list}};
727 return @list?$list[0]:'';
730 return join($param{only_two},@list);
732 my $ret = $param{last} . pop(@list);
733 return join($param{normal},@list) . $ret;
737 =head2 globify_scalar
739 my $handle = globify_scalar(\$foo);
741 if $foo isn't already a glob or a globref, turn it into one using
742 IO::Scalar. Gives a new handle to /dev/null if $foo isn't defined.
744 Will carp if given a scalar which isn't a scalarref or a glob (or
745 globref), and return /dev/null. May return undef if IO::Scalar or
746 IO::File fails. (Check $!)
753 if (defined $scalar) {
754 if (defined ref($scalar)) {
755 if (ref($scalar) eq 'SCALAR' and
756 not UNIVERSAL::isa($scalar,'GLOB')) {
757 return IO::Scalar->new($scalar);
763 elsif (UNIVERSAL::isa(\$scalar,'GLOB')) {
767 carp "Given a non-scalar reference, non-glob to globify_scalar; returning /dev/null handle";
770 return IO::File->new('/dev/null','w');
773 =head2 cleanup_eval_fail()
775 print "Something failed with: ".cleanup_eval_fail($@);
777 Does various bits of cleanup on the failure message from an eval (or
778 any other die message)
780 Takes at most two options; the first is the actual failure message
781 (usually $@ and defaults to $@), the second is the debug level
782 (defaults to $DEBUG).
784 If debug is non-zero, the code at which the failure occured is output.
788 sub cleanup_eval_fail {
789 my ($error,$debug) = @_;
790 if (not defined $error or not @_) {
791 $error = $@ // 'unknown reason';
794 $debug = $DEBUG // 0;
796 $debug = 0 if not defined $debug;
801 # ditch the "at foo/bar/baz.pm line 5"
802 $error =~ s/\sat\s\S+\sline\s\d+//;
803 # ditch trailing multiple periods in case there was a cascade of
805 $error =~ s/\.+$/\./;