gestionProjets/GestionVersion2.4.py

242 lines
No EOL
11 KiB
Python

# Todo:
# - Make an AVP folder in the current directory whe creating a new project
# - Make a BPE folder in the current directory whe creating a new project
import os
import datetime
import requests
# If colorama is not installed, notify the user
try:
from colorama import init, Fore, Style
except ImportError:
print("Please install the colorama module using 'pip install colorama' to enable colored text.")
Fore = Style = lambda x: x
debug_mode = False
software_version = "2.4"
# Initialize colorama
init()
# Function to pause if debug mode is enabled
def pause_debug(message="No message provided."):
if debug_mode:
input(Fore.YELLOW + "[DEBUG] " + message + " - Enter to continue.\n" + Style.RESET_ALL)
# Function to check the latest version from Gitea
def check_latest_version():
gitea_api_url = "https://gitea.achilletoupin.com/api/v1/repos/gribse/gestionProjets/releases/latest"
try:
response = requests.get(gitea_api_url)
response.raise_for_status()
latest_release = response.json()
latest_version = latest_release['tag_name']
pause_debug(Fore.GREEN + "Latest version: " + latest_version + Style.RESET_ALL)
return latest_version
except requests.RequestException as e:
print(Fore.RED + "Error checking latest version: " + str(e) + Style.RESET_ALL)
return None
def createNewProject():
# Prompt the user for the project name
project_name = input("Enter the project name:\n")
pause_debug(f"Project name entered: {project_name}")
# Get the current year and month
current_year = datetime.datetime.now().year
current_month = datetime.datetime.now().strftime("%m")
pause_debug(f"Current year and month: {current_year} {current_month}")
# Get all folders starting with the current year and month in the source directory
pattern = f"{current_year} {current_month}"
pause_debug(f"Pattern to search for: {pattern}")
folders = [f for f in os.listdir(current_directory) if os.path.isdir(os.path.join(current_directory, f)) and f.startswith(pattern)]
if not folders:
latest_number = 0
else:
latest_number = max(int(f.split()[2]) for f in folders)
pause_debug(f"Folders matching pattern '{pattern}' found: {', '.join(folders)}")
# Find the folder with the largest number after the year and month
if not folders:
projet_number_in_month = 1
else:
latest_number = max(int(f.split()[2]) for f in folders)
projet_number_in_month = latest_number + 1
pause_debug(f"New folder number determined: {projet_number_in_month}")
# Create the new folder name
new_folder_name = f"{current_year} {current_month} {projet_number_in_month} {project_name}"
pause_debug(f"New folder name: {new_folder_name}")
# Create the new folder
new_folder_path = os.path.join(current_directory, new_folder_name)
print(f"Creating new folder: {new_folder_name}")
os.makedirs(new_folder_path, exist_ok=True)
pause_debug(f"New folder created: {new_folder_path}")
# Copy this file to the new folder
source_file = os.path.abspath(__file__)
destination_file = os.path.join(new_folder_path, os.path.basename(__file__))
with open(source_file, 'rb') as src_file:
with open(destination_file, 'wb') as dst_file:
dst_file.write(src_file.read())
pause_debug(f"File copied to new folder: {destination_file}")
# Create the AVP & BPE folders
avp_folder_path = os.path.join(new_folder_path, "AVP")
bpe_folder_path = os.path.join(new_folder_path, "BPE")
print(f"Creating AVP and BPE folders in {new_folder_name}")
os.makedirs(avp_folder_path, exist_ok=True)
os.makedirs(bpe_folder_path, exist_ok=True)
pause_debug(f"AVP and BPE folders created in {new_folder_name}")
# Create the first AVP folder
createNewAVP()
# Create a placeholder file to indicate the default file name
placeholder_filename = f"{current_year}{current_month}{projet_number_in_month}AVP01-{project_name}"
placeholder_file_path = os.path.join(new_folder_path, "README.txt")
def createNewAVP():
# Creating AVP folders
folders = [f for f in os.listdir(avp_directory) if os.path.isdir(os.path.join(avp_directory, f)) and f.startswith("AVP")]
pause_debug(f"Folders found: {', '.join(folders)}")
if not folders:
print("No folders found. Creating first folder: AVP01")
os.makedirs(os.path.join(avp_directory, "AVP01"), exist_ok=True)
pause_debug("First folder created: AVP01")
else:
pause_debug("Finding the latest folder")
latest_number = max(int(f[3:]) for f in folders)
projet_number_in_month = latest_number + 1
projet_number_in_month = str(projet_number_in_month).zfill(2)
new_folder_name = f"AVP{str(projet_number_in_month).zfill(2)}"
pause_debug(f"New folder number determined: {projet_number_in_month}")
input(f"\nWould you like to create {new_folder_name}? Press any key to continue or CTRL+C to exit...")
pause_debug(f"User confirmed creation of new folder: {new_folder_name}")
new_folder_path = os.path.join(avp_directory, new_folder_name)
print(f"Creating {new_folder_name}")
os.makedirs(new_folder_path, exist_ok=True)
pause_debug(f"New folder created: {new_folder_path}")
print(f"Copying files from {avp_directory} to {new_folder_name} :")
# Copy files from the last folder to the new folder
last_folder_path = os.path.join(avp_directory, f"AVP{str(latest_number).zfill(2)}")
for filename in os.listdir(last_folder_path):
source_file = os.path.join(last_folder_path, filename)
if os.path.isfile(source_file):
new_filename = filename.replace(f"AVP{str(latest_number).zfill(2)}", new_folder_name)
destination_file = os.path.join(new_folder_path, new_filename)
with open(source_file, 'rb') as src_file:
with open(destination_file, 'wb') as dst_file:
dst_file.write(src_file.read())
print(f"- {new_filename}")
# Calculate the total size of the newly created directory
total_size = 0
for dirpath, dirnames, filenames in os.walk(new_folder_path):
for f in filenames:
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
total_size_mb = total_size / (1024 * 1024) # Convert bytes to megabytes
print(f"Total size : {total_size_mb:.2f} MB")
def displayWelcomeMessage():
ascii_art = """
╔════════════════════════════════════════════════════════════════════════════╗
║ __ _ ____ _ __ ║
║ ____ ____ _____/ /_(_)___ ____ / __ \\_________ (_)__ / /______ ║
║ / __ `/ _ \\/ ___/ __/ / __ \\/ __ \\/ /_/ / ___/ __ \\ / / _ \\/ __/ ___/ ║
║ / /_/ / __(__ ) /_/ / /_/ / / / / ____/ / / /_/ / / / __/ /_(__ ) ║
\\__, /\\___/____/\\__/_/\\____/_/ /_/_/ /_/ \\____/_/ /\\___/\\__/____/.py ║
║ /____/ /___/ ║
║ Your one-file tool to manage project directories ║
╚════════════════════════════════════════════════════════════════════════════╝
"""
print(ascii_art)
# Function to display the menu
def display_menu():
print("Select an action:")
print("1. Create New Project")
print("2. Create New AVP")
print("h. Help")
print("q. Quit")
def displayHelp():
print("This program is designed to help you manage project directories.")
print("When you run the program, you will be presented with a menu.")
print("You can choose to create a new project or create a new AVP.")
print("If you are in a parent directory named 'Projets', you will be asked if you want to initiate a new project.")
print("If you are in a project directory, you will be asked if you want to make a new AVP.")
print("You can also press 'H' to display this help message.")
print("You can press 'Q' to quit the program.")
def main():
# Display the welcome message
displayWelcomeMessage()
# Check if the current version is equal to the latest version
latest_version = check_latest_version()
if latest_version:
if software_version == latest_version:
print(Fore.GREEN + f"You are using the latest version: {software_version}" + Style.RESET_ALL)
elif software_version > latest_version:
print(Fore.YELLOW + f"You are using a newer version: {software_version}. The latest version is: {latest_version}" + Style.RESET_ALL)
else:
print(Fore.RED + f"A new version is available: {latest_version}. You are using version: {software_version}" + Style.RESET_ALL)
else:
print(Fore.RED + "Could not check the latest version." + Style.RESET_ALL)
# Get the various directories
current_directory = os.path.dirname(os.path.abspath(__file__)) # Get the current directory
pause_debug(f"Current directory: {current_directory}")
avp_directory = os.path.join(current_directory, "AVP") # Set the source directory to the 'Projets' directory
pause_debug(f"AVP directory: {avp_directory}")
# Check if the current directory is a parent directory named "Projets", and if so, ask the user if they want to initiate a new project
if os.path.basename(os.path.dirname(avp_directory)) == "Projets":
pause_debug("Checked parent directory. It is named 'Projets'.")
choice = input("You are in a parent directory named \"Projets\". Would you like to initiate a new project ? (y/n)\n").strip().upper()
if choice == 'Y':
createNewProject()
# Check if there is an AVP folder in the current directory, and if so, ask the user if they want to make a new AVP
elif "AVP" in os.listdir(current_directory):
choice = input("You seem to be in a project directory. Would you like to make a new AVP ? (y/n)\n").strip().upper()
if choice == 'Y':
pause_debug("User confirmed creation of new AVP.")
createNewAVP()
else:
print("invalid choice. Please try again.")
# If the user is not in a parent directory named "Projets" or an AVP directory, display the menu
else:
while True:
display_menu()
choice = input("Enter your choice: ").strip().upper()
if choice == '1':
createNewProject()
elif choice == '2':
createNewAVP()
elif choice == 'H':
displayHelp()
elif choice == 'Q':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()