]> git.donarmstrong.com Git - term-progressbar-io.git/blob - lib/Term/ProgressBar/IO.pm
initial work on Term::ProgressBar::IO
[term-progressbar-io.git] / lib / Term / ProgressBar / IO.pm
1 # This module is part of IO, and is released
2 # under the terms of the GPL version 3, or any later version at your option. See the
3 # file README and COPYING for more information.
4 # Copyright 2014 by Don Armstrong <don@donarmstrong.com>.
5
6 package Term::ProgressBar::IO;
7
8 =head1 NAME
9
10 Term::ProgressBar::IO -- Display a progress bar while reading from a seekable filehandle
11
12 =head1 SYNOPSIS
13
14   my $pb = Term::ProgressBar::IO->new($fh);
15
16   while (<$fh>) {
17       $pb->update();
18   }
19
20 =head1 DESCRIPTION
21
22 Displays a progress bar using L<Term::ProgressBar> which corresponds
23 to reading from a filehandle.
24
25 =head1 BUGS
26
27 None known.
28
29 =cut
30
31 use warnings;
32 use strict;
33 use vars qw($VERSION $DEBUG);
34
35 use parent qw(Term::ProgressBar);
36 use Carp;
37 use Fcntl qw(:seek);
38
39 BEGIN{
40      $VERSION = q(0.1);
41      $DEBUG = 0 unless defined $DEBUG;
42 }
43
44 sub init {
45     my $self = shift;
46     my $count;
47     if (@_==2) {
48         $count = $_[1];
49     } else {
50         croak
51             sprintf("Term::ProgressBar::IO::new We don't handle this many arguments: %d",
52                     scalar @_)
53             if @_ != 1;
54     }
55     my %config;
56     if ( UNIVERSAL::isa ($_[0], 'HASH') ) {
57         ($count) = @{$_[0]}{qw(count)};
58         %config = %{$_[0]};
59     } else {
60         ($count) = @_;
61     }
62     if (ref($count) and $count->can("seek")) {
63         $self->{__filehandle} = $count;
64         $count = $self->__determine_max();
65     }
66     $config{count} = $count;
67     $self->SUPER::init(\%config);
68 }
69
70 sub update {
71     my $self = shift;
72     my $count = $self->__determine_count();
73     $self->SUPER::update(scalar @_? @_ : $count);
74 }
75
76 sub __determine_max {
77     my $self = shift;
78     # is this an IO::Uncompress handle?
79     my $max = 0;
80     if ($self->{__filehandle}->can('getHeaderInfo')) {
81         $self->{__filehandle} = *$self->{__filehandle}{FH};
82     }
83     eval {
84         my $cur_pos = $self->{__filehandle}->tell;
85         $self->{__filehandle}->seek(0,SEEK_END);
86         $max = $self->{__filehandle}->tell;
87         $self->{__filehandle}->seek($cur_pos,SEEK_SET);
88     };
89     return $max;
90 }
91
92 sub __determine_count {
93     my $self = shift;
94     my $count = 0;
95     eval {
96         $count = $self->{__filehandle}->tell;
97     };
98     return $count;
99 }
100
101 1;
102
103
104 __END__
105
106
107
108
109
110