FileHandle.pm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. # Copyright © 2008-2010 Raphaël Hertzog <hertzog@debian.org>
  2. #
  3. # This program is free software; you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation; either version 2 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. package Dpkg::Compression::FileHandle;
  16. use strict;
  17. use warnings;
  18. our $VERSION = "1.00";
  19. use Dpkg::Compression;
  20. use Dpkg::Compression::Process;
  21. use Dpkg::Gettext;
  22. use Dpkg::ErrorHandling;
  23. use POSIX qw(WIFSIGNALED WTERMSIG SIGPIPE);
  24. use base qw(FileHandle Tie::Handle);
  25. # Useful reference to understand some kludges required to
  26. # have the object behave like a filehandle
  27. # http://blog.woobling.org/2009/10/are-filehandles-objects.html
  28. =encoding utf8
  29. =head1 NAME
  30. Dpkg::Compression::FileHandle - object dealing transparently with file compression
  31. =head1 SYNOPSIS
  32. use Dpkg::Compression::FileHandle;
  33. $fh = Dpkg::Compression::FileHandle->new(filename=>"sample.gz");
  34. print $fh "Something\n";
  35. close $fh;
  36. $fh = Dpkg::Compression::FileHandle->new();
  37. open($fh, ">", "sample.bz2");
  38. print $fh "Something\n";
  39. close $fh;
  40. $fh = Dpkg::Compression::FileHandle->new();
  41. $fh->open("sample.xz", "w");
  42. $fh->print("Something\n");
  43. $fh->close();
  44. $fh = Dpkg::Compression::FileHandle->new(filename=>"sample.gz");
  45. my @lines = <$fh>;
  46. close $fh;
  47. $fh = Dpkg::Compression::FileHandle->new();
  48. open($fh, "<", "sample.bz2");
  49. my @lines = <$fh>;
  50. close $fh;
  51. $fh = Dpkg::Compression::FileHandle->new();
  52. $fh->open("sample.xz", "r");
  53. my @lines = $fh->getlines();
  54. $fh->close();
  55. =head1 DESCRIPTION
  56. Dpkg::Compression::FileHandle is an object that can be used
  57. like any filehandle and that deals transparently with compressed
  58. files. By default, the compression scheme is guessed from the filename
  59. but you can override this behaviour with the method C<set_compression>.
  60. If you don't open the file explicitly, it will be auto-opened on the
  61. first read or write operation based on the filename set at creation time
  62. (or later with the C<set_filename> method).
  63. Once a file has been opened, the filehandle must be closed before being
  64. able to open another file.
  65. =head1 STANDARD FUNCTIONS
  66. The standard functions acting on filehandles should accept a
  67. Dpkg::Compression::FileHandle object transparently including
  68. C<open> (only when using the variant with 3 parameters), C<close>,
  69. C<binmode>, C<eof>, C<fileno>, C<getc>, C<print>, C<printf>, C<read>,
  70. C<sysread>, C<say>, C<write>, C<syswrite>, C<seek>, C<sysseek>, C<tell>.
  71. Note however that C<seek> and C<sysseek> will only work on uncompressed
  72. files as compressed files are really pipes to the compressor programs
  73. and you can't seek on a pipe.
  74. =head1 FileHandle METHODS
  75. The object inherits from FileHandle so all methods that work on this
  76. object should work for Dpkg::Compression::FileHandle too. There
  77. may be exceptions though.
  78. =head1 PUBLIC METHODS
  79. =over 4
  80. =item my $fh = Dpkg::Compression::FileHandle->new(%opts)
  81. Creates a new filehandle supporting on-the-fly compression/decompression.
  82. Supported options are "filename", "compression", "compression_level" (see
  83. respective set_* functions) and "add_comp_ext". If "add_comp_ext"
  84. evaluates to true, then the extension corresponding to the selected
  85. compression scheme is automatically added to the recorded filename. It's
  86. obviously incompatible with automatic detection of the compression method.
  87. =cut
  88. # Object methods
  89. sub new {
  90. my ($this, %args) = @_;
  91. my $class = ref($this) || $this;
  92. my $self = FileHandle->new();
  93. # Tying is required to overload the open functions and to auto-open
  94. # the file on first read/write operation
  95. tie *$self, $class, $self;
  96. bless $self, $class;
  97. # Initializations
  98. *$self->{"compression"} = "auto";
  99. *$self->{"compressor"} = Dpkg::Compression::Process->new();
  100. *$self->{"add_comp_ext"} = $args{"add_compression_extension"} ||
  101. $args{"add_comp_ext"} || 0;
  102. *$self->{"allow_sigpipe"} = 0;
  103. if (exists $args{"filename"}) {
  104. $self->set_filename($args{"filename"});
  105. }
  106. if (exists $args{"compression"}) {
  107. $self->set_compression($args{"compression"});
  108. }
  109. if (exists $args{"compression_level"}) {
  110. $self->set_compression_level($args{"compression_level"});
  111. }
  112. return $self;
  113. }
  114. =item $fh->ensure_open($mode)
  115. Ensure the file is opened in the requested mode ("r" for read and "w" for
  116. write). Opens the file with the recorded filename if needed. If the file
  117. is already open but not in the requested mode, then it errors out.
  118. =cut
  119. sub ensure_open {
  120. my ($self, $mode) = @_;
  121. if (exists *$self->{"mode"}) {
  122. return if *$self->{"mode"} eq $mode;
  123. internerr("ensure_open requested incompatible mode: $mode");
  124. } else {
  125. if ($mode eq "w") {
  126. $self->open_for_write();
  127. } elsif ($mode eq "r") {
  128. $self->open_for_read();
  129. } else {
  130. internerr("invalid mode in ensure_open: $mode");
  131. }
  132. }
  133. }
  134. ##
  135. ## METHODS FOR TIED HANDLE
  136. ##
  137. sub TIEHANDLE {
  138. my ($class, $self) = @_;
  139. return $self;
  140. }
  141. sub WRITE {
  142. my ($self, $scalar, $length, $offset) = @_;
  143. $self->ensure_open("w");
  144. return *$self->{'file'}->write($scalar, $length, $offset);
  145. }
  146. sub READ {
  147. my ($self, $scalar, $length, $offset) = @_;
  148. $self->ensure_open("r");
  149. return *$self->{'file'}->read($scalar, $length, $offset);
  150. }
  151. sub READLINE {
  152. my ($self) = shift;
  153. $self->ensure_open("r");
  154. return *$self->{"file"}->getlines() if wantarray;
  155. return *$self->{"file"}->getline();
  156. }
  157. sub OPEN {
  158. my ($self) = shift;
  159. if (scalar(@_) == 2) {
  160. my ($mode, $filename) = @_;
  161. $self->set_filename($filename);
  162. if ($mode eq ">") {
  163. $self->open_for_write();
  164. } elsif ($mode eq "<") {
  165. $self->open_for_read();
  166. } else {
  167. internerr("Unsupported open mode on Dpkg::Compression::FileHandle: $mode");
  168. }
  169. } else {
  170. internerr("Dpkg::Compression::FileHandle only supports open() with 3 parameters");
  171. }
  172. return 1; # Always works (otherwise errors out)
  173. }
  174. sub CLOSE {
  175. my ($self) = shift;
  176. my $ret = 1;
  177. if (defined *$self->{'file'}) {
  178. $ret = *$self->{'file'}->close(@_) if *$self->{'file'}->opened();
  179. } else {
  180. $ret = 0;
  181. }
  182. $self->cleanup();
  183. return $ret;
  184. }
  185. sub FILENO {
  186. my ($self) = shift;
  187. return *$self->{"file"}->fileno(@_) if defined *$self->{"file"};
  188. return undef;
  189. }
  190. sub EOF {
  191. my ($self) = shift;
  192. return *$self->{"file"}->eof(@_) if defined *$self->{"file"};
  193. return 1;
  194. }
  195. sub SEEK {
  196. my ($self) = shift;
  197. return *$self->{"file"}->seek(@_) if defined *$self->{"file"};
  198. return 0;
  199. }
  200. sub TELL {
  201. my ($self) = shift;
  202. return *$self->{"file"}->tell(@_) if defined *$self->{"file"};
  203. return -1;
  204. }
  205. sub BINMODE {
  206. my ($self) = shift;
  207. return *$self->{"file"}->binmode(@_) if defined *$self->{"file"};
  208. return undef;
  209. }
  210. ##
  211. ## NORMAL METHODS
  212. ##
  213. =item $fh->set_compression($comp)
  214. Defines the compression method used. $comp should one of the methods supported by
  215. B<Dpkg::Compression> or "none" or "auto". "none" indicates that the file is
  216. uncompressed and "auto" indicates that the method must be guessed based
  217. on the filename extension used.
  218. =cut
  219. sub set_compression {
  220. my ($self, $method) = @_;
  221. if ($method ne "none" and $method ne "auto") {
  222. *$self->{"compressor"}->set_compression($method);
  223. }
  224. *$self->{"compression"} = $method;
  225. }
  226. =item $fh->set_compression_level($level)
  227. Indicate the desired compression level. It should be a value accepted
  228. by the function C<compression_is_valid_level> of B<Dpkg::Compression>.
  229. =cut
  230. sub set_compression_level {
  231. my ($self, $level) = @_;
  232. *$self->{"compressor"}->set_compression_level($level);
  233. }
  234. =item $fh->set_filename($name, [$add_comp_ext])
  235. Use $name as filename when the file must be opened/created. If
  236. $add_comp_ext is passed, it indicates whether the default extension
  237. of the compression method must be automatically added to the filename
  238. (or not).
  239. =cut
  240. sub set_filename {
  241. my ($self, $filename, $add_comp_ext) = @_;
  242. *$self->{"filename"} = $filename;
  243. # Automatically add compression extension to filename
  244. if (defined($add_comp_ext)) {
  245. *$self->{"add_comp_ext"} = $add_comp_ext;
  246. }
  247. if (*$self->{"add_comp_ext"} and $filename =~ /\.$compression_re_file_ext$/) {
  248. warning("filename %s already has an extension of a compressed file " .
  249. "and add_comp_ext is active", $filename);
  250. }
  251. }
  252. =item my $file = $fh->get_filename()
  253. Returns the filename that would be used when the filehandle must
  254. be opened (both in read and write mode). This function errors out
  255. if "add_comp_ext" is enableactivated while the compression method is set
  256. to "auto". The returned filename includes the extension of the compression
  257. method if "add_comp_ext" is enabled.
  258. =cut
  259. sub get_filename {
  260. my $self = shift;
  261. my $comp = *$self->{"compression"};
  262. if (*$self->{'add_comp_ext'}) {
  263. if ($comp eq "auto") {
  264. internerr("automatic detection of compression is " .
  265. "incompatible with add_comp_ext");
  266. } elsif ($comp eq "none") {
  267. return *$self->{"filename"};
  268. } else {
  269. return *$self->{"filename"} . "." .
  270. compression_get_property($comp, "file_ext");
  271. }
  272. } else {
  273. return *$self->{"filename"};
  274. }
  275. }
  276. =item $ret = $fh->use_compression()
  277. Returns "0" if no compression is used and the compression method used
  278. otherwise. If the compression is set to "auto", the value returned
  279. depends on the extension of the filename obtained with the B<get_filename>
  280. method.
  281. =cut
  282. sub use_compression {
  283. my ($self) = @_;
  284. my $comp = *$self->{"compression"};
  285. if ($comp eq "none") {
  286. return 0;
  287. } elsif ($comp eq "auto") {
  288. $comp = compression_guess_from_filename($self->get_filename());
  289. *$self->{"compressor"}->set_compression($comp) if $comp;
  290. }
  291. return $comp;
  292. }
  293. =item my $real_fh = $fh->get_filehandle()
  294. Returns the real underlying filehandle. Useful if you want to pass it
  295. along in a derived object.
  296. =cut
  297. sub get_filehandle {
  298. my ($self) = @_;
  299. return *$self->{"file"} if exists *$self->{"file"};
  300. }
  301. ## INTERNAL METHODS
  302. sub open_for_write {
  303. my ($self) = @_;
  304. error("Can't reopen an already opened compressed file") if exists *$self->{"mode"};
  305. my $filehandle;
  306. if ($self->use_compression()) {
  307. *$self->{'compressor'}->compress(from_pipe => \$filehandle,
  308. to_file => $self->get_filename());
  309. } else {
  310. CORE::open($filehandle, ">", $self->get_filename) ||
  311. syserr(_g("cannot write %s"), $self->get_filename());
  312. }
  313. *$self->{"mode"} = "w";
  314. *$self->{"file"} = $filehandle;
  315. }
  316. sub open_for_read {
  317. my ($self) = @_;
  318. error("Can't reopen an already opened compressed file") if exists *$self->{"mode"};
  319. my $filehandle;
  320. if ($self->use_compression()) {
  321. *$self->{'compressor'}->uncompress(to_pipe => \$filehandle,
  322. from_file => $self->get_filename());
  323. *$self->{'allow_sigpipe'} = 1;
  324. } else {
  325. CORE::open($filehandle, "<", $self->get_filename) ||
  326. syserr(_g("cannot read %s"), $self->get_filename());
  327. }
  328. *$self->{"mode"} = "r";
  329. *$self->{"file"} = $filehandle;
  330. }
  331. sub cleanup {
  332. my ($self) = @_;
  333. my $cmdline = *$self->{"compressor"}{"cmdline"} || "";
  334. *$self->{"compressor"}->wait_end_process(nocheck => *$self->{'allow_sigpipe'});
  335. if (*$self->{'allow_sigpipe'}) {
  336. unless (($? == 0) || (WIFSIGNALED($?) && (WTERMSIG($?) == SIGPIPE))) {
  337. subprocerr($cmdline);
  338. }
  339. *$self->{'allow_sigpipe'} = 0;
  340. }
  341. delete *$self->{"mode"};
  342. delete *$self->{"file"};
  343. }
  344. =back
  345. =head1 DERIVED OBJECTS
  346. If you want to create an object that inherits from
  347. Dpkg::Compression::FileHandle you must be aware that
  348. the object is a reference to a GLOB that is returned by Symbol::gensym()
  349. and as such it's not a HASH.
  350. You can store internal data in a hash but you have to use
  351. C<*$self->{...}> to access the associated hash like in the example below:
  352. sub set_option {
  353. my ($self, $value) = @_;
  354. *$self->{"option"} = $value;
  355. }
  356. =head1 AUTHOR
  357. Raphaël Hertzog <hertzog@debian.org>
  358. =cut
  359. 1;