61 lines
1.8 KiB
Python
61 lines
1.8 KiB
Python
# tabularfile.writer - tabular file for humans
|
|
# Copyright (C) 2020 Entr'ouvert
|
|
#
|
|
# This program is free software: you can redistribute it and/or modify it
|
|
# under the terms of the GNU Affero General Public License as published
|
|
# by the Free Software Foundation, either version 3 of the License, or
|
|
# (at your option) any later version.
|
|
#
|
|
# This program is distributed in the hope that it will be useful,
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
# GNU Affero General Public License for more details.
|
|
#
|
|
# You should have received a copy of the GNU Affero General Public License
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
import contextlib
|
|
import io
|
|
import weakref
|
|
|
|
from .common import TabularFileError
|
|
|
|
|
|
@contextlib.contextmanager
|
|
def fh_from_path_or_file(path_or_file):
|
|
if isinstance(path_or_file, io.IOBase):
|
|
if not path_or_file.writable or not path_or_file.seekable:
|
|
raise TabularFileError('file handle must be writable and seekable')
|
|
yield path_or_file
|
|
else:
|
|
with open(path_or_file, 'wb') as fh:
|
|
yield fh
|
|
|
|
|
|
class WeakrefHolder:
|
|
def __init__(self, value):
|
|
self.value = value
|
|
|
|
def __enter__(self):
|
|
return weakref.proxy(self.value)
|
|
|
|
def __exit__(self, a, b, c):
|
|
self.value = None
|
|
|
|
|
|
@contextlib.contextmanager
|
|
def write(path_or_file, format='ods', **kwargs):
|
|
from . import ods, csv
|
|
|
|
with fh_from_path_or_file(path_or_file) as fh:
|
|
if format == 'ods':
|
|
context = ods.writer(fh, **kwargs)
|
|
elif format == 'csv':
|
|
context = csv.writer(fh, **kwargs)
|
|
else:
|
|
raise ValueError('invalid format %r' % format)
|
|
|
|
with context as _writer:
|
|
with WeakrefHolder(_writer) as proxy:
|
|
yield proxy
|