1 # -*- coding: utf-8 -*-
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
10 class OutputFile(object):
11 """Represents a file returned by one of the converters."""
18 os.unlink(self._filename)
20 def __nonzero__(self):
21 return self._string is not None or self._filename is not None
24 def from_string(cls, string):
25 """Converter returns contents of a file as a string."""
28 instance._string = string
32 def from_filename(cls, filename):
33 """Converter returns contents of a file as a named file."""
36 instance._filename = filename
40 """Get file's contents as a string."""
42 if self._filename is not None:
43 with open(self._filename) as f:
49 """Get file as a file-like object."""
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)
57 def get_filename(self):
58 """Get file as a fs path."""
60 if self._filename is not None:
62 elif self._string is not None:
63 from tempfile import NamedTemporaryFile
64 temp = NamedTemporaryFile(prefix='librarian-', delete=False)
65 temp.write(self._string)
67 self._filename = temp.name
72 def save_as(self, path):
73 """Save file to a path. Create directories, if necessary."""
75 dirname = os.path.dirname(os.path.abspath(path))
76 if not os.path.isdir(dirname):
78 shutil.copy(self.get_filename(), path)