Passed
Push — master ( 2adcb6...75d235 )
by Markus
01:50
created

tcllib.dumpmgr.DumpMgr.delete_last_dump()   A

Complexity

Conditions 2

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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