Skip to content

Commit f4e758f

Browse files
authored
Refactor info command (#16)
### Issue <!-- Please link the GitHub issues related to this PR, if available --> ### Description <!-- Please explain the changes you made here. Help your reviewers by guiding them through your key changes, implementation decisions etc. You can even include snippets of output or screenshots. A good, clear description == a faster review :) --> ### Checklist - [ ] I have read the [contributing guidelines](https://github.com/httpdss/struct/blob/main/README.md#contributing). - [ ] My code follows the code style of this project. - [ ] I have performed a self-review of my own code. - [ ] I have added tests that prove my fix is effective or that my feature works. - [ ] New and existing unit tests pass locally with my changes. - [ ] I have updated the documentation accordingly. ### Screenshots (if applicable) <!-- Add screenshots to illustrate the changes made in the pull request --> ### Additional Comments <!-- Add any other context or comments about the pull request here -->
1 parent 591fe91 commit f4e758f

File tree

5 files changed

+117
-24
lines changed

5 files changed

+117
-24
lines changed

.devcontainer/devcontainer.json

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,7 @@
55
// Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
66
"image": "mcr.microsoft.com/devcontainers/python:1-3.12-bullseye",
77
"features": {
8-
"ghcr.io/devcontainers/features/python:1": {
9-
"installTools": true,
10-
"version": "latest"
11-
},
12-
"ghcr.io/lentzi90/features/yamlfmt:0": {
13-
"version": "v0.14.0"
14-
},
15-
"ghcr.io/gvatsal60/dev-container-features/pre-commit:1": {}
8+
169
},
1710

1811
// Features to add to the dev container. More info: https://containers.dev/features.
@@ -25,7 +18,12 @@
2518
"postCreateCommand": "bash ./scripts/devcontainer_start.sh",
2619

2720
// Configure tool-specific properties.
28-
// "customizations": {},
21+
"customizations": {
22+
"vscode": {
23+
"extensions": [
24+
]
25+
}
26+
},
2927

3028
// Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
3129
"remoteUser": "root"

struct_module/commands/import.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
from struct_module.commands import Command
2+
import os
3+
import yaml
4+
5+
# Import command class
6+
# This class is responsible for importing a structure definition given a file path. It will create the structure in the base path provided.
7+
class ImportCommand(Command):
8+
def __init__(self, parser):
9+
super().__init__(parser)
10+
parser.add_argument('import_from', type=str, help='Directory to import the structure from')
11+
parser.add_argument('-o', '--output-path', type=str, help='Path to the output directory', default='.')
12+
parser.set_defaults(func=self.execute)
13+
14+
def execute(self, args):
15+
self.logger.info(f"Importing structure from {args.import_from} to {args.output_path}")
16+
17+
self._import_structure(args)
18+
19+
20+
def _import_structure(self, args):
21+
raise NotImplementedError("This method needs to be implemented")
22+
# # Check if the import_from directory exists
23+
# if not os.path.exists(args.import_from):
24+
# self.logger.error(f"Directory not found: {args.import_from}")
25+
# return
26+
27+
# # Define the path for the structure.yaml file
28+
# structure_definition = os.path.join(args.output_path, 'structure.yaml')
29+
30+
# # Check if the output_path exists, if not, create it
31+
# if not os.path.exists(args.output_path):
32+
# self.logger.warning(f"Output path not found: {args.output_path}, creating it")
33+
# os.makedirs(args.output_path)
34+
35+
# # Check if the structure.yaml file already exists
36+
# if os.path.exists(structure_definition):
37+
# self.logger.warning(f"Structure definition already exists at {structure_definition}")
38+
# # Ask the user if they want to overwrite the existing structure.yaml file
39+
# if input("Do you want to overwrite it? (y/N) ").lower() != 'y':
40+
# return
41+
42+
# # Initialize the structure dictionary
43+
# generated_structure = {
44+
# 'structure': [],
45+
# 'folders': [],
46+
# 'variables': []
47+
# }
48+
49+
# for root, dirs, files in os.walk(args.import_from):
50+
# for file in files:
51+
# self.logger.info(f"Processing file {file}")
52+
# file_path = os.path.join(root, file)
53+
# relative_path = os.path.relpath(file_path, args.import_from)
54+
# generated_structure['structure'].append(
55+
# {
56+
# 'path': relative_path,
57+
# 'content': open(file_path, 'r').read()
58+
# }
59+
# )
60+
61+
# with open(structure_definition, 'w') as f:
62+
# self.logger.info(f"Writing structure definition to {structure_definition}")
63+
# yaml.dump(generated_structure, f)

struct_module/commands/info.py

Lines changed: 47 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,54 @@
1+
import os
2+
import yaml
3+
14
from struct_module.commands import Command
2-
import struct_module
3-
# Info command class
5+
6+
# Info command class for exposing information about the structure
47
class InfoCommand(Command):
58
def __init__(self, parser):
69
super().__init__(parser)
10+
parser.add_argument('structure_definition', type=str, help='Name of the structure definition')
11+
parser.add_argument('-s', '--structures-path', type=str, help='Path to structure definitions')
12+
713
parser.set_defaults(func=self.execute)
814

915
def execute(self, args):
10-
version = struct_module.__version__
11-
print(f"STRUCT {version}")
12-
print("")
13-
print("Generate project structure from YAML configuration.")
14-
print("Commands:")
15-
print(" generate Generate the project structure")
16-
print(" validate Validate the YAML configuration file")
17-
print(" info Show information about the package")
18-
print(" list List available structures")
16+
self.logger.info(f"Getting info for structure {args.structure_definition}")
17+
18+
self._get_info(args)
19+
20+
def _get_info(self, args):
21+
if args.structure_definition.startswith("file://") and args.structure_definition.endswith(".yaml"):
22+
with open(args.structure_definition[7:], 'r') as f:
23+
config = yaml.safe_load(f)
24+
else:
25+
if args.structures_path is None:
26+
this_file = os.path.dirname(os.path.realpath(__file__))
27+
file_path = os.path.join(this_file, "..", "contribs", f"{args.structure_definition}.yaml")
28+
else:
29+
file_path = os.path.join(args.structures_path, f"{args.structure_definition}.yaml")
30+
# show error if file is not found
31+
if not os.path.exists(file_path):
32+
self.logger.error(f"File not found: {file_path}")
33+
return
34+
with open(file_path, 'r') as f:
35+
config = yaml.safe_load(f)
36+
37+
print("📒 Structure definition\n")
38+
print(f" 📌 Name: {args.structure_definition}\n")
39+
print(f" 📌 Description: {config.get('description', 'No description')}\n")
40+
41+
if config.get('structure'):
42+
print(f" 📌 Structure:")
43+
for item in config.get('structure', []):
44+
for name, content in item.items():
45+
print(f" - {name} ")
46+
# indent all lines of content
47+
# for line in content.get('content', content.get('file', 'Not defined')).split('\n'):
48+
# print(f" {line}")
49+
50+
if config.get('folders'):
51+
print(f" 📌 Folders:")
52+
for folder in config.get('folders', []):
53+
print(f" - {folder}")
54+
# print(f" - {folder}: {folder.get('struct', 'No structure')}")

struct_module/commands/list.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,3 @@ def _list_structures(self, args):
4444

4545
print("\nUse 'struct generate' to generate the structure")
4646
print("Note: Structures with '+' sign are custom structures")
47-
48-
49-

struct_module/utils.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,4 +34,3 @@ def get_current_repo():
3434

3535

3636
project_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")
37-

0 commit comments

Comments
 (0)