Compare commits

11 Commits

Author SHA1 Message Date
6738f73db7 create class 2025-09-28 13:53:10 +02:00
e99ee7925f update logger 2025-09-28 13:52:40 +02:00
d910027bc0 update refit.py with Refit_Create() class 2025-09-28 13:51:53 +02:00
2dc233eef0 update README 2025-09-28 13:48:57 +02:00
09563a997c made some minor adjustments 2025-09-28 09:25:08 +02:00
a26367c0aa update README 2025-09-27 20:54:27 +02:00
8bc7bf5584 introduced src 2025-09-27 20:53:07 +02:00
b3834f4798 update .gitignore 2025-09-27 19:15:43 +02:00
f0a7ea1874 update .gitignore 2025-09-27 19:14:43 +02:00
c41ff7e0f5 fixed the usage program name from upper to lower case 2025-09-27 19:05:44 +02:00
78f8c991bd update README 2025-09-27 19:03:00 +02:00
8 changed files with 389 additions and 16 deletions

179
.gitignore vendored
View File

@@ -1,2 +1,177 @@
__pycache__
releases
release
# ---> Python
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# UV
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
#uv.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
# Ruff stuff:
.ruff_cache/
# PyPI configuration file
.pypirc

18
refit/README.md Normal file
View File

@@ -0,0 +1,18 @@
# refit
`refit` is a file, directory manipulation and creation tool.
## ToDos
1. folder and file creation
1.1 simple file creation
1.2 recursive file creation
1.3 file creation
2. file movement
2.1 apply a pattern what to move to where
3. file removal
3.1 remove all files like '*.tar'
## Changelog
<2025-09-28> V0.1.0 - Added the creation of multiple numbered files in a given directory with the pattern default directory_n

View File

@@ -0,0 +1,92 @@
import os
import pathlib
import sys
from .refit_logger import logger
logger.debug("Initiated refit_create.py")
# ----------------------------------------------------------------------
class Refit_Create:
"""A class to create folders and files.
It first calls the decider which lets the create_input_valid() function
check if the input argument exists. If create_input_valid() returns
'True' it continues to execute the command as per the given arguments.
default folder name: directory"""
def __init__(self, args):
"""Initiating variables for creation"""
self.args = args
self.name = args.name
self.input = args.input
self.n = args.n
def create_input_valid(self):
"""Checks if the input is valid and returns either True or
throws an error in log and terminal."""
logger.debug("in create_input_valid()")
if self.input is None:
logger.warning(f"{self.input} cannot be None")
print("Input argument missing. Use 'refit create -h' for help")
raise ValueError("Input missing")
return True
def create_n_folders(self, n, input, name):
"""Creates an set ammount of folders. Using the default directory
name if no other is provided."""
logger.debug("in create_n_folders()")
# Sets the default directory name.
if name is None:
logger.debug("name argument is 'None', applying default name")
name = "directory"
else:
logger.debug(f"{name}, Type: {type(name)}, Length: {len(name)}")
# Checks if multiple names are passed to the --name argument
# if so, only the first one gets used.
if len(name) > 1:
_NAMES_WARNING = f"{len(name)} names given, only one required.\nContinuing with '{name[0]}' as name."
logger.warning(_NAMES_WARNING)
print(_NAMES_WARNING)
name = name[0]
logger.debug(f"{name}, Type: {type(name)}")
# Creating the length of the suffix.
length_n = len(str(n))
logger.debug(f"Length of numbering string:{length_n}")
while n > 0:
# Creating the suffix string, filling the numbers to len of arg.n
i = str(n - 1)
number_string = str.zfill(i, length_n)
# Creating path for the folder
temp_name = f"{name}_{number_string}"
rfc_path = os.path.join(input, temp_name)
# Creating folder and subtracting n by one for the number_string
os.mkdir(rfc_path)
n -= 1
def rf_create_decider(self):
"""Coordination of the 'create' sub command"""
if self.create_input_valid():
logger.debug("valid input -> continue")
self.create_n_folders(self.n, self.input, self.name)
logger.debug(
"End of run---------------------------------------------------------"
)
def __call__(self):
"""Gets called when the object is treated as an function"""
self.rf_create_decider()

View File

@@ -0,0 +1,32 @@
import logging
import sys
from pathlib import Path
log_dir = Path.home() / ".local" / "share" / "refit"
log_dir.mkdir(parents=True, exist_ok=True)
log_file = log_dir / "refit.log"
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(levelname)s - %(message)s",
filename=log_file,
)
logger = logging.getLogger()
def handle_exception(exec_type, exec_value, exec_traceback):
if issubclass(exec_type, KeyboardInterrupt):
sys.__excepthook__(exec_type, exec_value, exec_traceback)
return
logger.error(
"External error accured",
exc_info=(exec_type, exec_value, exec_traceback),
)
sys.excepthook = handle_exception
# logger.debug(f"Log path:\t{log_dir}")
# logger.debug(f"Log file:\t{log_file}")

57
refit/src/refit.py Normal file
View File

@@ -0,0 +1,57 @@
import argparse
import sys
from modules.refit_logger import logger
from modules.refit_create import Refit_Create
# Setting Global Variables
REFIT_VERSION = "Refit Beta 0.0.0"
# ---------------------------ARGPARSE START---------------------------
# Main Parser
parser = argparse.ArgumentParser(
prog="Refit",
description="This is a file and directory manipulation tool.\
it can create, move and delete files and directories as well as \
renaming them",
epilog=REFIT_VERSION,
)
# Main Parser Arguments
# Create Parser
subparser = parser.add_subparsers(
title="Commands",
dest="create",
required=False,
)
# Create Parser Arguments
create_parser = subparser.add_parser(
"create",
help="creates a new file/folder",
)
create_parser.add_argument("-n", type=int, help="number of items")
create_parser.add_argument("-i", "--input", help="input file")
create_parser.add_argument(
"--name",
nargs="*",
help="the name of the folder you want to create\n Default: directory",
)
create_parser.set_defaults(command_class=Refit_Create)
args = parser.parse_args()
# ---------------------------ARGPARSE END-----------------------------
# Dispatcher
# determines what code gets addressed based of the users choosen flags.
if hasattr(args, "command_class"):
logger.debug("In hasattr()")
Refit_Create = args.command_class
create_command_instance = Refit_Create(args)
create_command_instance()
else:
parser.print_help()
logger.info("No input, exiting with error:1")
sys.exit(1)

View File

@@ -29,12 +29,15 @@ def execute_as_subprocess(command, base_path, verbosity=False):
"""executes the string given with the '-c, --command' flag."""
logger.debug("Entered execute_as_subprocess()")
logger.debug(f"Path:\t{base_path}\nCommand:\t{command}")
logger.debug(f"Path:\t{base_path}\nCommand:\t\t\t{command}")
# Decicion if the terminal output is verbose or not
if verbosity:
# Verbose output
logger.info("Running subprocess with terminal output.")
subprocess.run(command, cwd=base_path, shell=True)
else:
# Suppressed output
logger.info("Running with suppressed stdout and stderr")
subprocess.run(
command,
@@ -43,5 +46,4 @@ def execute_as_subprocess(command, base_path, verbosity=False):
stdout=subprocess.DEVNULL,
stderr=subprocess.STDOUT,
)
logger.debug("Exited execute_as_subprocess()")

View File

@@ -13,5 +13,5 @@ logging.basicConfig(
)
logger = logging.getLogger()
logger.debug(f"Log path:\t{log_dir}")
logger.debug(f"Log file:\t{log_file}")
# logger.debug(f"Log path:\t{log_dir}")
# logger.debug(f"Log file:\t{log_file}")

View File

@@ -5,12 +5,13 @@ from modules.tempbox_functions import execute_as_subprocess
from modules.tempbox_logger import logger
tempbox_version = "Tempbox Beta b0.2.1"
# Argument parsing
parser = argparse.ArgumentParser(
prog="Tempbox",
prog="tempbox",
description="This program accepts an\
command whicht it executes in an temporary directory in /temp.",
# epilog="helloooooooo",
epilog=tempbox_version,
)
parser.add_argument(
@@ -19,20 +20,19 @@ parser.add_argument(
action="store_true",
help="Activates or deactivates verbose output. (default=%(default)s)",
)
parser.add_argument(
"-c",
"--command",
help="Takes the string right after the flag to execute it.",
)
parser.add_argument("-V", "--version", action="version", version=tempbox_version)
args = parser.parse_args()
# Begin of script logic
if args.command is not None:
with tempfile.TemporaryDirectory() as temp_dir:
logger.debug(f"'{temp_dir}' was created")
logger.info(f"'{temp_dir}' was created")
if args.command is not None:
execute_as_subprocess(
args.command,
@@ -41,7 +41,4 @@ if args.command is not None:
)
else:
parser.print_help()
logger.info("Printed Version")
# Creates a temporary directory and executes the command in it.
logger.debug("Printed Version")