FileHandle.pm 12 KB

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