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(qw(lock quit date util misc));
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);
74 use Params::Validate qw(validate_with :types);
76 use Fcntl qw(:DEFAULT :flock);
78 our $DEBUG_FH = \*STDERR if not defined $DEBUG_FH;
82 The following functions are exported by the C<:util> tag
84 =head2 getbugcomponent
86 my $file = getbugcomponent($bug_number,$extension,$location)
88 Returns the path to the bug file in location C<$location>, bug number
89 C<$bugnumber> and extension C<$extension>
94 my ($bugnum, $ext, $location) = @_;
96 if (not defined $location) {
97 $location = getbuglocation($bugnum, $ext);
98 # Default to non-archived bugs only for now; CGI scripts want
99 # archived bugs but most of the backend scripts don't. For now,
100 # anything that is prepared to accept archived bugs should call
101 # getbuglocation() directly first.
102 return undef if defined $location and
103 ($location ne 'db' and $location ne 'db-h');
105 my $dir = getlocationpath($location);
106 return undef if not defined $dir;
107 if (defined $location and $location eq 'db') {
108 return "$dir/$bugnum.$ext";
110 my $hash = get_hashname($bugnum);
111 return "$dir/$hash/$bugnum.$ext";
115 =head2 getbuglocation
117 getbuglocation($bug_number,$extension)
119 Returns the the location in which a particular bug exists; valid
120 locations returned currently are archive, db-h, or db. If the bug does
121 not exist, returns undef.
126 my ($bugnum, $ext) = @_;
127 my $archdir = get_hashname($bugnum);
128 return 'archive' if -r getlocationpath('archive')."/$archdir/$bugnum.$ext";
129 return 'db-h' if -r getlocationpath('db-h')."/$archdir/$bugnum.$ext";
130 return 'db' if -r getlocationpath('db')."/$bugnum.$ext";
135 =head2 getlocationpath
137 getlocationpath($location)
139 Returns the path to a specific location
143 sub getlocationpath {
145 if (defined $location and $location eq 'archive') {
146 return "$config{spool_dir}/archive";
147 } elsif (defined $location and $location eq 'db') {
148 return "$config{spool_dir}/db";
150 return "$config{spool_dir}/db-h";
159 Returns the hash of the bug which is the location within the archive
164 return "" if ( $_[ 0 ] < 0 );
165 return sprintf "%02d", $_[ 0 ] % 100;
172 Returns the path to the logfile corresponding to the bug.
174 Returns undef if the bug does not exist.
180 my $location = getbuglocation($bugnum, 'log');
181 return getbugcomponent($bugnum, 'log', $location) if ($location);
182 $location = getbuglocation($bugnum, 'log.gz');
183 return getbugcomponent($bugnum, 'log.gz', $location) if ($location);
192 Returns the path to the summary file corresponding to the bug.
194 Returns undef if the bug does not exist.
200 my $location = getbuglocation($bugnum, 'summary');
201 return getbugcomponent($bugnum, 'summary', $location) if ($location);
207 appendfile($file,'data','to','append');
209 Opens a file for appending and writes data to it.
214 my ($file,@data) = @_;
215 my $fh = IO::File->new($file,'a') or
216 die "Unable top open $file for appending: $!";
217 print {$fh} @data or die "Unable to write to $file: $!";
218 close $fh or die "Unable to close $file: $!";
223 ovewritefile($file,'data','to','append');
225 Opens file.new, writes data to it, then moves file.new to file.
230 my ($file,@data) = @_;
231 my $fh = IO::File->new("${file}.new",'w') or
232 die "Unable top open ${file}.new for writing: $!";
233 print {$fh} @data or die "Unable to write to ${file}.new: $!";
234 close $fh or die "Unable to close ${file}.new: $!";
235 rename("${file}.new",$file) or
236 die "Unable to rename ${file}.new to $file: $!";
243 =head2 getparsedaddrs
245 my $address = getparsedaddrs($address);
246 my @address = getparsedaddrs($address);
248 Returns the output from Mail::Address->parse, or the cached output if
249 this address has been parsed before. In SCALAR context returns the
250 first address parsed.
258 return () unless defined $addr;
259 return wantarray?@{$_parsedaddrs{$addr}}:$_parsedaddrs{$addr}[0]
260 if exists $_parsedaddrs{$addr};
262 # don't display the warnings from Mail::Address->parse
263 local $SIG{__WARN__} = sub { };
264 @{$_parsedaddrs{$addr}} = Mail::Address->parse($addr);
266 return wantarray?@{$_parsedaddrs{$addr}}:$_parsedaddrs{$addr}[0];
269 =head2 getmaintainers
271 my $maintainer = getmaintainers()->{debbugs}
273 Returns a hashref of package => maintainer pairs.
277 our $_maintainer = undef;
278 our $_maintainer_rev = undef;
280 return $_maintainer if defined $_maintainer;
281 package_maintainer(rehash => 1);
285 =head2 getmaintainers_reverse
287 my @packages = @{getmaintainers_reverse->{'don@debian.org'}||[]};
289 Returns a hashref of maintainer => [qw(list of packages)] pairs.
293 sub getmaintainers_reverse{
294 return $_maintainer_rev if defined $_maintainer_rev;
295 package_maintainer(rehash => 1);
296 return $_maintainer_rev;
299 =head2 package_maintainer
301 my @s = package_maintainer(source => [qw(foo bar baz)],
302 binary => [qw(bleh blah)],
307 =item source -- scalar or arrayref of source package names to return
308 maintainers for, defaults to the empty arrayref.
310 =item binary -- scalar or arrayref of binary package names to return
311 maintainers for; automatically returns source package maintainer if
312 the package name starts with 'src:', defaults to the empty arrayref.
314 =item reverse -- whether to return the source/binary packages a
315 maintainer maintains instead
317 =item rehash -- whether to reread the maintainer and source maintainer
324 our $_source_maintainer = undef;
325 our $_source_maintainer_rev = undef;
326 sub package_maintainer {
327 my %param = validate_with(params => \@_,
328 spec => {source => {type => SCALAR|ARRAYREF,
331 binary => {type => SCALAR|ARRAYREF,
334 maintainer => {type => SCALAR|ARRAYREF,
337 rehash => {type => BOOLEAN,
340 reverse => {type => BOOLEAN,
345 my @binary = make_list($param{binary});
346 my @source = make_list($param{source});
347 my @maintainers = make_list($param{maintainer});
348 if ((@binary or @source) and @maintainers) {
349 croak "It is nonsensical to pass both maintainers and source or binary";
351 if ($param{rehash}) {
352 $_source_maintainer = undef;
353 $_source_maintainer_rev = undef;
354 $_maintainer = undef;
355 $_maintainer_rev = undef;
357 if (not defined $_source_maintainer or
358 not defined $_source_maintainer_rev) {
359 $_source_maintainer = {};
360 $_source_maintainer_rev = {};
361 for my $fn (@config{('source_maintainer_file',
362 'source_maintainer_file_override',
363 'pseudo_maint_file')}) {
364 next unless defined $fn;
366 warn "Missing source maintainer file '$fn'";
369 __add_to_hash($fn,$_source_maintainer,
370 $_source_maintainer_rev);
373 if (not defined $_maintainer or
374 not defined $_maintainer_rev) {
376 $_maintainer_rev = {};
377 for my $fn (@config{('maintainer_file',
378 'maintainer_file_override',
379 'pseudo_maint_file')}) {
380 next unless defined $fn;
382 warn "Missing maintainer file '$fn'";
385 __add_to_hash($fn,$_maintainer,
390 for my $binary (@binary) {
391 if (not $param{reverse} and $binary =~ /^src:/) {
392 push @source,$binary;
395 push @return,grep {defined $_} make_list($_maintainer->{$binary});
397 for my $source (@source) {
398 $source =~ s/^src://;
399 push @return,grep {defined $_} make_list($_source_maintainer->{$source});
401 for my $maintainer (grep {defined $_} @maintainers) {
402 push @return,grep {defined $_}
403 make_list($_maintainer_rev->{$maintainer});
404 push @return,map {$_ !~ /^src:/?'src:'.$_:$_}
406 make_list($_source_maintainer_rev->{$maintainer});
411 #=head2 __add_to_hash
413 # __add_to_hash($file,$forward_hash,$reverse_hash,'address');
415 # Reads a maintainer/source maintainer/pseudo desc file and adds the
416 # maintainers from it to the forward and reverse hashref; assumes that
417 # the forward is unique; makes no assumptions of the reverse.
422 my ($fn,$forward,$reverse,$type) = @_;
423 if (ref($forward) ne 'HASH') {
424 croak "__add_to_hash must be passed a hashref for the forward";
426 if (defined $reverse and not ref($reverse) eq 'HASH') {
427 croak "if reverse is passed to __add_to_hash, it must be a hashref";
430 my $fh = IO::File->new($fn,'r') or
431 die "Unable to open $fn for reading: $!";
434 next unless m/^(\S+)\s+(\S.*\S)\s*$/;
435 my ($key,$value)=($1,$2);
437 $forward->{$key}= $value;
438 if (defined $reverse) {
439 if ($type eq 'address') {
440 for my $m (map {lc($_->address)} (getparsedaddrs($value))) {
441 push @{$reverse->{$m}},$key;
445 push @{$reverse->{$value}}, $key;
454 my $pseudopkgdesc = getpseudodesc(...);
456 Returns the entry for a pseudo package from the
457 $config{pseudo_desc_file}. In cases where pseudo_desc_file is not
458 defined, returns an empty arrayref.
460 This function can be used to see if a particular package is a
461 pseudopackage or not.
465 our $_pseudodesc = undef;
467 return $_pseudodesc if defined $_pseudodesc;
469 __add_to_hash($config{pseudo_desc_file},$_pseudodesc) if
470 defined $config{pseudo_desc_file};
476 sort_versions('1.0-2','1.1-2');
478 Sorts versions using AptPkg::Versions::compare if it is available, or
479 Debbugs::Versions::Dpkg::vercmp if it isn't.
485 use Debbugs::Versions::Dpkg;
486 $vercmp=\&Debbugs::Versions::Dpkg::vercmp;
488 # eventually we'll use AptPkg:::Version or similar, but the current
489 # implementation makes this *super* difficult.
492 # use AptPkg::Version;
493 # $vercmp=\&AptPkg::Version::compare;
498 return sort {$vercmp->($a,$b)} @_;
504 my $english = secs_to_english($seconds);
505 my ($days,$english) = secs_to_english($seconds);
507 XXX This should probably be changed to use Date::Calc
514 my $days = int($seconds / 86400);
515 my $years = int($days / 365);
519 push @age, "1 year" if ($years == 1);
520 push @age, "$years years" if ($years > 1);
521 push @age, "1 day" if ($days == 1);
522 push @age, "$days days" if ($days > 1);
523 $result .= join(" and ", @age);
525 return wantarray?(int($seconds/86400),$result):$result;
531 These functions are exported with the :lock tag
536 filelock($lockfile,$locks);
538 FLOCKs the passed file. Use unfilelock to unlock it.
540 Can be passed an optional $locks hashref, which is used to track which
541 files are locked (and how many times they have been locked) to allow
542 for cooperative locking.
551 # NB - NOT COMPATIBLE WITH `with-lock'
552 my ($lockfile,$locks) = @_;
553 if ($lockfile !~ m{^/}) {
554 $lockfile = cwd().'/'.$lockfile;
556 # This is only here to allow for relocking bugs inside of
557 # Debbugs::Control. Nothing else should be using it.
558 if (defined $locks and exists $locks->{locks}{$lockfile} and
559 $locks->{locks}{$lockfile} >= 1) {
560 if (exists $locks->{relockable} and
561 exists $locks->{relockable}{$lockfile}) {
562 $locks->{locks}{$lockfile}++;
563 # indicate that the bug for this lockfile needs to be reread
564 $locks->{relockable}{$lockfile} = 1;
565 push @{$locks->{lockorder}},$lockfile;
570 confess "Locking already locked file: $lockfile\n".Data::Dumper->Dump([$lockfile,$locks],[qw(lockfile locks)]);
574 $count= 10; $errors= '';
577 my $fh2 = IO::File->new($lockfile,'w')
578 or die "Unable to open $lockfile for writing: $!";
579 flock($fh2,LOCK_EX|LOCK_NB)
580 or die "Unable to lock $lockfile $!";
587 push @filelocks, {fh => $fh, file => $lockfile};
588 if (defined $locks) {
589 $locks->{locks}{$lockfile}++;
590 push @{$locks->{lockorder}},$lockfile;
597 croak "failed to get lock on $lockfile -- $errors".
598 (defined $locks?Data::Dumper->Dump([$locks],[qw(locks)]):'');
604 # clean up all outstanding locks at end time
617 Unlocks the file most recently locked.
619 Note that it is not currently possible to unlock a specific file
620 locked with filelock.
626 if (@filelocks == 0) {
627 carp "unfilelock called with no active filelocks!\n";
630 if (defined $locks and ref($locks) ne 'HASH') {
631 croak "hash not passsed to unfilelock";
633 if (defined $locks and exists $locks->{lockorder} and
634 @{$locks->{lockorder}} and
635 exists $locks->{locks}{$locks->{lockorder}[-1]}) {
636 my $lockfile = pop @{$locks->{lockorder}};
637 $locks->{locks}{$lockfile}--;
638 if ($locks->{locks}{$lockfile} > 0) {
641 delete $locks->{locks}{$lockfile};
643 my %fl = %{pop(@filelocks)};
644 flock($fl{fh},LOCK_UN)
645 or warn "Unable to unlock lockfile $fl{file}: $!";
647 or warn "Unable to close lockfile $fl{file}: $!";
649 or warn "Unable to unlink lockfile $fl{file}: $!";
655 lockpid('/path/to/pidfile');
657 Creates a pidfile '/path/to/pidfile' if one doesn't exist or if the
658 pid in the file does not respond to kill 0.
660 Returns 1 on success, false on failure; dies on unusual errors.
667 my $pid = checkpid($pidfile);
668 die "Unable to read pidfile $pidfile: $!" if not defined $pid;
669 return 0 if $pid != 0;
671 die "Unable to unlink stale pidfile $pidfile $!";
673 my $pidfh = IO::File->new($pidfile,O_CREAT|O_EXCL|O_WRONLY) or
674 die "Unable to open $pidfile for writing: $!";
675 print {$pidfh} $$ or die "Unable to write to $pidfile $!";
676 close $pidfh or die "Unable to close $pidfile $!";
682 checkpid('/path/to/pidfile');
684 Checks a pid file and determines if the process listed in the pidfile
685 is still running. Returns the pid if it is, 0 if it isn't running, and
686 undef if the pidfile doesn't exist or cannot be read.
693 my $pidfh = IO::File->new($pidfile, 'r') or
698 ($pid) = $pid =~ /(\d+)/;
699 if (defined $pid and kill(0,$pid)) {
712 These functions are exported with the :quit tag.
718 Exits the program by calling die.
720 Usage of quit is deprecated; just call die instead.
725 print {$DEBUG_FH} "quitting >$_[0]<\n" if $DEBUG;
726 carp "quit() is deprecated; call die directly instead";
732 These functions are exported with the :misc tag
736 LIST = make_list(@_);
738 Turns a scalar or an arrayref into a list; expands a list of arrayrefs
741 That is, make_list([qw(a b c)]); returns qw(a b c); make_list([qw(a
742 b)],[qw(c d)] returns qw(a b c d);
747 return map {(ref($_) eq 'ARRAY')?@{$_}:$_} @_;
753 print english_join(list => \@list);
754 print english_join(\@list);
756 Joins list properly to make an english phrase.
760 =item normal -- how to separate most values; defaults to ', '
762 =item last -- how to separate the last two values; defaults to ', and '
764 =item only_two -- how to separate only two values; defaults to ' and '
766 =item list -- ARRAYREF values to join; if the first argument is an
767 ARRAYREF, it's assumed to be the list of values to join
771 In cases where C<list> is empty, returns ''; when there is only one
772 element, returns that element.
777 if (ref $_[0] eq 'ARRAY') {
778 return english_join(list=>$_[0]);
780 my %param = validate_with(params => \@_,
781 spec => {normal => {type => SCALAR,
784 last => {type => SCALAR,
787 only_two => {type => SCALAR,
790 list => {type => ARRAYREF,
794 my @list = @{$param{list}};
796 return @list?$list[0]:'';
799 return join($param{only_two},@list);
801 my $ret = $param{last} . pop(@list);
802 return join($param{normal},@list) . $ret;
806 =head2 globify_scalar
808 my $handle = globify_scalar(\$foo);
810 if $foo isn't already a glob or a globref, turn it into one using
811 IO::Scalar. Gives a new handle to /dev/null if $foo isn't defined.
813 Will carp if given a scalar which isn't a scalarref or a glob (or
814 globref), and return /dev/null. May return undef if IO::Scalar or
815 IO::File fails. (Check $!)
822 if (defined $scalar) {
823 if (defined ref($scalar)) {
824 if (ref($scalar) eq 'SCALAR' and
825 not UNIVERSAL::isa($scalar,'GLOB')) {
826 return IO::Scalar->new($scalar);
832 elsif (UNIVERSAL::isa(\$scalar,'GLOB')) {
836 carp "Given a non-scalar reference, non-glob to globify_scalar; returning /dev/null handle";
839 return IO::File->new('/dev/null','w');
842 =head2 cleanup_eval_fail()
844 print "Something failed with: ".cleanup_eval_fail($@);
846 Does various bits of cleanup on the failure message from an eval (or
847 any other die message)
849 Takes at most two options; the first is the actual failure message
850 (usually $@ and defaults to $@), the second is the debug level
851 (defaults to $DEBUG).
853 If debug is non-zero, the code at which the failure occured is output.
857 sub cleanup_eval_fail {
858 my ($error,$debug) = @_;
859 if (not defined $error or not @_) {
860 $error = $@ // 'unknown reason';
863 $debug = $DEBUG // 0;
865 $debug = 0 if not defined $debug;
870 # ditch the "at foo/bar/baz.pm line 5"
871 $error =~ s/\sat\s\S+\sline\s\d+//;
872 # ditch trailing multiple periods in case there was a cascade of
874 $error =~ s/\.+$/\./;
880 hash_slice(%hash,qw(key1 key2 key3))
882 For each key, returns matching values and keys of the hash if they exist
887 # NB: We use prototypes here SPECIFICALLY so that we can be passed a
888 # hash without uselessly making a reference to first. DO NOT USE
889 # PROTOTYPES USELESSLY ELSEWHERE.
890 sub hash_slice(\%@) {
891 my ($hashref,@keys) = @_;
892 return map {exists $hashref->{$_}?($_,$hashref->{$_}):()} @keys;