-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.py
More file actions
297 lines (238 loc) · 8.57 KB
/
config.py
File metadata and controls
297 lines (238 loc) · 8.57 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# from pathlib import Path
import logging as log
from collections import defaultdict
from datetime import datetime
from os import listdir, path, remove
from shutil import copy
from subprocess import run
from sys import exit as _exit
# GLOBALS
# CONFIG ONLY
DEBUG=False
if DEBUG:
table_name = "resources/debug.csv"
backup_table_name = "resources/.backup/debug.csv"
else:
table_name = "TaskList.csv"
backup_table_name = "resources/.backup/TaskList.csv"
code_wrap = 150
half_tab = 2
# MAKETABLE.PY
day_limit = 5
class CustomLogFormatter(log.Formatter):
# DEBUG -> 10
# INFO -> 20
# ERROR -> 40
# CRITICAL -> 50
def __init__(self, fmt=None, datefmt="%m.%d[%H:%M:%S]", style="%", validate=True, *, defaults=None):
super().__init__(fmt, datefmt, style, validate, defaults=defaults)
def format(self, record):
# CODE START
if record.levelno == log.CRITICAL:
self._style._fmt = "\n\n%(asctime)s: %(message)s"
# self._style._fmt = f'\n\n%(asctime)s: %(message)s'
# METHOD START
elif record.levelno == log.INFO:
self._style._fmt = "%(asctime)s:\t└── %(message)s"
# self._style._fmt = f'%(asctime)s:\t└── %(message)s'
# ERROR DETECTED
elif record.levelno == log.ERROR:
self._style._fmt = "%(message)s"
# self._style._fmt = f'%(message)s'
# ALL OTHER MESSAGES
else:
self._style._fmt = "%(asctime)s: %(message)s"
# self._style._fmt = f'%(asctime)s: %(message)s'
return super().format(record)
def formatException(self, exception_info):
global code_wrap
global half_tab
result = (super().formatException(exception_info)).splitlines()
result_formatted_list = [f"{half_tab * ' '}│{half_tab * ' '}{strline}" for strline in result]
result_formatted_string = (
f"{' ' * half_tab}{'─' * (code_wrap - half_tab)}\n{'\n'.join(result_formatted_list)}"
)
return result_formatted_string
def myLog(message: str, log_level=log.DEBUG):
"""
logs data to file
Args:
message (str): any string to be logged
"""
log_name = "diegoibarra.todo.log"
log_file = path.join(path_dict["resources"], "cache", log_name)
my_handler = log.FileHandler(log_file)
my_handler.setFormatter(CustomLogFormatter())
my_logger = log.getLogger("myLogger")
my_logger.setLevel(log.DEBUG)
my_logger.addHandler(my_handler)
# CODE START
if message.lower().startswith("-") and ("done" not in message.lower()):
message = message.center(35, "-")
my_logger.critical(message)
# METHOD START
elif message.lower().startswith("method"):
my_logger.info(message)
# ERROR DETECTED
elif log_level == log.ERROR:
log_message = f"ERROR: {message}"
my_logger.error(log_message, exc_info=True)
getDialog(log_file, message)
# SCRIPT END
elif "done" in message.lower():
message = message.center(35, "-")
my_logger.debug(message)
# ALL OTHER MESSAGES
else:
my_logger.debug(message)
my_logger.removeHandler(my_handler)
my_handler.close()
def clearScreen() -> None:
print("\x1b[H\x1b[J")
def copy2Clipboard(_text) -> None:
"""
Copies the given text to the clipboard using the pbcopy command.
Args:
_text (str): The text to be copied to the clipboard.
"""
run("pbcopy", text=True, input=str(_text))
def pathDict() -> dict:
"""
Using the main file as the source of the Project Directory,
returns a dict of all of the paths used throughout the project
Returns:
dict: Project = '*';
resources = '*/resources';
configPATH = '*/.config';
"""
base_directory = path.dirname(__file__)
key_list = ["Project", "resources", "images"]
path_dict = defaultdict(str)
path_dict[key_list[0]] = base_directory # Project Directory
path_dict[key_list[1]] = path.join(base_directory, "resources")
path_dict[key_list[2]] = path.join(path_dict[key_list[1]], "images")
return path_dict
def csvTable(project_directory: str) -> str:
"""
Checks to see if csv file exists. If file exists, saves a backup copy and deletes previous backup if exists.
Returns path of original csv file.
Args:
project_directory (str)
Returns:
str: path of csv file
"""
global table_name
global backup_table_name
csv_path = path.join(project_directory, table_name)
backup_path = path.join(project_directory, backup_table_name)
# CHECKS IF CSV FILE EXISTS
if path.isfile(csv_path):
# CHECKS IF CSV BACKUP FILE EXISTS
if path.isfile(backup_path):
remove(backup_path)
copy(csv_path, backup_path)
return csv_path
else:
_exit(myLog("CSV FILE DOES NOT EXIST"))
def getDialog(log_file="", message="") -> None:
def runScript(applescript: str) -> str:
std_outerr = run(["osascript", "-e", applescript], capture_output=True, text=True)
stdout = std_outerr.stdout.strip()
return stdout
applescript = """
set dialog_message to "%s\n\n\tOpen ToDo.log in VSCode?"
set buttons_list to {"Open", "Nah"}
set default_button to (item 2 of buttons_list)
set title_message to "ToDo [ ERROR ]"
set dialog_icon to POSIX file "/Users/diegoibarra/Pictures/1. Icons/0. Icons/MyApps/ToDo/AppIcon.icns"
set time_out to 4
display dialog dialog_message ¬
with title title_message ¬
buttons buttons_list ¬
default button default_button ¬
with icon dialog_icon ¬
giving up after time_out
""" % (message)
stdout = runScript(applescript)
# button returned:Nah, gave up:false
stdout_parse = stdout.split(", ")
user_response = stdout_parse[0].split(":")
if user_response[1].lower() == "open":
run(["code", path_dict["Project"], log_file])
exit()
def clearFolder(directory: str) -> None:
"""
Removes all files within a directory, preserving the directory itself.
Args:
directory (str): Full path of directory
"""
folder_files = listdir(directory)
for i in folder_files:
path_to_remove = directory + "/" + i
remove(path_to_remove)
def timeLabel(prefix="") -> str:
"""
Returns time string as *HHMMSS
accepting a prefix represented by the asterisk
Args:
prefix (str, optional): Any string to precede the time. Defaults to "".
Returns:
str: "052501"
"""
def getTime() -> list[str]:
current_hour = datetime.today().hour
current_min = datetime.today().minute
current_sec = datetime.today().second
current_list = [current_hour, current_min, current_sec]
return padNumbers(current_list)
def padNumbers(raw_time) -> list[str]:
for i in range(len(raw_time)):
time_component = str(raw_time[i])
if len(time_component) < 2:
time_component = "0" + time_component
raw_time[i] = time_component
return raw_time
return f"{prefix}{''.join(getTime())}"
# LIGHT
# def tableStyle():
# cautionColor = "004874"
# priorityColor = "941717"
# cStyle = {}
# cStyle["head_font"] = "SF Pro Rounded"
# cStyle["body_font"] = "SF Mono"
# cStyle["head_font_size"] = 1.2
# cStyle["body_font_size"] = 1.3
# cStyle["border_width"] = 4
# # BOX COLOR
# cStyle["box_color"] = "828282"
# cStyle["head_font_color"] = "D0D0D0"
# cStyle["body_font_color"] = "F0F0F0"
# cStyle["header_line_color"] = "F0F0F0"
# cStyle["rowCoE"] = "828282" # / Dark
# cStyle["rowCoO"] = "9B9B9B" # / Light
# cStyle["pastCo"] = cautionColor # / PastDue Color
# cStyle["priorityCo"] = priorityColor # / PastDue Color
# return cStyle
# DARK
def tableStyle():
cautionColor = "F86702"
priorityColor = "FB3819"
cStyle = {}
cStyle["head_font"] = "SF Pro Rounded"
cStyle["body_font"] = "SF Mono"
cStyle["head_font_size"] = 1.2
cStyle["body_font_size"] = 1.3
cStyle["border_width"] = 4
# BOX COLOR
cStyle["box_color"] = "353535"
cStyle["head_font_color"] = "8E8E8E"
cStyle["body_font_color"] = "E0E0E0"
cStyle["header_line_color"] = "E2E2E2"
cStyle["rowCoE"] = "424242" # / Dark
cStyle["rowCoO"] = "353535" # / Light
cStyle["pastCo"] = cautionColor # / PastDue Color
cStyle["priorityCo"] = priorityColor # / PastDue Color
return cStyle
# MakeAssignments & MakeTable
path_dict = pathDict()
csv_path = csvTable(path_dict["Project"])