FileHandle.pm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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(:signal_h :sys_wait_h);
  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;
  189. }
  190. sub EOF {
  191. # Since perl 5.12, an integer parameter is passed describing how the
  192. # function got called, just ignore it.
  193. my ($self, $param) = (shift, shift);
  194. return *$self->{file}->eof(@_) if defined *$self->{file};
  195. return 1;
  196. }
  197. sub SEEK {
  198. my ($self) = shift;
  199. return *$self->{file}->seek(@_) if defined *$self->{file};
  200. return 0;
  201. }
  202. sub TELL {
  203. my ($self) = shift;
  204. return *$self->{file}->tell(@_) if defined *$self->{file};
  205. return -1;
  206. }
  207. sub BINMODE {
  208. my ($self) = shift;
  209. return *$self->{file}->binmode(@_) if defined *$self->{file};
  210. return;
  211. }
  212. ##
  213. ## NORMAL METHODS
  214. ##
  215. =item $fh->set_compression($comp)
  216. Defines the compression method used. $comp should one of the methods supported by
  217. B<Dpkg::Compression> or "none" or "auto". "none" indicates that the file is
  218. uncompressed and "auto" indicates that the method must be guessed based
  219. on the filename extension used.
  220. =cut
  221. sub set_compression {
  222. my ($self, $method) = @_;
  223. if ($method ne "none" and $method ne "auto") {
  224. *$self->{compressor}->set_compression($method);
  225. }
  226. *$self->{compression} = $method;
  227. }
  228. =item $fh->set_compression_level($level)
  229. Indicate the desired compression level. It should be a value accepted
  230. by the function C<compression_is_valid_level> of B<Dpkg::Compression>.
  231. =cut
  232. sub set_compression_level {
  233. my ($self, $level) = @_;
  234. *$self->{compressor}->set_compression_level($level);
  235. }
  236. =item $fh->set_filename($name, [$add_comp_ext])
  237. Use $name as filename when the file must be opened/created. If
  238. $add_comp_ext is passed, it indicates whether the default extension
  239. of the compression method must be automatically added to the filename
  240. (or not).
  241. =cut
  242. sub set_filename {
  243. my ($self, $filename, $add_comp_ext) = @_;
  244. *$self->{filename} = $filename;
  245. # Automatically add compression extension to filename
  246. if (defined($add_comp_ext)) {
  247. *$self->{add_comp_ext} = $add_comp_ext;
  248. }
  249. if (*$self->{add_comp_ext} and $filename =~ /\.$compression_re_file_ext$/) {
  250. warning("filename %s already has an extension of a compressed file " .
  251. "and add_comp_ext is active", $filename);
  252. }
  253. }
  254. =item my $file = $fh->get_filename()
  255. Returns the filename that would be used when the filehandle must
  256. be opened (both in read and write mode). This function errors out
  257. if "add_comp_ext" is enableactivated while the compression method is set
  258. to "auto". The returned filename includes the extension of the compression
  259. method if "add_comp_ext" is enabled.
  260. =cut
  261. sub get_filename {
  262. my $self = shift;
  263. my $comp = *$self->{compression};
  264. if (*$self->{add_comp_ext}) {
  265. if ($comp eq "auto") {
  266. internerr("automatic detection of compression is " .
  267. "incompatible with add_comp_ext");
  268. } elsif ($comp eq "none") {
  269. return *$self->{filename};
  270. } else {
  271. return *$self->{filename} . "." .
  272. compression_get_property($comp, "file_ext");
  273. }
  274. } else {
  275. return *$self->{filename};
  276. }
  277. }
  278. =item $ret = $fh->use_compression()
  279. Returns "0" if no compression is used and the compression method used
  280. otherwise. If the compression is set to "auto", the value returned
  281. depends on the extension of the filename obtained with the B<get_filename>
  282. method.
  283. =cut
  284. sub use_compression {
  285. my ($self) = @_;
  286. my $comp = *$self->{compression};
  287. if ($comp eq "none") {
  288. return 0;
  289. } elsif ($comp eq "auto") {
  290. $comp = compression_guess_from_filename($self->get_filename());
  291. *$self->{compressor}->set_compression($comp) if $comp;
  292. }
  293. return $comp;
  294. }
  295. =item my $real_fh = $fh->get_filehandle()
  296. Returns the real underlying filehandle. Useful if you want to pass it
  297. along in a derived object.
  298. =cut
  299. sub get_filehandle {
  300. my ($self) = @_;
  301. return *$self->{file} if exists *$self->{file};
  302. }
  303. ## INTERNAL METHODS
  304. sub open_for_write {
  305. my ($self) = @_;
  306. error("Can't reopen an already opened compressed file") if exists *$self->{mode};
  307. my $filehandle;
  308. if ($self->use_compression()) {
  309. *$self->{compressor}->compress(from_pipe => \$filehandle,
  310. to_file => $self->get_filename());
  311. } else {
  312. CORE::open($filehandle, ">", $self->get_filename) ||
  313. syserr(_g("cannot write %s"), $self->get_filename());
  314. }
  315. *$self->{mode} = "w";
  316. *$self->{file} = $filehandle;
  317. }
  318. sub open_for_read {
  319. my ($self) = @_;
  320. error("Can't reopen an already opened compressed file") if exists *$self->{mode};
  321. my $filehandle;
  322. if ($self->use_compression()) {
  323. *$self->{compressor}->uncompress(to_pipe => \$filehandle,
  324. from_file => $self->get_filename());
  325. *$self->{allow_sigpipe} = 1;
  326. } else {
  327. CORE::open($filehandle, "<", $self->get_filename) ||
  328. syserr(_g("cannot read %s"), $self->get_filename());
  329. }
  330. *$self->{mode} = "r";
  331. *$self->{file} = $filehandle;
  332. }
  333. sub cleanup {
  334. my ($self) = @_;
  335. my $cmdline = *$self->{compressor}{cmdline} || "";
  336. *$self->{compressor}->wait_end_process(nocheck => *$self->{allow_sigpipe});
  337. if (*$self->{allow_sigpipe}) {
  338. unless (($? == 0) || (WIFSIGNALED($?) && (WTERMSIG($?) == SIGPIPE))) {
  339. subprocerr($cmdline);
  340. }
  341. *$self->{allow_sigpipe} = 0;
  342. }
  343. delete *$self->{mode};
  344. delete *$self->{file};
  345. }
  346. =back
  347. =head1 DERIVED OBJECTS
  348. If you want to create an object that inherits from
  349. Dpkg::Compression::FileHandle you must be aware that
  350. the object is a reference to a GLOB that is returned by Symbol::gensym()
  351. and as such it's not a HASH.
  352. You can store internal data in a hash but you have to use
  353. C<*$self->{...}> to access the associated hash like in the example below:
  354. sub set_option {
  355. my ($self, $value) = @_;
  356. *$self->{option} = $value;
  357. }
  358. =head1 AUTHOR
  359. Raphaël Hertzog <hertzog@debian.org>
  360. =cut
  361. 1;