Certainly! Below is a Python script that generates the specified directory and file structure in the current working directory. The script checks if each directory or file already exists and skips creation if it does.
Python Script: generate_structure.py
python
import os
from pathlib import Path
def create_directories_and_files(base_path, structure):
"""
Recursively creates directories and files based on the provided structure.
:param base_path: The base Path object where the structure will be created.
:param structure: A dictionary representing the directory and file structure.
"""
for name, content in structure.items():
current_path = base_path / name
if isinstance(content, dict):
# It's a directory
if not current_path.exists():
print(f"Creating directory: {current_path}")
current_path.mkdir(parents=True, exist_ok=True)
else:
print(f"Directory already exists, skipping: {current_path}")
# Recursively create subdirectories and files
create_directories_and_files(current_path, content)
elif isinstance(content, list):
# It's a directory containing files
if not current_path.exists():
print(f"Creating directory: {current_path}")
current_path.mkdir(parents=True, exist_ok=True)
else:
print(f"Directory already exists, skipping: {current_path}")
for file in content:
file_path = current_path / file
if not file_path.exists():
print(f"Creating file: {file_path}")
file_path.touch()
else:
print(f"File already exists, skipping: {file_path}")
elif isinstance(content, str):
# It's a file
if not current_path.exists():
print(f"Creating file: {current_path}")
current_path.touch()
else:
print(f"File already exists, skipping: {current_path}")
if __name__ == "__main__":
# Define the desired structure
project_structure = {
"public": {
"icons": ["icon16.png", "icon48.png", "icon128.png"]
},
"src": {
# Files directly under src
"background.js": "",
"content.js": "",
"popup": ["popup.html", "popup.js"],
"options": ["options.html", "options.js"],
"scripts": ["regionSelector.js"],
},
"styles": ["popup.css", "options.css", "annotation.css"],
"manifest.json": "",
"vite.config.js": "",
"package.json": "",
"package-lock.json": "",
}
# Get the current working directory
current_dir = Path.cwd()
# Create the structure
create_directories_and_files(current_dir, project_structure)
print("\nStructure generation completed.")
How It Works
Import Modules:
os: Provides a way of using operating system-dependent functionality.
Path from pathlib: Offers an object-oriented approach to handling filesystem paths.
Function create_directories_and_files:
Parameters:
base_path: The base directory where the structure will be created.
structure: A dictionary representing the desired directory and file hierarchy.
Logic:
Iterates through each item in the structure dictionary.
If the item is a dictionary, it represents a subdirectory. The function creates the directory (if it doesn't exist) and recursively calls itself to handle nested structures.
If the item is a list, it represents files within a directory. The function ensures the directory exists and creates each file (if it doesn't exist).
If the item is a string, it represents a single file. The function creates the file (if it doesn't exist).
Main Execution:
Defines the project_structure dictionary that mirrors your desired folder and file layout.
Retrieves the current working directory using Path.cwd().
Calls create_directories_and_files to create the structure.
Prints a completion message.
Usage
Save the Script:
Save the above script to a file named generate_structure.py in the directory where you want to create the project structure.
Run the Script:
Open a terminal or command prompt.
Navigate to the directory containing generate_structure.py.
Execute the script using Python:
bash
python generate_structure.py
Script Output:
The script will print messages indicating whether each directory or file is being created or skipped because it already exists.
Result:
After running the script, your current directory will have the following structure:
File Contents: This script creates empty files. If you need to add specific content to any file, you can modify the script to write data to the files after creating them. For example:
python
# After creating the file
file_path.touch()
with file_path.open('w') as f:
f.write("// Your JavaScript content here")
Idempotent Operation: Running the script multiple times won't overwrite existing files or directories; it will simply skip those that already exist.
Customization: You can easily modify the project_structure dictionary to add more directories or files as needed.
Conclusion
This script provides a straightforward way to set up your project structure automatically, ensuring consistency and saving time. Feel free to enhance it further based on your specific requirements!