Skip to content

Commit

Permalink
- Added multiple files for future PyPI package upload.
Browse files Browse the repository at this point in the history
- Improved function inline docs.
- Added function to change file extensions in a given directory.
- Better log formatting.

Signed-off-by: schlopp96 <[email protected]>
  • Loading branch information
schlopp96 committed May 3, 2022
1 parent f755cbd commit cf8b8ad
Show file tree
Hide file tree
Showing 4 changed files with 134 additions and 90 deletions.
3 changes: 3 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
include *.txt
recursive-include PyFiTransfer *.gitkeep
recursive-include img *.png
184 changes: 95 additions & 89 deletions PyFiTransfer/main.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
#!/usr/bin/env python3
#< PyFiTransfer >#
#& Est. 1/15/22 $#

import logging
from os import PathLike, chdir
from os import scandir as lsContents
import os
from os.path import basename as base
from os.path import dirname
from os.path import exists as isDir
Expand All @@ -13,139 +12,140 @@

from PyLoadBar import load

#> Set CWD:
# > Set CWD:
chdir(dirname(__file__))

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('[%(asctime)s : %(levelname)s] - %(message)s')
def init_logger():
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

logHandler = logging.FileHandler('./logs/log.log', 'a')
formatter = logging.Formatter(
"[%(asctime)s : %(levelname)s] - %(message)s",
datefmt='%Y-%m-%d %H:%M:%S')

logHandler.setFormatter(formatter)
logHandler = logging.FileHandler("./logs/log.log", "a")

logger.addHandler(logHandler)
logHandler.setFormatter(formatter)

textborder: str = '\n========================\n'
logger.addHandler(logHandler)
return logger


logger = init_logger()

BORDER: str = '='.ljust(50, '=')


def main() -> NoReturn | None:
"""Run `PyFiTransfer`.
"""Initialize logging subsystem and start program.
---
Parameters:
:return: Program start
:rtype: NoReturn | None
:return: Program start
:rtype: NoReturn | None
"""
logger.debug('> Started PyFiTransfer... <\n')
logger.info(" PyFiTransfer Started...\n")

origin: str = getStartDir()
logger.info(f'Got origin directory:\n==> "{origin}"')
logger.info(f'Got origin directory:\n>> "{origin}"')

destination: str = getFinalDir()
logger.info(f'Got file destination:\n==> "{destination}"')
targetDir: str = getTargetDir()
logger.info(f'Got file destination:\n>> "{targetDir}"')

fileType: str = getFileType()
logger.info(f'Got file-type to be transferred:\n==> ".{fileType}"')
fileExt: str = getExt()
logger.info(f'Got file-type to be transferred:\n>> ".{fileExt}"')

originClearance: bool = verify(origin)
destinationClearance: bool = verify(destination)

if originClearance and destinationClearance:
logger.info('==> Transferring files now <==')
transfer(origin, destination, fileType)
if verifyPath(origin) and verifyPath(targetDir):
logger.info("Starting file transfer...")
transfer(origin, targetDir, fileExt)
return Ex_0()
return Ex_1(fileType)
return Ex_1(fileExt)


def getStartDir() -> str:
"""Prompt user for file-path of directory containing files to move.
"""Prompt user for filepath of directory containing files to move.
---
Parameters:
:return: directory path of files to move
:rtype: str | PathLike
:return: filepath containing files to be transferred
:rtype: str | PathLike
"""
return input(
'\nPlease enter the file-path of the starting directory\'s location containing the files you wish to transfer:\n> '
"\nPlease enter the filepath of the starting directory's location containing the files you wish to transfer:\n> "
)


def getFinalDir() -> str:
"""Prompt user for file-path of directory to move files to.
def getTargetDir() -> str:
"""Prompt user for filepath of directory to move files to.
---
Parameters:
:return: directory path of file destination.
:rtype: str | PathLike
:return: target destination of file transfer.
:rtype: str | PathLike
"""
return input(
'\nPlease enter the file-path of the directory intended to be the destination of transferred files:\n> '
)
"\nPlease enter the destination filepath for transferred files:\n> ")


def getFileType() -> str:
"""Prompt user for type of file needing to be moved.
def getExt() -> str:
"""Prompt user for extension of files to be transferred.
---
Parameters:
:return: file-type/extension.
:rtype: str
:return: file-type/extension of files to be transferred.
:rtype: str
"""
return input(
'\nPlease enter the file-type/file-extension of the files intended to be tansferred between directory locations.\nOnly include letters of extension.\n- INCORRECT Ex: ".mp4"\n- Correct Ex (without quotes): "mp4"\n> '
'\nPlease enter the file-type/extension of the files intended to be tansferred between directory locations.\nOnly include letters of extension:\n>> Correct Ex (without quotes): "mp4"\n> '
)


def verify(filepath: PathLike | str) -> bool:
"""Verify existence of a given directory.
def verifyPath(filepath: PathLike | str) -> bool:
"""Verify existence of a given directory path.
---
Parameters:
:param filepath: path to directory.
:type filepath: PathLike | str
:return: verification of existence of the given directory, or lack thereof.
:rtype: bool
:param filepath: path to directory.
:type filepath: PathLike | str
:return: verification existence of given directory, or lack thereof.
:rtype: bool
"""
try:
logger.info(
f'Verifying directory of given file location:\n==> "{filepath}"...'
)
f'Verifying directory of given file location:\n>> "{filepath}"...')
if isDir(filepath):
load(
f'\nVerifying destination for file location:\n==> "{filepath}"',
'\nDirectory verified successfully!',
enable_display=False)
logger.info('Directory verified successfully.')
f'\nVerifying file transfer destination:\n>> "{filepath}"',
"\nDirectory verified successfully!",
enable_display=False,
)
logger.info(f"Filepath \"{filepath}\" verified successfully!")
return True
else:
logger.error(
f'Directory: "{filepath}"\n==> Unable to be found, thus could NOT be verified.'
)
load(
f'\nVerifying destination for file location:\n==> "{filepath}"',
f'> ERROR\n> Directory: "{filepath}"\n==> Unable to be found, thus could NOT be verified.',
enable_display=False)
f'\nVerifying file transfer destination:\n>> "{filepath}"',
f'>> ERROR:\n>> Directory: "{filepath}" could NOT be verified.',
enable_display=False,
)
logger.warning(
f'Directory: "{filepath}" could NOT be verified...s')
return False
except (OSError, ValueError, TypeError, EOFError) as error:
logger.exception(
f'Something went wrong during directory verification...\n> {error}'
f"Something went wrong during directory verification...\n>> {error}"
)
print(
f'> ERROR!\nSomething went wrong during directory verification...\n> {error}'
f">> ERROR:\nSomething went wrong during directory verification...\n>> {error.__traceback__}"
)
return False


def transfer(startingDir: str, finalDir: str, fileType: str) -> None:
"""Transfer files of certain extensions from original directory to given destination.
---
:param startingDir: starting location of transfer
:type startingDir: str
:param finalDir: file transfer destination
Expand All @@ -156,35 +156,35 @@ def transfer(startingDir: str, finalDir: str, fileType: str) -> None:
:rtype: Any
"""
files: list = []
print('\n> Transferring files now...\n')
print("\n> Transferring files now...\n")
with lsContents(startingDir) as dirFiles:
for file in dirFiles:
if not file.name.startswith('.') and file.name.endswith(
f'.{fileType}') == True and file.is_file():
logger.info(f'==> Transferring file {file.name}...')
if (not file.name.startswith(".")
and file.name.endswith(f".{fileType}") == True
and file.is_file()):
logger.info(f">> Transferring file: \"{file.name}\"...")
files.append(file.name)
copyfile(file, f'{finalDir}\{base(file)}')
copyfile(file, f"{finalDir}\{base(file)}")
load(
f'> Transferring all files with extension ".{fileType}" to:\n>> "{finalDir}"',
f"> {len(files)} files successfully copied to new location:\n>> {files}",
time=len(files) if files else 5,
)
logger.info(
f'{len(files)} files successfully copied to new location:\n==> {files}'
f"{len(files)} files successfully copied to new location:\n>> \"{finalDir}\""
)
load(
f'> Transferring all ".{fileType}" files to: "{finalDir}"',
f'> {len(files)} files successfully copied to new location:\n{files}',
time=len(files) if files else 5)


def Ex_0() -> NoReturn | None:
"""Exit program with success message.
---
Parameters:
:return: Exits program.
:rtype: NoReturn
:return: Exits program.
:rtype: NoReturn
"""
logger.debug(
f'==> Operation Successful! <==\n==> Exiting Program...{textborder}')
print('\n\nOperation Successfull!\n\nExiting Program...')
logger.info(f"Operation Successful!\n\n>> Exiting Program...{BORDER}")
print("\n\nOperation Successfull!\n\nExiting Program...")
return exit()


Expand All @@ -193,20 +193,26 @@ def Ex_1(fileType: str) -> NoReturn | None:
---
Parameters:
:param fileType: extension of files not found
:type fileType: str
:return: Closes application
:rtype: NoReturn | None
:param fileType: extension of files not found
:type fileType: str
:return: Closes application
:rtype: NoReturn | None
"""
logger.warning(
f'==> Operation Failure! <==\n==> No Files were found with given extension: ".{fileType}".\n==>Exiting Program...{textborder}'
f'No Files were found with given extension: ".{fileType}".\n>> Exiting Program...{BORDER}'
)
print(
f'\n\n> Operation Failure!\n\n> No Files were found with given extension: ".{fileType}".\n\nExiting Program...'
f'\n\nOperation Failure!\n\n>> No Files were found with given extension: ".{fileType}".\n\n>> Exiting Program...'
)
return exit()


def change_ext(path, curext, newext):
for filename in os.listdir(os.path.dirname(os.path.abspath(path))):
base_file, ext = os.path.splitext(filename)
if ext == curext:
os.rename(filename, base_file + newext)


if __name__ == "__main__":
main()
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
PyLoadBar==0.0.6
PyLoadBar==0.0.7.1
setuptools==58.1.0
34 changes: 34 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import pathlib
from setuptools import setup, find_packages

readme = pathlib.Path("readme.md").read_text()
reqs = pathlib.Path("requirements.txt").read_text()
setup(
name="PyFiTransfer",
version="0.4.0",
description=
'Program built to easily transfer files of a specified extension-type from a starting directory to desired destination.',
url='https://github.com/schlopp96/PyFiTransfer',
author='schlopp96',
author_email='[email protected]',
long_description=readme,
long_description_content_type='text/markdown',
packages=find_packages(),
include_package_data=True,
install_requires=[reqs],
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
"Natural Language :: English",
"Operating System :: Microsoft :: Windows",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Utilities",
],
keywords=[
'file', 'transfer', 'script', 'files', 'directory', 'directories'
])

0 comments on commit cf8b8ad

Please sign in to comment.