-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
250 lines (189 loc) · 7.51 KB
/
cli.py
File metadata and controls
250 lines (189 loc) · 7.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
#!/usr/bin/env python3
"""Merisio CLI — validate, generate SQL, view MLD, export diagrams, and parse MSD files."""
import argparse
import os
import sys
def load_project(file_path):
"""Load a .merisio project file, exiting on failure."""
from src.utils.file_io import FileIO
if not os.path.isfile(file_path):
print(f"Error: file not found: {file_path}", file=sys.stderr)
sys.exit(2)
project = FileIO.load_project(file_path)
if project is None:
print(f"Error: failed to load project: {file_path}", file=sys.stderr)
sys.exit(2)
return project
def cmd_info(args):
"""Show project metadata and statistics."""
from src.controllers.mcd_controller import MCDController
project = load_project(args.file)
controller = MCDController(project)
stats = controller.get_statistics()
print(f"Project: {project.name}")
print(f"Author: {project.author or '(none)'}")
print(f"Description: {project.description or '(none)'}")
print(f"Created: {project.created_at}")
print(f"Modified: {project.modified_at}")
print(f"Entities: {stats['entities']}")
print(f"Associations: {stats['associations']}")
print(f"Links: {stats['links']}")
print(f"Attributes: {stats['attributes']}")
def cmd_validate(args):
"""Validate the MCD model."""
from src.controllers.mcd_controller import MCDController
project = load_project(args.file)
controller = MCDController(project)
errors = controller.validate()
if errors:
print(f"Validation failed with {len(errors)} error(s):")
for err in errors:
print(f" - {err}")
sys.exit(1)
else:
print("Validation passed. No errors found.")
def cmd_sql(args):
"""Generate PostgreSQL DDL."""
from src.controllers.sql_generator import SQLGenerator
project = load_project(args.file)
generator = SQLGenerator(project)
sql = generator.generate()
if args.output:
try:
with open(args.output, "w", encoding="utf-8") as f:
f.write(sql)
print(f"SQL written to {args.output}")
except OSError as e:
print(f"Error writing file: {e}", file=sys.stderr)
sys.exit(2)
else:
print(sql)
def cmd_mld(args):
"""Show the logical data model (MLD tables)."""
from src.controllers.mld_transformer import MLDTransformer
project = load_project(args.file)
transformer = MLDTransformer(project)
tables = transformer.transform()
if not tables:
print("No tables generated.")
return
for table in tables:
pk_cols = [c.name for c in table.columns if c.is_primary_key]
fk_cols = [c for c in table.columns if c.is_foreign_key]
print(f"{table.name} ({table.source_type})")
for col in table.columns:
flags = []
if col.is_primary_key:
flags.append("PK")
if col.is_foreign_key:
flags.append(f"FK -> {col.references_table}.{col.references_column}")
if not col.is_nullable:
flags.append("NOT NULL")
flag_str = f" [{', '.join(flags)}]" if flags else ""
print(f" {col.name} {col.data_type}{flag_str}")
print()
def cmd_parse(args):
"""Parse an MSD file and convert to .merisio project."""
from src.msd import MSDParser, MSDProjectBuilder
from src.utils.file_io import FileIO
file_path = args.file
if not os.path.isfile(file_path):
print(f"Error: file not found: {file_path}", file=sys.stderr)
sys.exit(2)
try:
with open(file_path, "r", encoding="utf-8") as f:
source = f.read()
except OSError as e:
print(f"Error reading file: {e}", file=sys.stderr)
sys.exit(2)
parser = MSDParser()
parse_result = parser.parse(source, filename=file_path)
builder = MSDProjectBuilder()
project, errors = builder.build(parse_result)
# Print warnings and errors
has_fatal = False
for err in errors:
print(str(err), file=sys.stderr)
if err.severity == "error":
has_fatal = True
if has_fatal:
print(f"Parse failed with errors.", file=sys.stderr)
sys.exit(1)
# Determine output path
output = args.output
if not output:
base, _ = os.path.splitext(file_path)
output = base + ".merisio"
if FileIO.save_project(project, output):
print(f"Saved project to {output}")
else:
print(f"Error: failed to save project to {output}", file=sys.stderr)
sys.exit(2)
def cmd_export(args):
"""Export diagram to PNG, SVG, or PDF."""
# QGraphicsScene requires QApplication (not QGuiApplication)
from PySide6.QtWidgets import QApplication
app = QApplication.instance()
if app is None:
app = QApplication(sys.argv)
from src.export.renderer import HeadlessRenderer
project = load_project(args.file)
if not args.output:
print("Error: export requires -o / --output", file=sys.stderr)
sys.exit(2)
renderer = HeadlessRenderer(project)
fmt = args.format.lower()
if fmt == "png":
ok = renderer.export_png(args.output, scale=args.scale)
elif fmt == "svg":
ok = renderer.export_svg(args.output)
elif fmt == "pdf":
ok = renderer.export_pdf(args.output)
else:
print(f"Error: unsupported format: {args.format}", file=sys.stderr)
sys.exit(2)
if ok:
print(f"Exported {fmt.upper()} to {args.output}")
else:
print(f"Error: export failed (empty diagram or write error)", file=sys.stderr)
sys.exit(2)
def main():
from src.utils.constants import APP_VERSION
parser = argparse.ArgumentParser(
prog="merisio-cli",
description="Merisio CLI — work with .merisio and .msd project files from the command line.",
)
parser.add_argument("--version", action="version", version=f"merisio-cli {APP_VERSION}")
parser.add_argument("file", help="Path to a .merisio or .msd project file")
subparsers = parser.add_subparsers(dest="command", required=True)
# info
subparsers.add_parser("info", help="Show project metadata and statistics")
# validate
subparsers.add_parser("validate", help="Validate the MCD model")
# sql
sql_parser = subparsers.add_parser("sql", help="Generate PostgreSQL DDL")
sql_parser.add_argument("-o", "--output", help="Write SQL to file instead of stdout")
# mld
subparsers.add_parser("mld", help="Show the logical data model (MLD tables)")
# parse
parse_parser = subparsers.add_parser("parse", help="Parse an MSD file and convert to .merisio")
parse_parser.add_argument("-o", "--output", help="Output .merisio file (default: same name with .merisio extension)")
# export
export_parser = subparsers.add_parser("export", help="Export diagram to PNG, SVG, or PDF")
export_parser.add_argument("--format", required=True, choices=["png", "svg", "pdf"],
help="Export format")
export_parser.add_argument("-o", "--output", required=True, help="Output file path")
export_parser.add_argument("--scale", type=float, default=2.0,
help="Scale factor for PNG export (default: 2.0)")
args = parser.parse_args()
commands = {
"info": cmd_info,
"validate": cmd_validate,
"sql": cmd_sql,
"mld": cmd_mld,
"parse": cmd_parse,
"export": cmd_export,
}
commands[args.command](args)
if __name__ == "__main__":
main()