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),
47 misc => [qw(make_list globify_scalar english_join checkpid)],
48 date => [qw(secs_to_english)],
50 lock => [qw(filelock unfilelock lockpid)],
53 Exporter::export_ok_tags(qw(lock quit date util misc));
54 $EXPORT_TAGS{all} = [@EXPORT_OK];
57 #use Debbugs::Config qw(:globals);
61 use Debbugs::Config qw(:config);
64 use Debbugs::MIME qw(decode_rfc1522);
68 use Params::Validate qw(validate_with :types);
72 our $DEBUG_FH = \*STDERR if not defined $DEBUG_FH;
76 The following functions are exported by the C<:util> tag
78 =head2 getbugcomponent
80 my $file = getbugcomponent($bug_number,$extension,$location)
82 Returns the path to the bug file in location C<$location>, bug number
83 C<$bugnumber> and extension C<$extension>
88 my ($bugnum, $ext, $location) = @_;
90 if (not defined $location) {
91 $location = getbuglocation($bugnum, $ext);
92 # Default to non-archived bugs only for now; CGI scripts want
93 # archived bugs but most of the backend scripts don't. For now,
94 # anything that is prepared to accept archived bugs should call
95 # getbuglocation() directly first.
96 return undef if defined $location and
97 ($location ne 'db' and $location ne 'db-h');
99 my $dir = getlocationpath($location);
100 return undef if not defined $dir;
101 if (defined $location and $location eq 'db') {
102 return "$dir/$bugnum.$ext";
104 my $hash = get_hashname($bugnum);
105 return "$dir/$hash/$bugnum.$ext";
109 =head2 getbuglocation
111 getbuglocation($bug_number,$extension)
113 Returns the the location in which a particular bug exists; valid
114 locations returned currently are archive, db-h, or db. If the bug does
115 not exist, returns undef.
120 my ($bugnum, $ext) = @_;
121 my $archdir = get_hashname($bugnum);
122 return 'archive' if -r getlocationpath('archive')."/$archdir/$bugnum.$ext";
123 return 'db-h' if -r getlocationpath('db-h')."/$archdir/$bugnum.$ext";
124 return 'db' if -r getlocationpath('db')."/$bugnum.$ext";
129 =head2 getlocationpath
131 getlocationpath($location)
133 Returns the path to a specific location
137 sub getlocationpath {
139 if (defined $location and $location eq 'archive') {
140 return "$config{spool_dir}/archive";
141 } elsif (defined $location and $location eq 'db') {
142 return "$config{spool_dir}/db";
144 return "$config{spool_dir}/db-h";
153 Returns the hash of the bug which is the location within the archive
158 return "" if ( $_[ 0 ] < 0 );
159 return sprintf "%02d", $_[ 0 ] % 100;
166 Returns the path to the logfile corresponding to the bug.
168 Returns undef if the bug does not exist.
174 my $location = getbuglocation($bugnum, 'log');
175 return getbugcomponent($bugnum, 'log', $location) if ($location);
176 $location = getbuglocation($bugnum, 'log.gz');
177 return getbugcomponent($bugnum, 'log.gz', $location) if ($location);
186 Returns the path to the summary file corresponding to the bug.
188 Returns undef if the bug does not exist.
194 my $location = getbuglocation($bugnum, 'summary');
195 return getbugcomponent($bugnum, 'summary', $location) if ($location);
201 appendfile($file,'data','to','append');
203 Opens a file for appending and writes data to it.
208 my ($file,@data) = @_;
209 my $fh = IO::File->new($file,'a') or
210 die "Unable top open $file for appending: $!";
211 print {$fh} @data or die "Unable to write to $file: $!";
212 close $fh or die "Unable to close $file: $!";
215 =head2 getparsedaddrs
217 my $address = getparsedaddrs($address);
218 my @address = getparsedaddrs($address);
220 Returns the output from Mail::Address->parse, or the cached output if
221 this address has been parsed before. In SCALAR context returns the
222 first address parsed.
230 return () unless defined $addr;
231 return wantarray?@{$_parsedaddrs{$addr}}:$_parsedaddrs{$addr}[0]
232 if exists $_parsedaddrs{$addr};
234 # don't display the warnings from Mail::Address->parse
235 local $SIG{__WARN__} = sub { };
236 @{$_parsedaddrs{$addr}} = Mail::Address->parse($addr);
238 return wantarray?@{$_parsedaddrs{$addr}}:$_parsedaddrs{$addr}[0];
241 =head2 getmaintainers
243 my $maintainer = getmaintainers()->{debbugs}
245 Returns a hashref of package => maintainer pairs.
250 our $_maintainer_rev;
252 return $_maintainer if $_maintainer;
255 for my $file (@config{qw(maintainer_file maintainer_file_override pseduo_maint_file)}) {
256 next unless defined $file;
257 my $maintfile = IO::File->new($file,'r') or
258 die "Unable to open maintainer file $file: $!";
259 while(<$maintfile>) {
260 next unless m/^(\S+)\s+(\S.*\S)\s*$/;
264 for my $maint (map {lc($_->address)} getparsedaddrs($b)) {
265 push @{$maintainer_rev{$maint}},$a;
270 $_maintainer = \%maintainer;
271 $_maintainer_rev = \%maintainer_rev;
275 =head2 getmaintainers_reverse
277 my @packages = @{getmaintainers_reverse->{'don@debian.org'}||[]};
279 Returns a hashref of maintainer => [qw(list of packages)] pairs.
283 sub getmaintainers_reverse{
284 return $_maintainer_rev if $_maintainer_rev;
286 return $_maintainer_rev;
291 my $pseudopkgdesc = getpseudodesc(...);
293 Returns the entry for a pseudo package from the
294 $config{pseudo_desc_file}. In cases where pseudo_desc_file is not
295 defined, returns an empty arrayref.
297 This function can be used to see if a particular package is a
298 pseudopackage or not.
304 return $_pseudodesc if $_pseudodesc;
307 if (not defined $config{pseudo_desc_file}) {
311 my $pseudo = IO::File->new($config{pseudo_desc_file},'r')
312 or die "Unable to open $config{pseudo_desc_file}: $!";
314 next unless m/^(\S+)\s+(\S.*\S)\s*$/;
315 $pseudodesc{lc $1} = $2;
318 $_pseudodesc = \%pseudodesc;
325 my $english = secs_to_english($seconds);
326 my ($days,$english) = secs_to_english($seconds);
328 XXX This should probably be changed to use Date::Calc
335 my $days = int($seconds / 86400);
336 my $years = int($days / 365);
340 push @age, "1 year" if ($years == 1);
341 push @age, "$years years" if ($years > 1);
342 push @age, "1 day" if ($days == 1);
343 push @age, "$days days" if ($days > 1);
344 $result .= join(" and ", @age);
346 return wantarray?(int($seconds/86400),$result):$result;
352 These functions are exported with the :lock tag
358 FLOCKs the passed file. Use unfilelock to unlock it.
365 # NB - NOT COMPATIBLE WITH `with-lock'
367 if ($lockfile !~ m{^/}) {
368 $lockfile = cwd().'/'.$lockfile;
371 $count= 10; $errors= '';
374 my $fh2 = IO::File->new($lockfile,'w')
375 or die "Unable to open $lockfile for writing: $!";
376 flock($fh2,LOCK_EX|LOCK_NB)
377 or die "Unable to lock $lockfile $!";
384 push @filelocks, {fh => $fh, file => $lockfile};
389 die "failed to get lock on $lockfile -- $errors";
395 # clean up all outstanding locks at end time
407 Unlocks the file most recently locked.
409 Note that it is not currently possible to unlock a specific file
410 locked with filelock.
415 if (@filelocks == 0) {
416 warn "unfilelock called with no active filelocks!\n";
419 my %fl = %{pop(@filelocks)};
420 flock($fl{fh},LOCK_UN)
421 or warn "Unable to unlock lockfile $fl{file}: $!";
423 or warn "Unable to close lockfile $fl{file}: $!";
425 or warn "Unable to unlink lockfile $fl{file}: $!";
431 lockpid('/path/to/pidfile');
433 Creates a pidfile '/path/to/pidfile' if one doesn't exist or if the
434 pid in the file does not respond to kill 0.
436 Returns 1 on success, false on failure; dies on unusual errors.
443 my $pid = checkpid($pidfile);
444 die "Unable to read pidfile $pidfile: $!" if not defined $pid;
445 return 0 if $pid != 0;
447 die "Unable to unlink stale pidfile $pidfile $!";
449 my $pidfh = IO::File->new($pidfile,'w') or
450 die "Unable to open $pidfile for writing: $!";
451 print {$pidfh} $$ or die "Unable to write to $pidfile $!";
452 close $pidfh or die "Unable to close $pidfile $!";
458 checkpid('/path/to/pidfile');
460 Checks a pid file and determines if the process listed in the pidfile
461 is still running. Returns the pid if it is, 0 if it isn't running, and
462 undef if the pidfile doesn't exist or cannot be read.
469 my $pidfh = IO::File->new($pidfile, 'r') or
474 ($pid) = $pid =~ /(\d+)/;
475 if (defined $pid and kill(0,$pid)) {
488 These functions are exported with the :quit tag.
494 Exits the program by calling die.
496 Usage of quit is deprecated; just call die instead.
501 print {$DEBUG_FH} "quitting >$_[0]<\n" if $DEBUG;
502 carp "quit() is deprecated; call die directly instead";
508 These functions are exported with the :misc tag
512 LIST = make_list(@_);
514 Turns a scalar or an arrayref into a list; expands a list of arrayrefs
517 That is, make_list([qw(a b c)]); returns qw(a b c); make_list([qw(a
518 b)],[qw(c d)] returns qw(a b c d);
523 return map {(ref($_) eq 'ARRAY')?@{$_}:$_} @_;
529 print english_join(list => \@list);
530 print english_join(\@list);
532 Joins list properly to make an english phrase.
536 =item normal -- how to separate most values; defaults to ', '
538 =item last -- how to separate the last two values; defaults to ', and '
540 =item only_two -- how to separate only two values; defaults to ' and '
542 =item list -- ARRAYREF values to join; if the first argument is an
543 ARRAYREF, it's assumed to be the list of values to join
547 In cases where C<list> is empty, returns ''; when there is only one
548 element, returns that element.
553 if (ref $_[0] eq 'ARRAY') {
554 return english_join(list=>$_[0]);
556 my %param = validate_with(params => \@_,
557 spec => {normal => {type => SCALAR,
560 last => {type => SCALAR,
563 only_two => {type => SCALAR,
566 list => {type => ARRAYREF,
570 my @list = @{$param{list}};
572 return @list?$list[0]:'';
575 return join($param{only_two},@list);
577 my $ret = $param{last} . pop(@list);
578 return join($param{normal},@list) . $ret;
582 =head2 globify_scalar
584 my $handle = globify_scalar(\$foo);
586 if $foo isn't already a glob or a globref, turn it into one using
587 IO::Scalar. Gives a new handle to /dev/null if $foo isn't defined.
589 Will carp if given a scalar which isn't a scalarref or a glob (or
590 globref), and return /dev/null. May return undef if IO::Scalar or
591 IO::File fails. (Check $!)
598 if (defined $scalar) {
599 if (defined ref($scalar)) {
600 if (ref($scalar) eq 'SCALAR' and
601 not UNIVERSAL::isa($scalar,'GLOB')) {
602 return IO::Scalar->new($scalar);
608 elsif (UNIVERSAL::isa(\$scalar,'GLOB')) {
612 carp "Given a non-scalar reference, non-glob to globify_scalar; returning /dev/null handle";
615 return IO::File->new('/dev/null','w');