Some experiments with the language: html, epub, covers.
[librarian.git] / librarian / output.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 import os
7 import shutil
8
9
10 class OutputFile(object):
11     """Represents a file returned by one of the converters."""
12
13     _string = None
14     _filename = None
15
16     def __del__(self):
17         if self._filename:
18             os.unlink(self._filename)
19
20     def __nonzero__(self):
21         return self._string is not None or self._filename is not None
22
23     @classmethod
24     def from_string(cls, string):
25         """Converter returns contents of a file as a string."""
26
27         instance = cls()
28         instance._string = string
29         return instance
30
31     @classmethod
32     def from_filename(cls, filename):
33         """Converter returns contents of a file as a named file."""
34
35         instance = cls()
36         instance._filename = filename
37         return instance
38
39     def get_string(self):
40         """Get file's contents as a string."""
41
42         if self._filename is not None:
43             with open(self._filename) as f:
44                 return f.read()
45         else:
46             return self._string
47
48     def get_file(self):
49         """Get file as a file-like object."""
50
51         if self._string is not None:
52             from StringIO import StringIO
53             return StringIO(self._string)
54         elif self._filename is not None:
55             return open(self._filename)
56
57     def get_filename(self):
58         """Get file as a fs path."""
59
60         if self._filename is not None:
61             return self._filename
62         elif self._string is not None:
63             from tempfile import NamedTemporaryFile
64             temp = NamedTemporaryFile(prefix='librarian-', delete=False)
65             temp.write(self._string)
66             temp.close()
67             self._filename = temp.name
68             return self._filename
69         else:
70             return None
71
72     def save_as(self, path):
73         """Save file to a path. Create directories, if necessary."""
74
75         dirname = os.path.dirname(os.path.abspath(path))
76         if not os.path.isdir(dirname):
77             os.makedirs(dirname)
78         shutil.copy(self.get_filename(), path)