migration vers python, ajout d'un menu et de la création d'un projet

This commit is contained in:
gribse 2024-10-10 17:03:52 +02:00
parent 9eadeb4b0a
commit f4719b115a
10 changed files with 306 additions and 61 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 72 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 72 MiB

164
GestionVersion2.0.py Normal file
View file

@ -0,0 +1,164 @@
import os
import datetime
current_directory = os.path.dirname(os.path.abspath(__file__)) # Get the current directory
debug_mode = False
source_directory = os.path.join(current_directory, "AVP") # Set the source directory to the 'Projets' directory
# Function to pause if debug mode is enabled
def pause_debug(message="No message provided."):
if debug_mode:
input(message+"\nPlease press a key to continue.")
def createNewProject():
pause_debug("Checked parent directory. It is named 'Projets'.")
# Prompt the user for the project name
project_name = input("Enter the project name: ")
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}"
folders = [f for f in os.listdir(source_directory) if os.path.isdir(os.path.join(source_directory, f)) and f.startswith(pattern)]
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:
new_number = 1
else:
latest_number = max(int(f.split()[2]) for f in folders)
new_number = latest_number + 1
pause_debug(f"New folder number determined: {new_number}")
# Create the new folder name
new_folder_name = f"{current_year} {current_month} {new_number} {project_name}"
pause_debug(f"New folder name: {new_folder_name}")
# Create the new folder
new_folder_path = os.path.join(source_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}")
def createNewAVP():
# Creating AVP folders
folders = [f for f in os.listdir(source_directory) if os.path.isdir(os.path.join(source_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(source_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)
new_number = latest_number + 1
new_folder_name = f"AVP{str(new_number).zfill(2)}"
pause_debug(f"New folder number determined: {new_number}")
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(source_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 {source_directory} to {new_folder_name} :")
# Copy files from the last folder to the new folder
last_folder_path = os.path.join(source_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():
displayWelcomeMessage()
# 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(source_directory)) == "Projets":
choice = input("You are in a parent directory named \"Projets\". Would you like to initiate a new project ? (y/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()

View file

@ -1,61 +0,0 @@
# Define the source directory
$sourceDirectory = ".\AVP"
# Get all folders starting with "AVP" in the source directory
Write-Host "Getting folders in $sourceDirectory"
$folders = Get-ChildItem -Path $sourceDirectory -Directory | Where-Object { $_.Name -like "AVP*" }
# If no folders are found, create the first folder
if ($folders.Count -eq 0) {
Write-Host "No folders found. Creating first folder: AVP01"
New-Item -ItemType Directory -Path (Join-Path -Path $sourceDirectory -ChildPath "AVP01") -ErrorAction SilentlyContinue
return
}
# Find the folder with the largest number after "AVP"
Write-Host "Finding the latest folder"
$latestFolder = $folders | Sort-Object -Property { [int]($_.Name -replace "[^\d]") } | Select-Object -Last 1
# Increment the number in the folder name
$latestNumber = [int]($latestFolder.Name -replace "[^\d]")
$newNumber = $latestNumber + 1
$newFolderName = "AVP" + $newNumber.ToString().PadLeft(2, '0')
# List to the console the folders found, ask before creating the new one "AVPXX"
Write-Host "`nFolders found:"
$folders | ForEach-Object { Write-Host $_.Name }
Write-Host "`nWould you like to create the nex AVP "$newFolderName" ? Press any key to continue or CTRL+C to exit..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
# Create the new folder
$newFolderPath = Join-Path -Path $sourceDirectory -ChildPath $newFolderName
Write-Host "Creating new folder: $newFolderName"
New-Item -ItemType Directory -Path $newFolderPath -ErrorAction SilentlyContinue
# Copy the contents of the latest folder to the new folder
$latestFolderPath = Join-Path -Path $sourceDirectory -ChildPath $latestFolder.Name
$filesToCopy = Get-ChildItem -Path $latestFolderPath -File | Where-Object { $_.Extension -ne ".stl" }
foreach ($file in $filesToCopy) {
$newFileName = $file.Name -replace "AVP\d{2}", $newFolderName
$newFilePath = Join-Path -Path $newFolderPath -ChildPath $newFileName
Write-Host "Copying file: $($file.Name)"
Copy-Item -Path $file.FullName -Destination $newFilePath
}
# Pause at the end
$filesCopied = Get-ChildItem -Path $newFolderPath -File
$totalSize = 0
foreach ($file in $filesCopied) {
$totalSize += $file.Length
}
$sizeInMB = [Math]::Round($totalSize / 1MB, 1)
Write-Host "`nAll files copied for a total of $sizeInMB MB.`nPress any key to exit..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

View file

@ -0,0 +1,71 @@
# Define the source directory
$sourceDirectory = ".\AVP"
# Check if the parent directory is named "Projets"
$parentDirectory = Split-Path -Path $sourceDirectory -Parent
if ((Split-Path -Path $parentDirectory -Leaf) -eq "Projets") {
# Prompt the user for the project name
$projectName = Read-Host "Enter the project name"
# Get the current year and month
$currentYear = (Get-Date).Year
$currentMonth = (Get-Date).Month.ToString("D2")
# Get all folders starting with the current year and month in the source directory
$pattern = "$currentYear $currentMonth*"
$folders = Get-ChildItem -Path $sourceDirectory -Directory | Where-Object { $_.Name -like $pattern }
# Find the folder with the largest number after the year and month
if ($folders.Count -eq 0) {
$newNumber = 1
} else {
$latestFolder = $folders | Sort-Object -Property { [int]($_.Name -replace "[^\d]") } | Select-Object -Last 1
$latestNumber = [int]($latestFolder.Name -replace "[^\d]")
$newNumber = $latestNumber + 1
}
# Create the new folder name
$newFolderName = "$currentYear $currentMonth $newNumber $projectName"
# Create the new folder
$newFolderPath = Join-Path -Path $sourceDirectory -ChildPath $newFolderName
Write-Host "Creating new folder: $newFolderName"
New-Item -ItemType Directory -Path $newFolderPath -ErrorAction SilentlyContinue
# Copy the current script to the new folder
$currentScriptPath = $MyInvocation.MyCommand.Path
Copy-Item -Path $currentScriptPath -Destination $newFolderPath -ErrorAction SilentlyContinue
# Create "AVP" and "Donnees" folders inside the new folder
New-Item -ItemType Directory -Path (Join-Path -Path $newFolderPath -ChildPath "AVP") -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Path (Join-Path -Path $newFolderPath -ChildPath "Donnees") -ErrorAction SilentlyContinue
} else {
# Existing logic for creating AVP folders
Write-Host "Getting folders in $sourceDirectory"
$folders = Get-ChildItem -Path $sourceDirectory -Directory | Where-Object { $_.Name -like "AVP*" }
if ($folders.Count -eq 0) {
Write-Host "No folders found. Creating first folder: AVP01"
New-Item -ItemType Directory -Path (Join-Path -Path $sourceDirectory -ChildPath "AVP01") -ErrorAction SilentlyContinue
return
}
Write-Host "Finding the latest folder"
$latestFolder = $folders | Sort-Object -Property { [int]($_.Name -replace "[^\d]") } | Select-Object -Last 1
$latestNumber = [int]($latestFolder.Name -replace "[^\d]")
$newNumber = $latestNumber + 1
$newFolderName = "AVP" + $newNumber.ToString().PadLeft(2, '0')
Write-Host "`nFolders found:"
$folders | ForEach-Object { Write-Host $_.Name }
Write-Host "`nWould you like to create the next AVP "$newFolderName" ? Press any key to continue or CTRL+C to exit..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
$newFolderPath = Join-Path -Path $sourceDirectory -ChildPath $newFolderName
Write-Host "Creating new folder: $newFolderName"
New-Item -ItemType Directory -Path $newFolderPath -ErrorAction SilentlyContinue
}

View file

@ -0,0 +1,71 @@
# Define the source directory
$sourceDirectory = ".\AVP"
# Check if the parent directory is named "Projets"
$parentDirectory = Split-Path -Path $sourceDirectory -Parent
if ((Split-Path -Path $parentDirectory -Leaf) -eq "Projets") {
# Prompt the user for the project name
$projectName = Read-Host "Enter the project name"
# Get the current year and month
$currentYear = (Get-Date).Year
$currentMonth = (Get-Date).Month.ToString("D2")
# Get all folders starting with the current year and month in the source directory
$pattern = "$currentYear $currentMonth*"
$folders = Get-ChildItem -Path $sourceDirectory -Directory | Where-Object { $_.Name -like $pattern }
# Find the folder with the largest number after the year and month
if ($folders.Count -eq 0) {
$newNumber = 1
} else {
$latestFolder = $folders | Sort-Object -Property { [int]($_.Name -replace "[^\d]") } | Select-Object -Last 1
$latestNumber = [int]($latestFolder.Name -replace "[^\d]")
$newNumber = $latestNumber + 1
}
# Create the new folder name
$newFolderName = "$currentYear $currentMonth $newNumber $projectName"
# Create the new folder
$newFolderPath = Join-Path -Path $sourceDirectory -ChildPath $newFolderName
Write-Host "Creating new folder: $newFolderName"
New-Item -ItemType Directory -Path $newFolderPath -ErrorAction SilentlyContinue
# Copy the current script to the new folder
$currentScriptPath = $MyInvocation.MyCommand.Path
Copy-Item -Path $currentScriptPath -Destination $newFolderPath -ErrorAction SilentlyContinue
# Create "AVP" and "Donnees" folders inside the new folder
New-Item -ItemType Directory -Path (Join-Path -Path $newFolderPath -ChildPath "AVP") -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Path (Join-Path -Path $newFolderPath -ChildPath "Donnees") -ErrorAction SilentlyContinue
} else {
# Existing logic for creating AVP folders
Write-Host "Getting folders in $sourceDirectory"
$folders = Get-ChildItem -Path $sourceDirectory -Directory | Where-Object { $_.Name -like "AVP*" }
if ($folders.Count -eq 0) {
Write-Host "No folders found. Creating first folder: AVP01"
New-Item -ItemType Directory -Path (Join-Path -Path $sourceDirectory -ChildPath "AVP01") -ErrorAction SilentlyContinue
return
}
Write-Host "Finding the latest folder"
$latestFolder = $folders | Sort-Object -Property { [int]($_.Name -replace "[^\d]") } | Select-Object -Last 1
$latestNumber = [int]($latestFolder.Name -replace "[^\d]")
$newNumber = $latestNumber + 1
$newFolderName = "AVP" + $newNumber.ToString().PadLeft(2, '0')
Write-Host "`nFolders found:"
$folders | ForEach-Object { Write-Host $_.Name }
Write-Host "`nWould you like to create the next AVP "$newFolderName" ? Press any key to continue or CTRL+C to exit..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
$newFolderPath = Join-Path -Path $sourceDirectory -ChildPath $newFolderName
Write-Host "Creating new folder: $newFolderName"
New-Item -ItemType Directory -Path $newFolderPath -ErrorAction SilentlyContinue
}