Certainly! I can help you create a robust Python script that takes a directory structure input—either in a tree-like text format or as JSON—and generates a corresponding CLI command to create the directories and files as specified. This script will handle parsing, error checking, and support both input modes seamlessly.
Overview
The script, named struct2cli.py, will perform the following:
-
Accept Input:
- Tree-like Text Format: Similar to the example you provided.
- JSON Format: A structured JSON representing directories and files.
-
Generate CLI Command:
- Constructs
mkdir -p commands to create directories.
- Constructs
touch commands to create empty files.
-
Error Handling:
- Validates input formats.
- Provides meaningful error messages for invalid inputs.
-
Usage Flexibility:
- Command-line arguments to specify input type and input data.
- Option to output the command or execute it directly.
Sample Script: struct2cli.py
Below is the Python script that accomplishes the above functionalities:
#!/usr/bin/env python3
import argparse
import json
import os
import re
import sys
from pathlib import Path
from typing import Any, Dict, List, Tuple
def parse_tree_input(tree_input: str) -> Tuple[Dict[str, Any], List[str]]:
"""
Parses a tree-like directory structure into a nested dictionary and a list of files.
"""
lines = tree_input.strip().split('\n')
stack = []
root = {}
current_dict = root
prev_indent = 0
file_paths = []
for line in lines:
# Determine the indentation level
indent = len(line) - len(line.lstrip(' '))
name = line.strip('├── ').strip('└── ').strip()
# Adjust the current_dict based on indentation
if indent > prev_indent:
stack.append(current_dict)
elif indent < prev_indent:
for _ in range((prev_indent - indent) // 4):
current_dict = stack.pop()
prev_indent = indent
if name.endswith('/'):
dir_name = name.rstrip('/')
current_dict[dir_name] = {}
current_dict = current_dict[dir_name]
else:
current_dict[name] = None
# Build the full path
path = build_full_path(root, name)
file_paths.append(path)
return root, file_paths
def build_full_path(d: Dict[str, Any], filename: str, path: str = '') -> str:
for key, value in d.items():
if value is None:
if key == filename:
return os.path.join(path, key)
elif isinstance(value, dict):
new_path = os.path.join(path, key)
result = build_full_path(value, filename, new_path)
if result:
return result
return ''
def parse_json_input(json_input: Dict[str, Any], path: str = '') -> Tuple[List[str], List[str]]:
"""
Parses a JSON directory structure into lists of directories and files.
"""
dirs = []
files = []
for key, value in json_input.items():
current_path = os.path.join(path, key)
if isinstance(value, dict):
dirs.append(current_path)
sub_dirs, sub_files = parse_json_input(value, current_path)
dirs.extend(sub_dirs)
files.extend(sub_files)
elif value is None:
files.append(current_path)
return dirs, files
def generate_cli_command(dirs: List[str], files: List[str]) -> str:
"""
Generates the CLI command for mkdir and touch.
"""
if not dirs and not files:
return ""
mkdir_cmd = ""
touch_cmd = ""
if dirs:
mkdir_cmd = "mkdir -p " + " ".join([f'"{d}"' for d in dirs])
if files:
touch_cmd = "touch " + " ".join([f'"{f}"' for f in files])
if mkdir_cmd and touch_cmd:
return mkdir_cmd + " \\\n && " + touch_cmd
elif mkdir_cmd:
return mkdir_cmd
else:
return touch_cmd
def main():
parser = argparse.ArgumentParser(
description="Generate CLI commands to create directories and files from a structure input."
)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
'--input-tree',
type=str,
help='Directory structure in tree-like text format.'
)
group.add_argument(
'--input-json',
type=str,
help='Directory structure in JSON format.'
)
parser.add_argument(
'--execute',
action='store_true',
help='Execute the generated CLI command.'
)
args = parser.parse_args()
try:
if args.input_tree:
directory_structure, files = parse_tree_input(args.input_tree)
# Extract directories from the dictionary
dirs = extract_directories(directory_structure)
else:
json_data = json.loads(args.input_json)
dirs, files = parse_json_input(json_data)
command = generate_cli_command(dirs, files)
if command:
print("Generated CLI Command:\n")
print(command)
if args.execute:
print("\nExecuting the command...")
os.system(command)
else:
print("No directories or files to create.")
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
def extract_directories(d: Dict[str, Any], path: str = '') -> List[str]:
dirs = []
for key, value in d.items():
current_path = os.path.join(path, key)
if isinstance(value, dict):
dirs.append(current_path)
dirs.extend(extract_directories(value, current_path))
return dirs
if __name__ == "__main__":
main()
How It Works
-
Input Parsing:
- Tree-like Input: The script parses each line, determines the indentation to understand the hierarchy, and builds a nested dictionary representing directories and files.
- JSON Input: It recursively traverses the JSON structure to extract directories and files.
-
Command Generation:
- Directories: Uses
mkdir -p with quoted paths to handle spaces or special characters.
- Files: Uses
touch with quoted filenames.
-
Execution Option:
- By default, the script will only print the generated CLI command.
- If the
--execute flag is provided, it will run the command directly using os.system.
Usage Examples
1. Using Tree-like Text Input
Suppose you have the following directory structure:
file_converter/
├── app/
│ ├── __init__.py
│ ├── config.py
│ ├── converters/
│ │ ├── __init__.py
│ │ ├── document_converters.py
│ │ ├── image_converters.py
│ │ ├── spreadsheet_converters.py
│ │ └── presentation_converters.py
│ ├── models.py
│ ├── routes.py
│ ├── utils.py
│ └── logging_config.py
├── static/
│ └── swagger.yaml
├── requirements.txt
├── logs/
├── run.py
└── README.md
Command:
python3 struct2cli.py --input-tree "
file_converter/
├── app/
│ ├── __init__.py
│ ├── config.py
│ ├── converters/
│ │ ├── __init__.py
│ │ ├── document_converters.py
│ │ ├── image_converters.py
│ │ ├── spreadsheet_converters.py
│ │ └── presentation_converters.py
│ ├── models.py
│ ├── routes.py
│ ├── utils.py
│ └── logging_config.py
├── static/
│ └── swagger.yaml
├── requirements.txt
├── logs/
├── run.py
└── README.md
"
Output:
mkdir -p "file_converter/app" "file_converter/app/converters" "file_converter/static" "file_converter/logs" \
&& touch "file_converter/app/__init__.py" "file_converter/app/config.py" "file_converter/app/models.py" "file_converter/app/routes.py" "file_converter/app/utils.py" "file_converter/app/logging_config.py" "file_converter/app/converters/__init__.py" "file_converter/app/converters/document_converters.py" "file_converter/app/converters/image_converters.py" "file_converter/app/converters/spreadsheet_converters.py" "file_converter/app/converters/presentation_converters.py" "file_converter/static/swagger.yaml" "file_converter/requirements.txt" "file_converter/run.py" "file_converter/README.md"
2. Using JSON Input
JSON Structure (structure.json):
{
"file_converter": {
"app": {
"__init__.py": null,
"config.py": null,
"converters": {
"__init__.py": null,
"document_converters.py": null,
"image_converters.py": null,
"spreadsheet_converters.py": null,
"presentation_converters.py": null
},
"models.py": null,
"routes.py": null,
"utils.py": null,
"logging_config.py": null
},
"static": {
"swagger.yaml": null
},
"requirements.txt": null,
"logs": {},
"run.py": null,
"README.md": null
}
}
Command:
python3 struct2cli.py --input-json "$(cat structure.json)"
Output:
mkdir -p "file_converter/app" "file_converter/app/converters" "file_converter/static" "file_converter/logs" \
&& touch "file_converter/app/__init__.py" "file_converter/app/config.py" "file_converter/app/models.py" "file_converter/app/routes.py" "file_converter/app/utils.py" "file_converter/app/logging_config.py" "file_converter/app/converters/__init__.py" "file_converter/app/converters/document_converters.py" "file_converter/app/converters/image_converters.py" "file_converter/app/converters/spreadsheet_converters.py" "file_converter/app/converters/presentation_converters.py" "file_converter/static/swagger.yaml" "file_converter/requirements.txt" "file_converter/run.py" "file_converter/README.md"
3. Executing the Generated Command
If you want the script to execute the generated command immediately, use the --execute flag:
python3 struct2cli.py --input-json "$(cat structure.json)" --execute
This will create the directories and files as specified.
Enhancements and Best Practices
-
Quoting Paths: The script quotes each path to handle spaces and special characters properly.
-
Cross-Platform Compatibility: While mkdir -p and touch are Unix-specific commands, you can modify the script to support Windows commands if needed.
-
Error Handling: The script includes try-except blocks to catch and display errors gracefully.
-
Extensibility: You can extend the script to support additional features like setting file permissions, adding boilerplate code to files, etc.
-
Validation: Incorporate more robust validation for the input structures to ensure they are well-formed.
Making the Script Executable
To run the script directly without prefixing python3, make it executable:
chmod +x struct2cli.py
Then, run it as:
./struct2cli.py --input-tree "..."
Conclusion
This struct2cli.py script provides a flexible and robust solution to generate CLI commands for creating complex directory and file structures from either tree-like text inputs or JSON. It includes error handling and supports direct execution of the generated commands, making it a powerful tool for automating project scaffolding.
Feel free to customize and extend the script to better fit your specific needs!