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),
43 qw(getmaintainers_reverse),
46 misc => [qw(make_list globify_scalar english_join checkpid)],
47 date => [qw(secs_to_english)],
49 lock => [qw(filelock unfilelock lockpid)],
52 Exporter::export_ok_tags(qw(lock quit date util misc));
53 $EXPORT_TAGS{all} = [@EXPORT_OK];
56 #use Debbugs::Config qw(:globals);
60 use Debbugs::Config qw(:config);
63 use Debbugs::MIME qw(decode_rfc1522);
67 use Params::Validate qw(validate_with :types);
71 our $DEBUG_FH = \*STDERR if not defined $DEBUG_FH;
75 The following functions are exported by the C<:util> tag
77 =head2 getbugcomponent
79 my $file = getbugcomponent($bug_number,$extension,$location)
81 Returns the path to the bug file in location C<$location>, bug number
82 C<$bugnumber> and extension C<$extension>
87 my ($bugnum, $ext, $location) = @_;
89 if (not defined $location) {
90 $location = getbuglocation($bugnum, $ext);
91 # Default to non-archived bugs only for now; CGI scripts want
92 # archived bugs but most of the backend scripts don't. For now,
93 # anything that is prepared to accept archived bugs should call
94 # getbuglocation() directly first.
95 return undef if defined $location and
96 ($location ne 'db' and $location ne 'db-h');
98 my $dir = getlocationpath($location);
99 return undef if not defined $dir;
100 if (defined $location and $location eq 'db') {
101 return "$dir/$bugnum.$ext";
103 my $hash = get_hashname($bugnum);
104 return "$dir/$hash/$bugnum.$ext";
108 =head2 getbuglocation
110 getbuglocation($bug_number,$extension)
112 Returns the the location in which a particular bug exists; valid
113 locations returned currently are archive, db-h, or db. If the bug does
114 not exist, returns undef.
119 my ($bugnum, $ext) = @_;
120 my $archdir = get_hashname($bugnum);
121 return 'archive' if -r getlocationpath('archive')."/$archdir/$bugnum.$ext";
122 return 'db-h' if -r getlocationpath('db-h')."/$archdir/$bugnum.$ext";
123 return 'db' if -r getlocationpath('db')."/$bugnum.$ext";
128 =head2 getlocationpath
130 getlocationpath($location)
132 Returns the path to a specific location
136 sub getlocationpath {
138 if (defined $location and $location eq 'archive') {
139 return "$config{spool_dir}/archive";
140 } elsif (defined $location and $location eq 'db') {
141 return "$config{spool_dir}/db";
143 return "$config{spool_dir}/db-h";
152 Returns the hash of the bug which is the location within the archive
157 return "" if ( $_[ 0 ] < 0 );
158 return sprintf "%02d", $_[ 0 ] % 100;
165 Returns the path to the logfile corresponding to the bug.
167 Returns undef if the bug does not exist.
173 my $location = getbuglocation($bugnum, 'log');
174 return getbugcomponent($bugnum, 'log', $location) if ($location);
175 $location = getbuglocation($bugnum, 'log.gz');
176 return getbugcomponent($bugnum, 'log.gz', $location) if ($location);
183 appendfile($file,'data','to','append');
185 Opens a file for appending and writes data to it.
190 my ($file,@data) = @_;
191 my $fh = IO::File->new($file,'a') or
192 die "Unable top open $file for appending: $!";
193 print {$fh} @data or die "Unable to write to $file: $!";
194 close $fh or die "Unable to close $file: $!";
197 =head2 getparsedaddrs
199 my $address = getparsedaddrs($address);
200 my @address = getparsedaddrs($address);
202 Returns the output from Mail::Address->parse, or the cached output if
203 this address has been parsed before. In SCALAR context returns the
204 first address parsed.
212 return () unless defined $addr;
213 return wantarray?@{$_parsedaddrs{$addr}}:$_parsedaddrs{$addr}[0]
214 if exists $_parsedaddrs{$addr};
216 # don't display the warnings from Mail::Address->parse
217 local $SIG{__WARN__} = sub { };
218 @{$_parsedaddrs{$addr}} = Mail::Address->parse($addr);
220 return wantarray?@{$_parsedaddrs{$addr}}:$_parsedaddrs{$addr}[0];
223 =head2 getmaintainers
225 my $maintainer = getmaintainers()->{debbugs}
227 Returns a hashref of package => maintainer pairs.
232 our $_maintainer_rev;
234 return $_maintainer if $_maintainer;
237 for my $file (@config{qw(maintainer_file maintainer_file_override pseduo_maint_file)}) {
238 next unless defined $file;
239 my $maintfile = IO::File->new($file,'r') or
240 die "Unable to open maintainer file $file: $!";
241 while(<$maintfile>) {
242 next unless m/^(\S+)\s+(\S.*\S)\s*$/;
246 for my $maint (map {lc($_->address)} getparsedaddrs($b)) {
247 push @{$maintainer_rev{$maint}},$a;
252 $_maintainer = \%maintainer;
253 $_maintainer_rev = \%maintainer_rev;
257 =head2 getmaintainers_reverse
259 my @packages = @{getmaintainers_reverse->{'don@debian.org'}||[]};
261 Returns a hashref of maintainer => [qw(list of packages)] pairs.
265 sub getmaintainers_reverse{
266 return $_maintainer_rev if $_maintainer_rev;
268 return $_maintainer_rev;
273 my $pseudopkgdesc = getpseudodesc(...);
275 Returns the entry for a pseudo package from the
276 $config{pseudo_desc_file}. In cases where pseudo_desc_file is not
277 defined, returns an empty arrayref.
279 This function can be used to see if a particular package is a
280 pseudopackage or not.
286 return $_pseudodesc if $_pseudodesc;
289 if (not defined $config{pseudo_desc_file}) {
293 my $pseudo = IO::File->new($config{pseudo_desc_file},'r')
294 or die "Unable to open $config{pseudo_desc_file}: $!";
296 next unless m/^(\S+)\s+(\S.*\S)\s*$/;
297 $pseudodesc{lc $1} = $2;
300 $_pseudodesc = \%pseudodesc;
307 my $english = secs_to_english($seconds);
308 my ($days,$english) = secs_to_english($seconds);
310 XXX This should probably be changed to use Date::Calc
317 my $days = int($seconds / 86400);
318 my $years = int($days / 365);
322 push @age, "1 year" if ($years == 1);
323 push @age, "$years years" if ($years > 1);
324 push @age, "1 day" if ($days == 1);
325 push @age, "$days days" if ($days > 1);
326 $result .= join(" and ", @age);
328 return wantarray?(int($seconds/86400),$result):$result;
334 These functions are exported with the :lock tag
340 FLOCKs the passed file. Use unfilelock to unlock it.
347 # NB - NOT COMPATIBLE WITH `with-lock'
349 if ($lockfile !~ m{^/}) {
350 $lockfile = cwd().'/'.$lockfile;
353 $count= 10; $errors= '';
356 my $fh2 = IO::File->new($lockfile,'w')
357 or die "Unable to open $lockfile for writing: $!";
358 flock($fh2,LOCK_EX|LOCK_NB)
359 or die "Unable to lock $lockfile $!";
366 push @filelocks, {fh => $fh, file => $lockfile};
371 die "failed to get lock on $lockfile -- $errors";
377 # clean up all outstanding locks at end time
389 Unlocks the file most recently locked.
391 Note that it is not currently possible to unlock a specific file
392 locked with filelock.
397 if (@filelocks == 0) {
398 warn "unfilelock called with no active filelocks!\n";
401 my %fl = %{pop(@filelocks)};
402 flock($fl{fh},LOCK_UN)
403 or warn "Unable to unlock lockfile $fl{file}: $!";
405 or warn "Unable to close lockfile $fl{file}: $!";
407 or warn "Unable to unlink lockfile $fl{file}: $!";
413 lockpid('/path/to/pidfile');
415 Creates a pidfile '/path/to/pidfile' if one doesn't exist or if the
416 pid in the file does not respond to kill 0.
418 Returns 1 on success, false on failure; dies on unusual errors.
425 my $pid = checkpid($pidfile);
426 die "Unable to read pidfile $pidfile: $!" if not defined $pid;
427 return 0 if $pid != 0;
429 die "Unable to unlink stale pidfile $pidfile $!";
431 my $pidfh = IO::File->new($pidfile,'w') or
432 die "Unable to open $pidfile for writing: $!";
433 print {$pidfh} $$ or die "Unable to write to $pidfile $!";
434 close $pidfh or die "Unable to close $pidfile $!";
440 checkpid('/path/to/pidfile');
442 Checks a pid file and determines if the process listed in the pidfile
443 is still running. Returns the pid if it is, 0 if it isn't running, and
444 undef if the pidfile doesn't exist or cannot be read.
451 my $pidfh = IO::File->new($pidfile, 'r') or
456 ($pid) = $pid =~ /(\d+)/;
457 if (defined $pid and kill(0,$pid)) {
470 These functions are exported with the :quit tag.
476 Exits the program by calling die.
478 Usage of quit is deprecated; just call die instead.
483 print {$DEBUG_FH} "quitting >$_[0]<\n" if $DEBUG;
484 carp "quit() is deprecated; call die directly instead";
490 These functions are exported with the :misc tag
494 LIST = make_list(@_);
496 Turns a scalar or an arrayref into a list; expands a list of arrayrefs
499 That is, make_list([qw(a b c)]); returns qw(a b c); make_list([qw(a
500 b)],[qw(c d)] returns qw(a b c d);
505 return map {(ref($_) eq 'ARRAY')?@{$_}:$_} @_;
511 print english_join(list => \@list);
512 print english_join(\@list);
514 Joins list properly to make an english phrase.
518 =item normal -- how to separate most values; defaults to ', '
520 =item last -- how to separate the last two values; defaults to ', and '
522 =item only_two -- how to separate only two values; defaults to ' and '
524 =item list -- ARRAYREF values to join; if the first argument is an
525 ARRAYREF, it's assumed to be the list of values to join
529 In cases where C<list> is empty, returns ''; when there is only one
530 element, returns that element.
535 if (ref $_[0] eq 'ARRAY') {
536 english_join(list=>$_[0]);
538 my %param = validate_with(param => \@_,
539 spec => {normal => {type => SCALAR,
542 last => {type => SCALAR,
545 only_two => {type => SCALAR,
548 list => {type => ARRAYREF,
552 my @list = @{$param{list}};
554 return @list?$list[0]:'';
557 return join($param{only_two},@list);
559 my $ret = $param{last} . pop(@list);
560 return join($param{normal},@list) . $ret;
564 =head2 globify_scalar
566 my $handle = globify_scalar(\$foo);
568 if $foo isn't already a glob or a globref, turn it into one using
569 IO::Scalar. Gives a new handle to /dev/null if $foo isn't defined.
571 Will carp if given a scalar which isn't a scalarref or a glob (or
572 globref), and return /dev/null. May return undef if IO::Scalar or
573 IO::File fails. (Check $!)
580 if (defined $scalar) {
581 if (defined ref($scalar)) {
582 if (ref($scalar) eq 'SCALAR' and
583 not UNIVERSAL::isa($scalar,'GLOB')) {
584 return IO::Scalar->new($scalar);
590 elsif (UNIVERSAL::isa(\$scalar,'GLOB')) {
594 carp "Given a non-scalar reference, non-glob to globify_scalar; returning /dev/null handle";
597 return IO::File->new('/dev/null','w');