FileHandle.pm 13 KB

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