Passed
Push — master ( 648e89...feb2f7 )
by Markus
02:11
created

tcllib.dumpmgr.DumpMgrMixin.get_timestamp_random()   A

Complexity

Conditions 1

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nop 0
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
4
# pylint: disable=C0111,C0326,C0103
5
6
"""Tools to manage dumps of API requests."""
7
8
import errno
9
import glob
10
import os
11
import random
12
import time
13
from math import floor
14
15
from . import ansi
16
17
18
class DumpMgrMixin:
0 ignored issues
show
Unused Code introduced by
The variable __class__ seems to be unused.
Loading history...
19
    """A mixin component for XML dump management."""
20
    def __init__(self):
21
        """Populate dump file name."""
22
        self.last_dump_filename = None
23
24
    @staticmethod
25
    def get_timestamp_random():
26
        """Generate timestamp + random part to avoid collisions."""
27
        millis = floor(time.time() * 1000)
28
        tail = "{:06d}".format(random.randint(0, 999999))
29
        return "{}_{}".format(str(millis), tail)
30
31
    def write_dump(self, data):
32
        """Write dump to file."""
33
        outfile = os.path.normpath("logs/{}.xml".format(self.get_timestamp_random()))
34
        if not os.path.exists(os.path.dirname(outfile)):
35
            try:
36
                os.makedirs(os.path.dirname(outfile))
37
            except OSError as err:
38
                if err.errno != errno.EEXIST:
39
                    raise
40
        with open(outfile, "w", encoding="utf-8") as fhandle:
41
            fhandle.write(data)
42
        self.last_dump_filename = outfile
43
44
    def delete_last_dump(self):
45
        """Delete last dump."""
46
        if self.last_dump_filename:
47
            os.unlink(self.last_dump_filename)
48
            self.last_dump_filename = None
49
50
    @staticmethod
51
    def write_info_if_dumps_found():
52
        """Notify user to upload dumps if present."""
53
        # To disable this info, uncomment the following line.
54
        # return
55
        files = glob.glob(os.path.normpath("logs/*.xml"))
56
        if files:
57
            print()
58
            print("{}There are {} logs collected in the logs/ directory.{} Please consider uploading".format(ansi.YELLOW, len(files), ansi.RESET))
59
            print("them to https://tclota.birth-online.de/ by running {}./upload_logs.py{}.".format(ansi.CYAN, ansi.RESET))
60