Completed
Push — master ( 33b60d...d9d086 )
by John
03:20
created

sql_excepthandler()   A

Complexity

Conditions 3

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
c 1
b 0
f 0
dl 0
loc 21
ccs 6
cts 6
cp 1
crap 3
rs 9.3142

1 Method

Rating   Name   Duplication   Size   Complexity  
A exceptdecorator() 0 13 2
1
#!/usr/bin/env python3
2 5
"""This module is used for decorators."""
3
4 5
import time  # spinner delay, timer decorator
5 5
import math  # rounding
6 5
import os  # path check
7 5
import sys  # frozen
8 5
import sqlite3  # the sql library
9 5
from bbarchivist import dummy  # useless stdout
10 5
from bbarchivist import exceptions  # exceptions
11
12 5
__author__ = "Thurask"
13 5
__license__ = "WTFPL v2"
14 5
__copyright__ = "2015-2017 Thurask"
15
16
17 5
def wrap_keyboard_except(method):
18
    """
19
    Decorator to absorb KeyboardInterrupt.
20
21
    :param method: Method to use.
22
    :type method: function
23
    """
24
    def wrapper(*args, **kwargs):
25
        """
26
        Try function, absorb KeyboardInterrupt and leave gracefully.
27
        """
28
        try:
29
            method(*args, **kwargs)
30
        except KeyboardInterrupt:
31
            dummy.UselessStdout.write("ASDASDASD")
32
    return wrapper
33
34
35 5
def timer(method):
36
    """
37
    Decorator to time a function.
38
39
    :param method: Method to time.
40
    :type method: function
41
    """
42 5
    def wrapper(*args, **kwargs):
43
        """
44
        Start clock, do function with args, print rounded elapsed time.
45
        """
46 5
        starttime = time.clock()
47 5
        method(*args, **kwargs)
48 5
        endtime = time.clock() - starttime
49 5
        endtime_proper = math.ceil(endtime * 100) / 100  # rounding
50 5
        mins, secs = divmod(endtime_proper, 60)
51 5
        hrs, mins = divmod(mins, 60)
52 5
        print("COMPLETED IN {0:02d}:{1:02d}:{2:02d}".format(int(hrs), int(mins), int(secs)))
53 5
    return wrapper
54
55
56 5
def sql_excepthandler(integrity):
57
    """
58
    Decorator to handle sqlite3.Error.
59
60
    :param integrity: Whether to allow sqlite3.IntegrityError.
61
    :type integrity: bool
62
    """
63 5
    def exceptdecorator(method):
64
        """
65
        Call function in sqlite3.Error try/except block.
66
67
        :param method: Method to use.
68
        :type method: function
69
        """
70 5
        def wrapper(*args, **kwargs):
71
            """
72
            Try function, handle sqlite3.Error, optionally pass sqlite3.IntegrityError.
73
            """
74 5
            return sql_exceptwrapper(method, integrity, *args, **kwargs)
75 5
        return wrapper
76 5
    return exceptdecorator
77
78
79 5
def sql_exceptwrapper(method, integrity, *args, **kwargs):
80
    """
81
    Try function, handle sqlite3.Error, optionally pass sqlite3.IntegrityError.
82
83
    :param method: Method to use.
84
    :type method: function
85
86
    :param integrity: Whether to allow sqlite3.IntegrityError.
87
    :type integrity: bool
88
    """
89 5
    try:
90 5
        result = method(*args, **kwargs)
91 5
        return result
92 5
    except sqlite3.IntegrityError if bool(integrity) else exceptions.DummyException:
93 5
        dummy.UselessStdout.write("ASDASDASD")  # DummyException never going to happen
94 5
    except sqlite3.Error as sqerror:
95 5
        print(sqerror)
96
97
98 5
def sql_existhandler(sqlpath):
99
    """
100
    Decorator to check if SQL database exists.
101
102
    :param sqlpath: Path to SQL database.
103
    :type sqlpath: str
104
    """
105 5
    def existdecorator(method):
106
        """
107
        Call function if SQL database exists.
108
109
        :param method: Method to use.
110
        :type method: function
111
        """
112 5
        def wrapper(*args, **kwargs):
113
            """
114
            Check existence of database, leave if it doesn't.
115
            """
116 5
            if os.path.exists(sqlpath):
117 5
                result = method(*args, **kwargs)
118 5
                return result
119
            else:
120 5
                print("NO SQL DATABASE FOUND!")
121 5
                raise SystemExit
122 5
        return wrapper
123 5
    return existdecorator
124
125
126 5
def enter_to_exit(checkfreeze=True):
127
    """
128
    Press enter to exit a script.
129
130
    :param checkfreeze: If this triggers only in frozen executables. Default is true.
131
    :type checkfreeze: bool
132
    """
133 5
    greenlight = bool(getattr(sys, 'frozen', False)) if checkfreeze else True
134 5
    if greenlight:
135
        smeg = input("Press Enter to exit")
136
        if smeg or not smeg:
137
            raise SystemExit
138