Compare commits
75 Commits
a26367c0aa
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 5d4788475e | |||
| de6f0ac17e | |||
| f148beedf5 | |||
| 82e6856439 | |||
| 6cbb352efb | |||
| ecd460d3ad | |||
| 1c47c68c11 | |||
| d5dcd35696 | |||
| 9e954d0790 | |||
| 171370ecac | |||
| fb78fe459f | |||
| 16aba4c60f | |||
| 2ad1d32fcc | |||
| 2b324fe2ef | |||
| 99d90d607d | |||
| 8c81064743 | |||
| 9c39b773da | |||
| 46ea1db65d | |||
| f7ab347316 | |||
| 2b1167b3ce | |||
| fe3f32c2af | |||
| e9b491e81d | |||
| e243f5f379 | |||
| c1e76b660a | |||
| 1c557913f9 | |||
| 67e68da880 | |||
| 8df12ec6f4 | |||
| 9d2d6931e3 | |||
| acd3f5fe39 | |||
| 0e84c959ce | |||
| aa5041a46c | |||
| fb4e8a3be6 | |||
| 36333b3b99 | |||
| 91e474c3b8 | |||
| e8ef3c6e53 | |||
| f4f5f9bc6b | |||
| 3c1d881de7 | |||
| b4e5694b7b | |||
| 691b68cb4c | |||
| 461533b717 | |||
| caff94ab41 | |||
| efcec653cb | |||
| a0f2f83a8a | |||
| af80345ff6 | |||
| f96d9b3257 | |||
| b0e3594b49 | |||
| cf828c7f97 | |||
| 49e16a522c | |||
| 927d5358f5 | |||
| 0bbfb9b9bf | |||
| a012f8f1e2 | |||
| 394b940841 | |||
| b615f52313 | |||
| 799e0239a1 | |||
| 5270fab084 | |||
| 5469a01c09 | |||
| 9b86007e34 | |||
| 40bf210067 | |||
| ae19816da1 | |||
| d2041c5355 | |||
| c8bf85cb6a | |||
| 9dcaacf64a | |||
| b82a04e3bb | |||
| 29924ffb36 | |||
| b09ea6a8c5 | |||
| 209fae5575 | |||
| 37fe1f5203 | |||
| c48e16fdb9 | |||
| 67b61a3d5f | |||
| 2425e0a215 | |||
| 6738f73db7 | |||
| e99ee7925f | |||
| d910027bc0 | |||
| 2dc233eef0 | |||
| 09563a997c |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1,4 +1,6 @@
|
||||
release
|
||||
releases
|
||||
version.py
|
||||
tester
|
||||
|
||||
# ---> Python
|
||||
# Byte-compiled / optimized / DLL files
|
||||
|
||||
20
README.md
20
README.md
@@ -1,13 +1,25 @@
|
||||
# Python Programs and Scripts Repository
|
||||
|
||||

|
||||
Collection of my python scripts and programs. Containing tools to manipulate the behavior of the system.
|
||||
Collection of my python scripts and programs. Containing tools to
|
||||
manipulate the behavior of the system.
|
||||
|
||||
## Wanna Do´s
|
||||
|
||||
- Program which creates an file containing a version and
|
||||
- Creating a Module which loads configuration files
|
||||
- GUI auto-clicker which accepts command line activation
|
||||
|
||||
## tempbox
|
||||
|
||||
A script which allows the user to execute commands in a temporary
|
||||
directory.
|
||||
directory.
|
||||
|
||||
### Wannado´s
|
||||
After execution, all contents within the folder get removed.
|
||||
|
||||
## refit
|
||||
|
||||
A file and folder manipulation tool. The aim is to unify various steps
|
||||
from moving to creating and deleting directories and folder with one
|
||||
tool.
|
||||
|
||||
- switch between temp file and temp dir
|
||||
|
||||
211
pyvers/src/pyvers.py
Normal file
211
pyvers/src/pyvers.py
Normal file
@@ -0,0 +1,211 @@
|
||||
import json
|
||||
import os
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
# ======================================================================
|
||||
# Constantes
|
||||
FILE_NAME = "version.json"
|
||||
# ======================================================================
|
||||
|
||||
# ======================================================================
|
||||
# Parser
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="pyvers",
|
||||
description="xD",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"config",
|
||||
help="The location of the config file to edit.",
|
||||
type=str,
|
||||
)
|
||||
parser.add_argument(
|
||||
"--patch",
|
||||
help="Bumps the patch version by one.",
|
||||
action="store_true",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--minor",
|
||||
help="Bumps the minor version by one.",
|
||||
action="store_true",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--major",
|
||||
help="Bumps the major version by one.",
|
||||
action="store_true",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
# ======================================================================
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# Functions
|
||||
def create_version_file(file_path) -> None:
|
||||
"""Creates a version.json file with all versions set to 0 at the
|
||||
input location.
|
||||
|
||||
Args:
|
||||
file_path: (str): Path with file name.
|
||||
|
||||
Example:
|
||||
>>>create_version_file(/path/to/file)
|
||||
file:
|
||||
{
|
||||
"minor": 0,
|
||||
"major": 0,
|
||||
"patch": 0
|
||||
}"""
|
||||
|
||||
# Defining the dictionary with the initial version numbers.
|
||||
initial_version = {"minor": 0, "major": 0, "patch": 0}
|
||||
|
||||
# Opening/creating the file to write the dictionary as json to it.
|
||||
file = open(file_path, "x")
|
||||
file.write(json.dumps(initial_version, indent=4))
|
||||
print("File written successfully.")
|
||||
return
|
||||
|
||||
|
||||
def load_version(input_path) -> dict[str, int]:
|
||||
"""Opens the given file and returns its contents."""
|
||||
# Open given path and loading the files contents into a variable
|
||||
file_path = open(input_path)
|
||||
prog_version = json.load(file_path)
|
||||
return prog_version
|
||||
|
||||
|
||||
def pretty_version(input_path) -> None:
|
||||
"""Prints the version in a prettifyed format."""
|
||||
prog_version = load_version(input_path)
|
||||
pretty_version = (
|
||||
f"{prog_version['major']}.{prog_version['minor']}.{prog_version['patch']}"
|
||||
)
|
||||
print(pretty_version)
|
||||
|
||||
|
||||
def bump_patch(version_file) -> None:
|
||||
"""Bumps the patch number of the given file by one."""
|
||||
# Get the version as dictionary
|
||||
version = load_version(version_file)
|
||||
|
||||
# Adding one to the version from the file and updating
|
||||
# the dictionary
|
||||
new_version = version["patch"] + 1
|
||||
version.update({"patch": new_version})
|
||||
|
||||
# Opening the file and overwriting its contents.
|
||||
with open(version_file, "w") as f:
|
||||
f.write(json.dumps(version, indent=4))
|
||||
|
||||
|
||||
def bump_minor(version_file) -> None:
|
||||
"""Bumps the minor version number of the given file by one."""
|
||||
# Get the version as dictionary
|
||||
version = load_version(version_file)
|
||||
|
||||
# Adding one to the version from the file and updating
|
||||
# the dictionary
|
||||
new_version = version["minor"] + 1
|
||||
version.update({"minor": new_version})
|
||||
|
||||
# Opening the file and overwriting its contents.
|
||||
with open(version_file, "w") as f:
|
||||
f.write(json.dumps(version, indent=4))
|
||||
|
||||
|
||||
def bump_major(version_file) -> None:
|
||||
"""Bumps the major version number of the given file by one."""
|
||||
# Get the version as dictionary
|
||||
version = load_version(version_file)
|
||||
|
||||
# Adding one to the version from the file and updating
|
||||
# the dictionary
|
||||
new_version = version["major"] + 1
|
||||
version.update({"major": new_version})
|
||||
|
||||
# Opening the file and overwriting its contents.
|
||||
with open(version_file, "w") as f:
|
||||
f.write(json.dumps(version, indent=4))
|
||||
|
||||
|
||||
def version_bumper(version_file, major_version, minor_version, patch) -> None:
|
||||
"""Decides what version to bump, based on the users passed flags"""
|
||||
if patch:
|
||||
bump_patch(version_file)
|
||||
if minor_version:
|
||||
bump_minor(version_file)
|
||||
if major_version:
|
||||
bump_major(version_file)
|
||||
|
||||
|
||||
def check_for_file(input_path: str) -> bool:
|
||||
"""Checks if the file 'version.json' exists at the given path.
|
||||
|
||||
Args:
|
||||
input_path ( str ): Path to check for the file.
|
||||
|
||||
Example:
|
||||
>>>check_for_file(".")
|
||||
'False'
|
||||
>>>check_for_file("version.json")
|
||||
'True'
|
||||
>>>check_for_file("./version.json")
|
||||
'True'
|
||||
"""
|
||||
if FILE_NAME in input_path:
|
||||
file_path = os.path.expanduser(input_path)
|
||||
if os.path.exists(file_path):
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
elif os.path.exists(os.path.join(input_path, FILE_NAME)):
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
def request_to_create():
|
||||
"""Prompts the user if he wants to create the file and exits if the
|
||||
user declines or presses any other character instead of 'y/Y'"""
|
||||
|
||||
PROMPT = "The file does not exist, do you want to create it? [y/n]"
|
||||
PROMPT += "\n>>>"
|
||||
|
||||
response = input(PROMPT)
|
||||
if "y" in response or "Y" in response:
|
||||
file_path = os.path.join(
|
||||
os.path.expanduser(args.config),
|
||||
FILE_NAME,
|
||||
)
|
||||
create_version_file(file_path)
|
||||
return
|
||||
else:
|
||||
parser.print_help()
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# Dispatching
|
||||
if check_for_file(args.config):
|
||||
file_path = os.path.join(os.path.expanduser(args.config), FILE_NAME)
|
||||
if args.patch or args.minor or args.major:
|
||||
version_bumper(
|
||||
version_file=file_path,
|
||||
major_version=args.major,
|
||||
minor_version=args.minor,
|
||||
patch=args.patch,
|
||||
)
|
||||
else:
|
||||
pretty_version(file_path)
|
||||
|
||||
if check_for_file(args.config) is False:
|
||||
request_to_create()
|
||||
file_path = os.path.join(os.path.expanduser(args.config), FILE_NAME)
|
||||
version_bumper(
|
||||
version_file=file_path,
|
||||
major_version=args.major,
|
||||
minor_version=args.minor,
|
||||
patch=args.patch,
|
||||
)
|
||||
@@ -1,14 +1,46 @@
|
||||
# refit
|
||||
|
||||
`refit` is a file, directory manipulation and creation tool.
|
||||
`refit` is a file and directory manipulation tool. Currently it can
|
||||
create a flat folder and file structure
|
||||
as well as an linear directory structure.
|
||||
|
||||
## ToDos
|
||||
|
||||
1. folder and file creation
|
||||
1.1 simple file creation
|
||||
1.2 recursive file creation
|
||||
1.3 file creation
|
||||
1.1 simple file and folder creation
|
||||
1.2 recursive file and folder creation
|
||||
2. file movement
|
||||
2.1 apply a pattern what to move to where
|
||||
3. file removal
|
||||
3.1 remove all files like '*.tar'
|
||||
2.1 file deletion
|
||||
|
||||
- implement config file containing version, default names and other
|
||||
configurations
|
||||
- make file and directory creation start counting at 1 instead of 0
|
||||
- Add security check which benchmarks the creation of folders and files
|
||||
before the first execution in order to prevent either python, the file
|
||||
system or the system in general to crash.
|
||||
|
||||
## Changelog
|
||||
|
||||
<2025-10-16> V0.3.9 - Changed how the version is read
|
||||
<2025-10-05> V0.3.8 - Added file extension to file creation mode
|
||||
<2025-10-05> V0.3.7 - Added custom naming for level and branch in
|
||||
recursive mode
|
||||
<2025-10-05> V0.3.6 - Recursive mode no longer requires the -n flag
|
||||
<2025-10-04> V0.3.5 - Added a function which returns the length of a
|
||||
number
|
||||
<2025-10-04> V0.3.5 - Changed the recursive mode into an linear x*y
|
||||
pattern
|
||||
<2025-10-04> V0.3.4 - Added recursive directory creation and fixed
|
||||
numbered naming
|
||||
<2025-10-03> V0.3.3 - Added the beginning of recursive mode
|
||||
<2025-09-30> V0.3.2 - Refactoring librefit and added proper docstrings;
|
||||
begun to remove the check for the valid input and put it in the decider
|
||||
<2025-09-29> V0.3.1 - Removed the requirement for an input
|
||||
<2025-09-29> V0.3.0 - Added file creation in the pattern like
|
||||
directories
|
||||
<2025-09-29> V0.2.4 - Improved logging and log readability
|
||||
<2025-09-28> V0.2.3 - Added logging for version file and --filemode
|
||||
path to the decider
|
||||
<2025-09-28> V0.2.0 - Added librefit for standard functions
|
||||
<2025-09-28> V0.1.0 - Added the creation of multiple numbered
|
||||
directories in a given directory with the pattern default directory_n
|
||||
|
||||
10
refit/pyproject.toml
Normal file
10
refit/pyproject.toml
Normal file
@@ -0,0 +1,10 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=61.0.0"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "refit"
|
||||
version = "0.0.1"
|
||||
|
||||
[tool.setuptools.packages]
|
||||
find = { where = ["src"] }
|
||||
0
refit/src/__init__.py
Normal file
0
refit/src/__init__.py
Normal file
277
refit/src/modules/librefit.py
Normal file
277
refit/src/modules/librefit.py
Normal file
@@ -0,0 +1,277 @@
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
|
||||
from .refit_logger import logger
|
||||
|
||||
# TODO: Make a standard function for reading config files, so it is
|
||||
# reusable
|
||||
|
||||
|
||||
def get_int_length(number: int) -> int:
|
||||
"""Takes an number as its input and returns the numbers diget amount.
|
||||
|
||||
This function takes an integer number, converts it into a string and
|
||||
converts its digets. It returns the length of the number as an integer.
|
||||
|
||||
Args:
|
||||
number (int): The number you need the length of
|
||||
|
||||
Examples:
|
||||
>>> get_int_length(100)
|
||||
'3'
|
||||
>>> get_int_length(10)
|
||||
'2'
|
||||
>>> get_int_length(4000)
|
||||
'4'
|
||||
"""
|
||||
number_string = str(number)
|
||||
amount_didgets = len(number_string)
|
||||
return amount_didgets
|
||||
|
||||
|
||||
def get_standard_name_number(current_number: int, number_str_length: int) -> str:
|
||||
"""Returns a number string filled to the length of the input number
|
||||
|
||||
This function returns the number in a standartized way as a string.
|
||||
As input it takes the current number of the string to build and a
|
||||
number which determines the length of the string.
|
||||
|
||||
Args:
|
||||
current_number (str): The current number of the item.
|
||||
number_str_length (int): The length of the string which gets returned.
|
||||
|
||||
Examples:
|
||||
>>> get_standard_name_number(1, 2)
|
||||
'01'
|
||||
>>> get_standard_name_number(23, 4)
|
||||
'0023'
|
||||
"""
|
||||
# logger.debug(
|
||||
# f"FUNC: get_standard_name_number() index={current_number} string_length={number_str_length}"
|
||||
# )
|
||||
temp_current_number = str(current_number)
|
||||
standard_name_number = str.zfill(temp_current_number, number_str_length)
|
||||
# logger.debug(
|
||||
# f"FUNC: get_standard_name_number() return value= '{standard_name_number}'"
|
||||
# )
|
||||
return standard_name_number
|
||||
|
||||
|
||||
def get_standard_folder_name(name: str) -> str:
|
||||
"""Returnes a standard name either from a list or the default value.
|
||||
|
||||
This function sanitizes the input, which gets passed as a list or None from
|
||||
argparse. The function either chooses the first entry of the list, given to
|
||||
the --name argument or returns the default value 'directory'
|
||||
|
||||
Args:
|
||||
name (list[str] | None): A list of names if passed to the --name argument
|
||||
or None if no name is passed.
|
||||
|
||||
Returns:
|
||||
str: The file name. Returns 'file' as default value if name argument is 'None'
|
||||
otherwise the first element of the list.
|
||||
|
||||
Examples:
|
||||
>>> get_standard_file_name(None)
|
||||
'file'
|
||||
>>> get_standard_file_name(["example"])
|
||||
'example'
|
||||
>>> get_standard_file_name(["directory_name", "example"])
|
||||
'directory_name'
|
||||
"""
|
||||
|
||||
standard_folder_name = name[0] if name is not None else "directory"
|
||||
|
||||
return standard_folder_name
|
||||
|
||||
|
||||
def get_standard_file_name(name) -> str:
|
||||
"""Returnes a name either from a list or the default value.
|
||||
|
||||
This function sanitizes the input, which gets passed as a list or None from
|
||||
argparse. The function either chooses the first entry of the list, given to
|
||||
the --name argument or returns the default value 'file'
|
||||
|
||||
Args:
|
||||
name (list[str] | None): A list of names if passed to the --name argument
|
||||
or None if no name is passed.
|
||||
|
||||
Returns:
|
||||
str: The file name. Returns 'file' as default value if name argument is 'None'
|
||||
otherwise the first element of the list.
|
||||
|
||||
Examples:
|
||||
>>> get_standard_file_name(None)
|
||||
'file'
|
||||
>>> get_standard_file_name(["example"])
|
||||
'example'
|
||||
>>> get_standard_file_name(["file_name", "example"])
|
||||
'file_name'
|
||||
"""
|
||||
|
||||
standard_file_name = name[0] if name is not None else "file"
|
||||
|
||||
return standard_file_name
|
||||
|
||||
|
||||
def get_current_path(path) -> str:
|
||||
"""Checks if the path argument is emty and applies the current directory as working path.
|
||||
|
||||
This function takes an list with strings as an input. If the input is `None` the current
|
||||
directory is taken as the working directory.
|
||||
If the path is passed, a check for its existence takes place.
|
||||
|
||||
Args:
|
||||
path (str): _The current working directory._
|
||||
|
||||
Returns:
|
||||
str: _Returns the path of the current directory after check for existence_
|
||||
"""
|
||||
|
||||
logger.debug(f"FUNC: get_current_path() MSG: entered function with path = '{path}'")
|
||||
if path is None:
|
||||
# Set the current directory if none is passed with the command.
|
||||
path = "."
|
||||
# logger.warning(
|
||||
# f"FUNC: {get_current_path.__name__}() MSG: Path now has the value: '{path}'"
|
||||
# )
|
||||
return path
|
||||
else:
|
||||
# Checks if the path, entered by the user, exists.
|
||||
if os.path.exists(path) is True:
|
||||
# logger.debug(
|
||||
# f"FUNC: {get_current_path.__name__} MSG: Path '{path}' exists, continue...."
|
||||
# )
|
||||
return path
|
||||
else:
|
||||
ERROR_MESSAGE = (
|
||||
f"FUNC: {get_current_path.__name__} MSG: '{path}' does not exist"
|
||||
)
|
||||
logger.warning(ERROR_MESSAGE)
|
||||
print(ERROR_MESSAGE)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def create_linear_directories(
|
||||
input_path: str, target_depth: int, current_depth: int, name
|
||||
):
|
||||
"""Creates the linear directories for the x*y pattern
|
||||
|
||||
If no name is given the name of the level is defaulted to 'level'.
|
||||
Otherwise it takes the second input of the --name argument. In the
|
||||
end it appends the number of the folder.
|
||||
|
||||
Args:
|
||||
input_path ( str ): _The current working directory.
|
||||
target_depth ( int ): _The depth on how deepo directories are created._
|
||||
current_depth ( int ): _The current depth of the folder creation._
|
||||
name ( list[str] | None ): _The name of the level directories._
|
||||
"""
|
||||
|
||||
# logger.debug(
|
||||
# f"FUNC: create_linear_directories(entered) VALUES: path='{input_path}', target_depth='{target_depth}', current_depth='{current_depth}'"
|
||||
# )
|
||||
|
||||
# TODO: Find a way on how to specify the type in the function call
|
||||
# and let the if statement pass.
|
||||
|
||||
# Get base directory name
|
||||
if name is None:
|
||||
base_name = "level"
|
||||
else:
|
||||
base_name = name[1]
|
||||
|
||||
if current_depth > target_depth:
|
||||
return
|
||||
# Create directory name
|
||||
directory_name = (
|
||||
base_name
|
||||
+ "_"
|
||||
+ get_standard_name_number(current_depth, get_int_length(target_depth))
|
||||
)
|
||||
|
||||
# Create the path where to create directory
|
||||
path = os.path.join(input_path, directory_name)
|
||||
|
||||
os.mkdir(path)
|
||||
|
||||
# Recursive call of itself
|
||||
create_linear_directories(path, target_depth, current_depth + 1, name)
|
||||
|
||||
|
||||
def create_parallel_directories(input_path: str, target_depth: int, width: int, name):
|
||||
"""Creates the branches which house the levels.
|
||||
|
||||
As input it takes the input_path and the width from which it creates
|
||||
the branches of the structure. Afterwards it passes the target_depth
|
||||
to another function to create the levels of each branch.
|
||||
If 'None' is passed to the '--name' argument, the default name 'branch'
|
||||
gets used as base directory name.
|
||||
|
||||
Args:
|
||||
input_path ( str ): _The current working directory.
|
||||
target_depth ( int ): _The depth on how deepo directories are created._
|
||||
width ( int ): _The ammount of branches to create._
|
||||
name ( list[str] | None ): _The name of the level directories._
|
||||
|
||||
"""
|
||||
|
||||
# logger.debug(
|
||||
# f"FUNC: create_parallel_directories(entered) VALUES: path='{input_path}', target_depth='{target_depth}', width='{width}', name={name}"
|
||||
# )
|
||||
|
||||
# TODO: Find a way on how to specify the type in the function call
|
||||
# and let the if statement pass.
|
||||
|
||||
# Get base directory name
|
||||
if name is None:
|
||||
base_name = "branch"
|
||||
else:
|
||||
base_name = name[0]
|
||||
|
||||
for i in range(width):
|
||||
# Create directory name
|
||||
directory_name = (
|
||||
base_name + "_" + get_standard_name_number(i, get_int_length(width))
|
||||
)
|
||||
|
||||
# Create the path where to create directory
|
||||
path = os.path.join(input_path, directory_name)
|
||||
os.mkdir(path)
|
||||
|
||||
# Recursive call of itself
|
||||
create_linear_directories(
|
||||
input_path=path,
|
||||
target_depth=target_depth,
|
||||
current_depth=0,
|
||||
name=name,
|
||||
)
|
||||
|
||||
|
||||
def get_version_from_file(input_path) -> str:
|
||||
"""Returns the version of the program.
|
||||
|
||||
The function accepts an path to a version file as a string and it
|
||||
returns it version number formatted.
|
||||
|
||||
Arg:
|
||||
input_path (str): The absolute or relative path to the
|
||||
version file.
|
||||
|
||||
Example:
|
||||
>>>get_version_from_file("/path/to/file.json")
|
||||
'0.2.1'"""
|
||||
# Expands the input path
|
||||
expanded_path = os.path.expanduser(input_path)
|
||||
|
||||
# Opening the file and reading its contents, saving as as an dict.
|
||||
file_path = open(expanded_path)
|
||||
prog_version = json.load(file_path)
|
||||
|
||||
# Formatting the output before returning the string again
|
||||
pretty_version = (
|
||||
f"{prog_version['major']}.{prog_version['minor']}.{prog_version['patch']}"
|
||||
)
|
||||
return pretty_version
|
||||
168
refit/src/modules/refit_create.py
Normal file
168
refit/src/modules/refit_create.py
Normal file
@@ -0,0 +1,168 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
from .refit_logger import logger
|
||||
from . import librefit
|
||||
|
||||
|
||||
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."""
|
||||
|
||||
def __init__(self, args):
|
||||
"""Initiating variables for creation"""
|
||||
self.args = args
|
||||
|
||||
self.name = args.name
|
||||
self.input = args.input
|
||||
self.n = args.n
|
||||
self.filemode = args.filemode
|
||||
self.recursive = args.recursive
|
||||
self.e = args.e
|
||||
|
||||
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(f"FUNC: create_n_folders() ARGS: n={n} input={input} name={name}")
|
||||
|
||||
# Creating the length of the suffix number_string.
|
||||
length_n = librefit.get_int_length(n)
|
||||
|
||||
# Get either the default folder name or the input name as string.
|
||||
folder_name = librefit.get_standard_folder_name(name)
|
||||
|
||||
while n > 0:
|
||||
# iterating down for the files number.
|
||||
folder_number = n - 1
|
||||
|
||||
# Passing the number and the length of the string to get the string back.
|
||||
number_string = librefit.get_standard_name_number(folder_number, length_n)
|
||||
|
||||
# Creating path for the folder
|
||||
temp_name = f"{folder_name}_{number_string}"
|
||||
folder_creation_path = os.path.join(input, temp_name)
|
||||
|
||||
# Creating folder and subtracting n by one for the number_string
|
||||
os.mkdir(folder_creation_path)
|
||||
n -= 1
|
||||
|
||||
def create_n_files(self, n, input, name, file_extension):
|
||||
"""Creates an set ammount of files, using the default file name
|
||||
if none is provided."""
|
||||
|
||||
logger.debug(
|
||||
f"FUNC: create_n_files() MSG: Entered function VALUES: n={self.n} name={self.name} input={self.input}"
|
||||
)
|
||||
|
||||
# Creating the length of the suffix number_string.
|
||||
length_n = librefit.get_int_length(n)
|
||||
|
||||
# Get the name from the input argument.
|
||||
file_name = librefit.get_standard_file_name(name)
|
||||
|
||||
while n > 0:
|
||||
# Get number of the file(s) to create
|
||||
|
||||
file_number = n - 1
|
||||
number_string = librefit.get_standard_name_number(file_number, length_n)
|
||||
|
||||
# Get the name of the file, either applying default or using first list item.
|
||||
if file_extension is not None:
|
||||
temp_name = f"{file_name}_{number_string}.{file_extension}"
|
||||
else:
|
||||
temp_name = f"{file_name}_{number_string}"
|
||||
|
||||
file_path = Path(os.path.join(input, temp_name)) # Build file path
|
||||
file_path.touch(exist_ok=True) # creating file
|
||||
|
||||
# Counting down n for the next ieration of the while-loop
|
||||
n -= 1
|
||||
|
||||
def create_recursive(self, recursive, name, input):
|
||||
"""Creating directories recursively"""
|
||||
logger.debug(
|
||||
f"FUNC: create_recursive(beginning) MSG: entered function with following arguments: recursive='{recursive}' name='{name}' input='{input}'"
|
||||
)
|
||||
librefit.create_parallel_directories(
|
||||
input_path=input,
|
||||
target_depth=recursive[0],
|
||||
width=recursive[1],
|
||||
name=name,
|
||||
)
|
||||
|
||||
def input_validator(self):
|
||||
"""Function, which checks if the user input is valid"""
|
||||
|
||||
# Check working directory
|
||||
if self.input is None:
|
||||
self.input = librefit.get_current_path(self.input)
|
||||
logger.info(f"FUNC: input_validator(input check) VALUE: input={self.input}")
|
||||
|
||||
# Check for conflicting flags
|
||||
if self.recursive is not None and self.filemode:
|
||||
logger.error(
|
||||
f"FUNC: input_validator(recursive&filemode?) VALUES: recursive='{self.recursive}', filemode={self.filemode}"
|
||||
)
|
||||
print("Filemode and recursive do not work together.")
|
||||
sys.exit(1)
|
||||
|
||||
# Check if recursive input is an empty list
|
||||
if self.recursive is not None:
|
||||
if len(self.recursive) < 2:
|
||||
logger.error(
|
||||
"FUNC:input_validator(recursive) MSG: Invalid input, enter 2 numbers!"
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
# Exit the program if the -n argument is not passed
|
||||
if self.n is None and self.recursive is None:
|
||||
logger.error(
|
||||
f"FUNC create_dispatcher(n=None ?) MSG: the number value cannot be '{self.n}'"
|
||||
)
|
||||
print("Use the '-n' flag for the create command.")
|
||||
sys.exit(1)
|
||||
else:
|
||||
return True
|
||||
|
||||
def create_dispatcher(self):
|
||||
"""Coordination of the 'create' sub command"""
|
||||
logger.debug(
|
||||
f"FUNC: create_dispatcher() MSG: Entered decider function {self.args}"
|
||||
)
|
||||
|
||||
if self.input_validator():
|
||||
if self.filemode:
|
||||
logger.debug(
|
||||
f"FUNC: create_dispatcher(filemode) MSG: given arguments: n={self.n} input={self.input} name={self.name} file_extension={self.e}"
|
||||
)
|
||||
self.create_n_files(self.n, self.input, self.name, self.e)
|
||||
|
||||
elif self.recursive is not None:
|
||||
logger.debug(
|
||||
f"FUNC: create_dispatcher(recursive) MSG: given arguments: n={self.n} input={self.input} name={self.name} recursive={self.recursive}"
|
||||
)
|
||||
self.create_recursive(self.recursive, self.name, self.input)
|
||||
|
||||
elif not self.recursive and not self.filemode:
|
||||
logger.debug(
|
||||
f"FUNC: create_dispatcher(n_folder) MSG: given arguments: n={self.n} input={self.input} name={self.name}"
|
||||
)
|
||||
self.create_n_folders(self.n, self.input, self.name)
|
||||
|
||||
else:
|
||||
logger.debug(
|
||||
f"FUNC: create_dispatcher(exit no input) MSG: given arguments: n={self.n} input={self.input} name={self.name} recursive={self.recursive}"
|
||||
)
|
||||
print(
|
||||
"Use '-n' argument to create directories.\nPlease use 'refit create -h' for help"
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
def __call__(self):
|
||||
"""Gets called when the 'create' subcommand is used."""
|
||||
self.create_dispatcher()
|
||||
@@ -27,6 +27,3 @@ def handle_exception(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}")
|
||||
|
||||
@@ -2,32 +2,22 @@ import argparse
|
||||
import sys
|
||||
|
||||
from modules.refit_logger import logger
|
||||
from modules.refit_create import Refit_Create
|
||||
from modules.librefit import get_version_from_file
|
||||
|
||||
|
||||
# Setting Global Variables
|
||||
REFIT_VERSION = "Refit Beta 0.0.0"
|
||||
|
||||
|
||||
# ---------------------------BEGIN FUNCTIONS---------------------------
|
||||
# will be in seperate file at some point
|
||||
def refit_create(args):
|
||||
logger.info("Running in create mode")
|
||||
logger.debug(f"Arguments: {args}")
|
||||
print(f"executing on {args.input}")
|
||||
|
||||
|
||||
# ----------------------------END FUNCTIONS----------------------------
|
||||
|
||||
# NOTE: The final version file needs a dedicated place to live in
|
||||
# so the version number is always readable, independent from where it
|
||||
# is executed
|
||||
REFIT_VERSION = get_version_from_file("~/Documents/git/python/refit/src/version.json")
|
||||
|
||||
# ---------------------------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",
|
||||
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,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
)
|
||||
|
||||
# Main Parser Arguments
|
||||
@@ -35,28 +25,65 @@ parser = argparse.ArgumentParser(
|
||||
# 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",
|
||||
name="create",
|
||||
description="The create sub command lets you create files, folders and directory structures.",
|
||||
help="The create sub command lets you create files, folders and directory structures.",
|
||||
)
|
||||
create_parser.add_argument("-n", type=int, help="number of items")
|
||||
create_parser.add_argument("-i", "--input", help="input file")
|
||||
create_parser.set_defaults(func=refit_create)
|
||||
create_parser.add_argument(
|
||||
"-n",
|
||||
metavar="COUNT",
|
||||
type=int,
|
||||
help="Number of items",
|
||||
)
|
||||
create_parser.add_argument(
|
||||
"-i",
|
||||
"--input",
|
||||
metavar="PATH",
|
||||
help="Input path. If not specified the current directory is used.",
|
||||
)
|
||||
create_parser.add_argument(
|
||||
"--name",
|
||||
nargs="*",
|
||||
help="the name of the folder you want to create\n Default: directory",
|
||||
)
|
||||
create_parser.add_argument(
|
||||
"--filemode",
|
||||
action="store_true",
|
||||
help="creates files instead of directories",
|
||||
)
|
||||
create_parser.add_argument(
|
||||
"-r",
|
||||
"--recursive",
|
||||
metavar="INT",
|
||||
type=int,
|
||||
nargs=2,
|
||||
help="""Sets the recursive mode for folders to true. First argumet
|
||||
is for the depth and the second for the width.""",
|
||||
)
|
||||
create_parser.add_argument(
|
||||
"-e",
|
||||
type=str,
|
||||
help="File extension which gets appended to the end of the file name.",
|
||||
)
|
||||
create_parser.set_defaults(command_class=Refit_Create)
|
||||
|
||||
args = parser.parse_args()
|
||||
# ---------------------------ARGPARSE END-----------------------------
|
||||
|
||||
|
||||
# Dispatcher
|
||||
if hasattr(args, "func"):
|
||||
logger.debug("In hasattr()")
|
||||
args.func(args)
|
||||
# determines what code gets addressed based of the users chosen flags.
|
||||
if hasattr(args, "command_class"):
|
||||
# logger.debug(f"In dispatcher with args: {args}")
|
||||
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")
|
||||
logger.info("No input, exiting with exit code: 1")
|
||||
sys.exit(1)
|
||||
|
||||
5
refit/src/version.json
Normal file
5
refit/src/version.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"minor": 3,
|
||||
"major": 0,
|
||||
"patch": 9
|
||||
}
|
||||
60
refit/test_librefit.py
Normal file
60
refit/test_librefit.py
Normal file
@@ -0,0 +1,60 @@
|
||||
from src.modules.librefit import (
|
||||
get_current_path,
|
||||
get_standard_folder_name,
|
||||
get_standard_name_number,
|
||||
get_standard_file_name,
|
||||
)
|
||||
|
||||
|
||||
def test_get_default_file_name():
|
||||
"""Tests if the function returns the correct value"""
|
||||
default_name = get_standard_file_name(None)
|
||||
assert "file" in default_name
|
||||
|
||||
|
||||
def test_get_default_folder_name():
|
||||
"""Test if the default directory name gets returned"""
|
||||
default_name = get_standard_folder_name(None)
|
||||
assert "directory" in default_name
|
||||
|
||||
|
||||
def test_get_standard_name_number():
|
||||
"""Tests if the number function returns the correctly formatted string."""
|
||||
name_number = get_standard_name_number(20, 3)
|
||||
assert "020" in name_number
|
||||
|
||||
|
||||
def test_get_filename():
|
||||
"""Tests if a passed filename is returned properly"""
|
||||
filename = get_standard_file_name(["testname"])
|
||||
assert "testname" in filename
|
||||
|
||||
|
||||
def test_get_folder_name():
|
||||
"""Tests if the function returns the passed folder name correctly"""
|
||||
folder_name = ["folder"]
|
||||
return_folder_name = get_standard_folder_name(folder_name)
|
||||
assert "folder" in return_folder_name
|
||||
|
||||
|
||||
def test_folder_name_list():
|
||||
"""The function is supposed to only return the first name of the
|
||||
passed list"""
|
||||
folder_names = ["folder1", "folder2", "folder3"]
|
||||
return_folder_name = get_standard_folder_name(folder_names)
|
||||
assert "folder1" in return_folder_name
|
||||
|
||||
|
||||
def test_get_current_directory():
|
||||
"""Tests if the directory is set to the current directory, if None
|
||||
is passed with the argument"""
|
||||
path = None
|
||||
directory = get_current_path(path)
|
||||
assert "." in directory
|
||||
|
||||
|
||||
def test_for_existing_path():
|
||||
"""Tests if the function returns the correct path."""
|
||||
path = "/home/cerberus/Documents/books/"
|
||||
directory = get_current_path(path)
|
||||
assert "/home/cerberus/Documents/books/" in directory
|
||||
@@ -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()")
|
||||
|
||||
@@ -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}")
|
||||
|
||||
@@ -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",
|
||||
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")
|
||||
|
||||
Reference in New Issue
Block a user