FileHandle.pm 12 KB

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