aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/vk/tracking/db/format.py
blob: 29f5c4c3e5260bb116fc9fa1a25cea732549a629 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# Copyright (c) 2016 Egor Tensin <egor@tensin.name>
# This file is part of the "VK scripts" project.
# For details, see https://github.com/egor-tensin/vk-scripts
# Distributed under the MIT License.

from enum import auto, StrEnum
import sys

from vk.utils import io

from . import backend


class Format(StrEnum):
    CSV = auto()
    LOG = auto()
    NULL = auto()

    def create_writer(self, fd=sys.stdout):
        if self is Format.CSV:
            return backend.csv.Writer(fd)
        if self is Format.LOG:
            return backend.log.Writer(fd)
        if self is Format.NULL:
            return backend.null.Writer()
        raise NotImplementedError(f"unsupported database format: {self}")

    def open_output_file(self, path=None):
        if self is Format.CSV:
            return self._open_output_database_file(path)
        if self is Format.LOG:
            return self._open_output_log_file(path)
        if self is Format.NULL:
            return self._open_output_database_file(None)
        raise NotImplementedError(f"unsupported database format: {self}")

    @staticmethod
    def _open_output_log_file(path):
        return io.open_output_text_file(path, mode="a")

    @staticmethod
    def _open_output_database_file(path):
        return io.open_output_text_file(path, mode="x")

    def create_reader(self, fd=sys.stdin):
        if self is Format.CSV:
            return backend.csv.Reader(fd)
        if self is Format.LOG:
            return NotImplementedError("cannot read from a log file")
        if self is Format.NULL:
            return backend.null.Reader()
        raise NotImplementedError(f"unsupported database format: {self}")

    def open_input_file(self, path=None):
        if self is Format.CSV:
            return io.open_input_text_file(path)
        if self is Format.LOG:
            raise NotImplementedError("cannot read from a log file")
        if self is Format.NULL:
            return io.open_input_text_file(None)
        raise NotImplementedError(f"unsupported database format: {self}")