Skip to content

Commit ccb5a24

Browse files
committed
0.4.1 Hotfix Update
--- - Fixed bug causing incorrect cwd to be set. - Enhanced app logging. - Changed `PyLoadBar` dependency version to 0.1.0 - Changed all `PyLoadBar` use cases to conform to new version params. - Additions to docstrings. - Added comments to source code. Signed-off-by: schlopp96 <71921821+schlopp96@users.noreply.github.com>
1 parent 69cdfe6 commit ccb5a24

File tree

7 files changed

+86
-60
lines changed

7 files changed

+86
-60
lines changed

PyFiTransfer/appevents/GUI_loop.py

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,63 @@
11
from random import uniform
22
from time import sleep
3+
34
from PyFiTransfer.appevents.events import events, exit_program, logger
45
from PyFiTransfer.appgui.gui import sg, window
56

67

78
def GUI_loop() -> None:
8-
"""GUI program event loop.
9+
"""Main GUI loop.
10+
11+
- Starts processing of window events.
912
1013
---
1114
12-
:return: run GUI program.
15+
:return: program window
1316
:rtype: None
1417
"""
1518

1619
while True:
17-
event, vals = window.read()
20+
event, vals = window.read() # Get events from GUI window
1821

19-
logger.info(f'{event} : {vals}')
22+
logger.info(f'{event} : {vals}') # Log events
2023

21-
if event in [sg.WIN_CLOSED, 'Exit']:
24+
if event in [sg.WIN_CLOSED, 'Exit']: # Exit events
2225
break
2326

24-
if event == '-Transfer-':
27+
if event == '-Transfer-': # Process Transfer button event
28+
29+
# No source directory entered
2530
if len(vals['-SourceFolderInput-']) < 1:
2631
sg.Popup('Make sure all fields are filled out!')
2732
continue
33+
34+
# No target directory entered
2835
if len(vals['-TargetFolderInput-']) < 1:
2936
sg.Popup('Make sure all fields are filled out!')
3037
continue
38+
39+
# No file extension entered
3140
if len(vals['-FileExtensionInput-']) < 1:
3241
sg.Popup('Make sure all fields are filled out!')
3342
continue
43+
44+
# Start Transfer
3445
transfer: int = events.transfer(vals['-SourceFolderInput-'],
3546
vals['-TargetFolderInput-'],
3647
vals['-FileExtensionInput-'],
3748
gui=True)
38-
if transfer > 0:
39-
for _ in range(50):
49+
50+
if transfer > 0: # Enable progress bar
51+
for _ in range(25):
4052
window.refresh()
41-
sleep(uniform(0.01, 0.25))
53+
sleep(uniform(0.01, 0.2))
4254
window['-ProgressBar-'].update(_ + 1)
43-
print(f'Successfully transferred {transfer} files!\n')
44-
window['-ProgressBar-'].update(0)
4555

46-
window.close()
56+
print(f'Successfully transferred {transfer} files!\n'
57+
) # Log success
58+
59+
window['-ProgressBar-'].update(0) # Reset progress bar
60+
61+
window.close() # Close window and return system resources
4762

48-
return exit_program.success()
63+
return exit_program.success() # Return successful exit status

PyFiTransfer/appevents/events.py

Lines changed: 31 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
2-
from os import PathLike
2+
from os.path import dirname
3+
from os import PathLike, chdir
34
from os import scandir as lsContents
45
from os.path import basename as base
56
from shutil import move
@@ -9,11 +10,14 @@
910
from PyFiTransfer.applogger.logger import _LogGenerator
1011
from PyLoadBar import PyLoadBar
1112

12-
logger = _LogGenerator(name='transferlog', filename='transferlog')
13+
chdir(dirname(dirname(__file__)))
1314

14-
loader = PyLoadBar()
15+
txt_seq = PyLoadBar(bar_sequence=False)
16+
bar_seq = PyLoadBar()
1517

16-
BORDER: str = '\n='.ljust(50, '=')
18+
logger = _LogGenerator('transferlog', 'Program')
19+
20+
BORDER: str = '\n<='.ljust(50, '=') + '=>'
1721

1822

1923
class FileTransfer:
@@ -33,7 +37,7 @@ class FileTransfer:
3337
- :func:`__verify_dir(self, filepath: PathLike | str) -> bool`
3438
- Verify if given filepath is a directory.
3539
36-
- :func:`transfer(self, src_dir: str | os.PathLike, target_dir: str | os.PathLike, file_ext: str | os.PathLike) -> bool`
40+
- :func:`transfer(self, src_dir: str | PathLike, target_dir: str | PathLike, file_ext: str | PathLike) -> bool | int`
3741
- Transfer files from source directory to target directory.
3842
"""
3943

@@ -78,54 +82,50 @@ def _verify_dir(self, filepath: PathLike | str) -> bool:
7882
7983
:param filepath: path to directory.
8084
:type filepath: :class:`PathLike` | :class:`str`
81-
:return: :bool:`True` if directory exists, :bool:`False` if not.
85+
:return: `True` if directory exists, `False` if not.
8286
:rtype: :class:`bool`
8387
"""
8488
try:
8589
logger.info(
8690
f'Verifying directory of given file location:\n>> "{filepath}"...'
8791
)
8892
if isdir(filepath):
89-
loader.load(
90-
f'\nVerifying file transfer destination:\n>> "{filepath}"',
91-
"\nDirectory verified successfully!",
92-
enable_display=False,
93-
)
93+
txt_seq.start(
94+
f'Verifying file transfer destination: "{filepath}"',
95+
"Directory verified successfully!",
96+
iter_total=5,
97+
txt_seq_speed=0.25)
9498
logger.info(
9599
f"Filepath \"{filepath}\" verified successfully!\n")
96100
return True
97101
else:
98-
loader.load(
99-
f'\nVerifying file transfer destination:\n>> "{filepath}"',
102+
txt_seq.start(
103+
f'Verifying file transfer destination: "{filepath}"',
100104
f'>> ERROR:\n>> Directory: "{filepath}" could NOT be verified.',
101-
enable_display=False,
102-
)
105+
iter_total=5,
106+
txt_seq_speed=0.25)
103107
logger.warning(
104108
f'Directory: "{filepath}" could NOT be verified...\n')
105109
return False
106110
except (OSError, ValueError, TypeError, EOFError) as error:
107111
logger.exception(
108112
f"Something went wrong during directory verification...\n>> {error}"
109113
)
110-
logger.info(
111-
f">> ERROR:\nSomething went wrong during directory verification...\n>> {error.__traceback__}"
112-
)
113114
return False
114115

115-
def transfer(self, src_dir: str | os.PathLike,
116-
target_dir: str | os.PathLike, file_ext: str | os.PathLike,
117-
gui: bool) -> bool | int:
116+
def transfer(self, src_dir: str | PathLike, target_dir: str | PathLike,
117+
file_ext: str | PathLike, gui: bool) -> bool | int:
118118
"""Transfer files of a given extension from source directory to target destination.
119119
120120
---
121121
122122
:param src_dir: starting location of transfer
123-
:type src_dir: :class:`str` | :class:`os.PathLike`
123+
:type src_dir: :class:`str` | :class:`PathLike`
124124
:param target_dir: file transfer destination
125-
:type target_dir: :class:`str` | :class:`os.PathLike`
125+
:type target_dir: :class:`str` | :class:`PathLike`
126126
:param file_ext: extension of files to be transferred
127-
:type file_ext: :class:`str` | :class:`os.PathLike`
128-
:return: :bool:`True` if transfer was successful, :bool:`False` if not.
127+
:type file_ext: :class:`str` | :class:`PathLike`
128+
:return: if :param:`gui` is `True`, return number of files transferred, else return `True` or `False` depending if transfer was successful or not.
129129
:rtype: :class:`bool` | :class:`int`
130130
"""
131131

@@ -161,12 +161,14 @@ def transfer(self, src_dir: str | os.PathLike,
161161
)
162162
return len(files)
163163

164-
loader.load(
164+
bar_seq.start(
165165
msg_loading=
166166
f'> Transferring all files with extension ".{file_ext}" to:\n>> "{target_dir}"',
167167
msg_complete=
168168
f'> {len(files)} files successfully copied to new location:\n>> {files}',
169-
time=len(files))
169+
min_iter=0.01,
170+
max_iter=0.2,
171+
iter_total=len(files))
170172

171173
logger.info(
172174
f'{len(files)} files successfully copied to new location:\n>> "{target_dir}"\n'
@@ -181,11 +183,11 @@ def transfer(self, src_dir: str | os.PathLike,
181183
return False
182184

183185

184-
def change_ext(path: str | os.PathLike, curext: str, newext: str) -> None:
186+
def change_ext(path: str | PathLike, curext: str, newext: str) -> None:
185187
"""Change extension of all files of a given type.
186188
187189
:param path: path to containing directory of files to be changed
188-
:type path: :class:`str` | :class:`os.PathLike`
190+
:type path: :class:`str` | :class:`PathLike`
189191
:param curext: extension of files to be changed
190192
:type curext: :class:`str`
191193
:param newext: extension to change files to.

PyFiTransfer/appgui/gui.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
button_color=('white', 'green'))
3737
],
3838
[
39-
sg.ProgressBar(max_value=50,
39+
sg.ProgressBar(max_value=25,
4040
size=(30, 10),
4141
orientation='horizontal',
4242
key='-ProgressBar-',

PyFiTransfer/applogger/logger.py

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import logging
2+
from os import PathLike
23

34

45
class _LogGenerator():
@@ -17,11 +18,12 @@ class _LogGenerator():
1718
NOTSET = 0
1819

1920
def __init__(self,
20-
name: str = __name__,
21-
filename: str = __name__,
21+
log_file: str | PathLike,
22+
logger_name: str = __name__,
2223
msgfmt: str = '[%(asctime)s - %(levelname)s] : %(message)s',
2324
datefmt: str = "%Y-%m-%d %H:%M:%S",
24-
level: int = DEBUG):
25+
level: int = DEBUG,
26+
stream: bool = False) -> None:
2527
"""Initialize logger instance.
2628
2729
- For the :param:`level` parameter, the level of logging can be any of the following:
@@ -40,28 +42,38 @@ def __init__(self,
4042
4143
---
4244
43-
:param name: assign specific name to logger, defaults to `__name__`.
44-
:type name: :class:`str`, optional
45+
:param log_file: File to which logger output is written
46+
:type log_file: :class:`str`
47+
:param logname: assign specific name to logger, defaults to `__name__`
48+
:type logname: :class:`str`, optional
4549
:param msgfmt: initialize log entry formatter either with a specified custom formatting, or the default formatting as described above, defaults to `'[%(asctime)s - %(levelname)s] : %(message)s'`
4650
:type msgfmt: :class:`str`, optional
4751
:param datefmt: set date formatting, defaults to `'%Y-%m-%d %H:%M:%S'`
4852
:type datefmt: :class:`str`, optional
49-
:param level: Set the logging level of this logger. Level must be an int or a str, defaults to `DEBUG` (10).
53+
:param level: Set the logging level of this logger. Level must be an int or a str, defaults to `DEBUG` (10)
5054
:type level: :class:`int`, optional
55+
:param stream: If `True`, log to stdout, defaults to `False`
56+
:type stream: :class:`bool`, optional
57+
:return: program logging instance
58+
:rtype: None
5159
"""
5260

53-
self.name: str = name
54-
self.filename: str = filename
55-
log_file: str = f'./logs/{self.filename}.log'
61+
self.logname: str = logger_name
62+
self.log_file: str | PathLike = log_file
5663
self.msgfmt: str = msgfmt
5764
self.datefmt: str = datefmt
5865
self.level: int = level
59-
self.logger: logging.Logger = logging.getLogger(self.name)
66+
self.logger: logging.Logger = logging.getLogger(self.logname)
6067
self.formatter: logging.Formatter = logging.Formatter(msgfmt, datefmt)
61-
self.fhandler: logging.FileHandler = logging.FileHandler(log_file)
68+
self.fhandler: logging.FileHandler = logging.FileHandler(
69+
f'./logs/{log_file}.log')
6270
self.logger.addHandler(self.fhandler)
6371
self.fhandler.setFormatter(self.formatter)
6472
self.logger.setLevel(level)
73+
self.stream = stream
74+
75+
if self.stream: # If stream is True, log to stderr
76+
self.logger.addHandler(logging.StreamHandler())
6577

6678
def debug(self, msg: str) -> None:
6779
"""Log :param:`msg` with severity `DEBUG`.
@@ -122,7 +134,7 @@ def exception(self, msg: str, exc_info=True) -> None:
122134
123135
:param msg: message to be logged
124136
:type msg: :class:`str`
125-
:param exc_info: include exception info, defaults to :bool:`True`
137+
:param exc_info: include exception info, defaults to `True`
126138
:type exc_info: :class:`bool`, optional
127139
:return: create log entry with given context and include exception info.
128140
:rtype: None

PyFiTransfer/main.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
11
#!/usr/bin/env python3
22

33
import sys
4-
from os import chdir
54
from os.path import dirname
65

76
sys.path.insert(0, dirname(
87
dirname(__file__))) # Ensure main module can be found by Python.
98

10-
# > Set CWD:
11-
chdir(dirname(__file__))
129

1310
from PyFiTransfer.appevents.events import logger
1411
from PyFiTransfer.appevents.GUI_loop import GUI_loop

requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
PyLoadBar>=0.0.8
1+
PyLoadBar>=0.1.0
22
PySimpleGUI>=4.60.1
33
setuptools>=58.1.0

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
reqs = pathlib.Path("requirements.txt").read_text()
66
setup(
77
name="PyFiTransfer",
8-
version="0.4.0",
8+
version="0.4.1",
99
description=
1010
'Transfer files with specified extension-type from a starting directory to desired target directory.',
1111
url='https://github.com/schlopp96/PyFiTransfer',

0 commit comments

Comments
 (0)