-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathplain2code.py
More file actions
370 lines (306 loc) · 12.9 KB
/
Copy pathplain2code.py
File metadata and controls
370 lines (306 loc) · 12.9 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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import importlib.resources
import logging
import logging.config
import os
import signal
import sys
import threading
from pathlib import Path
from typing import Optional
import yaml
from liquid2.exceptions import TemplateNotFoundError
import codeplain_REST_api as codeplain_api
import file_utils
import plain_file
import plain_spec
from event_bus import EventBus
from module_renderer import ModuleRenderer
from plain2code_arguments import parse_arguments
from plain2code_console import console
from plain2code_events import RenderFailed
from plain2code_exceptions import (
ConflictingRequirements,
InvalidAPIKey,
InvalidFridArgument,
MissingAPIKey,
MissingPreviousFunctionalitiesError,
MissingResource,
ModuleDoesNotExistError,
NetworkConnectionError,
OutdatedClientVersion,
PlainSyntaxError,
RenderCancelledError,
RenderingCreditBalanceTooLow,
UnsupportedResourceType,
)
from plain2code_logger import (
LOGGER_NAME,
CrashLogHandler,
IndentedFormatter,
LoggingHandler,
dump_crash_logs,
get_log_file_path,
)
from plain2code_state import RunState
from plain2code_utils import format_duration_hms, print_dry_run_output
from system_config import system_config
from tui.plain2code_tui import Plain2CodeTUI
DEFAULT_TEMPLATE_DIRS = importlib.resources.files("standard_template_library")
RENDER_THREAD_SHUTDOWN_TIMEOUT = 0.7
def print_exit_summary(
run_state: RunState,
spec_filename: str,
error_message: Optional[str] = None,
) -> None:
console.quiet = False
"""Print render outcome after the TUI exits (terminal restored)."""
msg = "\n[#79FC96]✓ rendering completed\n\n" if run_state.render_succeeded else "[#FF6B6B]✗ rendering failed\n\n"
msg += f" [#8E8F91]render id:\t\t\t[#FFFFFF]{run_state.render_id}\n"
msg += f" [#8E8F91]input file:\t\t\t[#FFFFFF]{spec_filename}\n"
msg += f" [#8E8F91]generated code folder:\t[#FFFFFF]{run_state.render_generated_code_path or '-'}\n\n"
msg += f"[#8E8F91]functionalities [#FFFFFF]{run_state.rendered_functionalities} [#8E8F91]used credits [#FFFFFF]{run_state.rendered_functionalities} [#8E8F91]render time [#FFFFFF]{format_duration_hms(run_state.render_time_accumulated)}\n"
console.info(msg)
if not run_state.render_succeeded and error_message:
console.error(error_message)
console.quiet = True
def get_render_range(render_range, plain_source):
render_range = render_range.split(",")
range_end = render_range[1] if len(render_range) == 2 else render_range[0]
return _get_frids_range(plain_source, render_range[0], range_end)
def get_render_range_from(start, plain_source):
return _get_frids_range(plain_source, start)
def compute_render_range(args, plain_source_tree):
"""Compute render range from --render-range or --render-from arguments.
Args:
args: Parsed command line arguments
plain_source_tree: Parsed plain source tree
Returns:
List of FRIDs to render, or None to render all
"""
if args.render_range:
return get_render_range(args.render_range, plain_source_tree)
elif args.render_from:
return get_render_range_from(args.render_from, plain_source_tree)
return None
def _get_frids_range(plain_source, start, end=None):
frids = list(plain_spec.get_frids(plain_source))
start = str(start)
if start not in frids:
raise InvalidFridArgument(f"Invalid start functionality ID: {start}. Valid IDs are: {frids}.\n")
if end is not None:
end = str(end)
if end not in frids:
raise InvalidFridArgument(f"Invalid end functionality ID: {end}. Valid IDs are: {frids}.\n")
end_idx = frids.index(end) + 1
else:
end_idx = len(frids)
start_idx = frids.index(start)
if start_idx >= end_idx:
raise InvalidFridArgument(f"Start functionality ID: {start} must be before end functionality ID: {end}.\n")
return frids[start_idx:end_idx]
def setup_logging(
args,
event_bus: EventBus,
run_state: RunState,
log_to_file: bool,
log_file_name: str,
plain_file_path: Optional[str],
headless: bool = False,
):
# Set default level to INFO for everything not explicitly configured
logging.getLogger().setLevel(logging.INFO)
logging.getLogger(LOGGER_NAME).setLevel(logging.INFO)
logging.getLogger("git").setLevel(logging.WARNING)
logging.getLogger("transitions").setLevel(logging.ERROR)
logging.getLogger("transitions.extensions.diagrams").setLevel(logging.ERROR)
log_file_path = get_log_file_path(plain_file_path, log_file_name)
# Try to load logging configuration from YAML file
if args.logging_config_path and os.path.exists(args.logging_config_path):
try:
with open(args.logging_config_path, "r") as f:
config = yaml.safe_load(f)
logging.config.dictConfig(config)
console.info(f"Loaded logging configuration from {args.logging_config_path}")
except Exception as e:
console.warning(f"Failed to load logging configuration from {args.logging_config_path}: {str(e)}")
# The IndentedFormatter provides better multiline log readability.
# We add the LoggingHandler to the root logger.
root_logger = logging.getLogger(LOGGER_NAME)
configured_log_level = root_logger.level
root_logger.setLevel(logging.DEBUG) # Capture all logs; handlers will filter levels as needed
formatter = IndentedFormatter("%(levelname)s:%(name)s:%(message)s")
if not headless:
handler = LoggingHandler(event_bus, run_state)
handler.setFormatter(formatter)
root_logger.addHandler(handler)
if log_to_file and log_file_path:
try:
file_handler = logging.FileHandler(log_file_path, mode="w")
file_handler.setFormatter(formatter)
file_handler.setLevel(configured_log_level)
root_logger.addHandler(file_handler)
except Exception as e:
console.warning(f"Failed to setup file logging to {log_file_path}: {str(e)}")
else:
# If file logging is disabled, use CrashLogHandler to buffer logs in memory
# in case we need to dump them on crash.
crash_handler = CrashLogHandler()
crash_handler.setFormatter(formatter)
crash_handler.setLevel(configured_log_level)
root_logger.addHandler(crash_handler)
def _check_connection(codeplainAPI: codeplain_api.CodeplainAPI):
"""Check API connectivity and validate API key and client version."""
response = codeplainAPI.connection_check(system_config.client_version)
if not response.get("api_key_valid", False):
raise InvalidAPIKey(
"The provided API key is invalid. Please provide a valid API key using the CODEPLAIN_API_KEY environment variable "
"or the --api-key argument.\n"
)
if not response.get("client_version_valid", False):
min_version = response.get("min_client_version", "unknown")
raise OutdatedClientVersion(
"Outdated client version: "
f"Your client version ({system_config.client_version}) is outdated. Minimum required version is {min_version}. "
"Please update using:"
" uv tool upgrade codeplain\n"
)
def render(args, run_state: RunState, event_bus: EventBus): # noqa: C901
template_dirs = file_utils.get_template_directories(args.filename, args.template_dir, DEFAULT_TEMPLATE_DIRS)
# Compute render range from either --render-range or --render-from
render_range = None
if args.render_range or args.render_from:
# Parse the plain file to get the plain_source for FRID extraction
_, plain_source, _ = plain_file.plain_file_parser(args.filename, template_dirs)
render_range = compute_render_range(args, plain_source)
codeplainAPI = codeplain_api.CodeplainAPI(args.api_key, console)
codeplainAPI.verbose = args.verbose
assert args.api is not None and args.api != "", "API URL is required"
codeplainAPI.api_url = args.api
_check_connection(codeplainAPI)
stop_event = threading.Event()
enter_pause_event = threading.Event()
signal.signal(signal.SIGTERM, lambda _signum, _frame: stop_event.set())
module_renderer = ModuleRenderer(
codeplainAPI,
args.filename,
render_range,
template_dirs,
args,
run_state,
event_bus,
stop_event=stop_event,
enter_pause_event=enter_pause_event,
)
render_error: list[Exception] = []
def run_render():
try:
module_renderer.render_module()
except RenderCancelledError:
pass # TUI already closed, nothing to report
except Exception as e:
run_state.set_render_succeeded(False)
render_error.append(e)
event_bus.publish(RenderFailed(error_message=str(e)))
if args.headless:
console.info(f"Render started. Render ID: {run_state.render_id}")
try:
module_renderer.render_module()
except RenderCancelledError:
run_state.set_render_succeeded(False)
pass
return
else:
render_thread = threading.Thread(target=run_render, daemon=True)
app = Plain2CodeTUI(
event_bus=event_bus,
on_ready=render_thread.start,
render_id=run_state.render_id,
unittests_script=args.unittests_script,
conformance_tests_script=args.conformance_tests_script,
prepare_environment_script=args.prepare_environment_script,
state_machine_version=system_config.client_version,
enter_pause_event=enter_pause_event,
css_path="styles.css",
)
app.run()
stop_event.set()
render_thread.join(timeout=RENDER_THREAD_SHUTDOWN_TIMEOUT)
if render_error:
raise render_error[0]
def main(): # noqa: C901
args = parse_arguments()
# Handle early-exit flags before heavy initialization
if args.dry_run or args.full_plain:
template_dirs = file_utils.get_template_directories(args.filename, args.template_dir, DEFAULT_TEMPLATE_DIRS)
try:
if args.full_plain:
module_name = Path(args.filename).stem
plain_source = plain_file.read_module_plain_source(module_name, template_dirs)
[full_plain_source, _] = file_utils.get_loaded_templates(template_dirs, plain_source)
console.info("Full plain text:\n")
console.info(full_plain_source)
return
if args.dry_run:
console.info("Printing dry run output...\n")
_, plain_source_tree, _ = plain_file.plain_file_parser(args.filename, template_dirs)
render_range = compute_render_range(args, plain_source_tree)
print_dry_run_output(plain_source_tree, render_range)
return
except Exception as e:
console.error(f"Error: {str(e)}")
return
event_bus = EventBus()
if not args.api:
args.api = "https://api.codeplain.ai"
run_state = RunState(spec_filename=args.filename, replay_with=args.replay_with)
if args.headless:
# Suppress Rich console output.
console.quiet = True
setup_logging(args, event_bus, run_state, args.log_to_file, args.log_file_name, args.filename, args.headless)
exc_info = None
error_message = None
try:
# Validate API key is present
if not args.api_key:
raise MissingAPIKey(
"Your API key is required. Please set the CODEPLAIN_API_KEY environment variable or provide it with the --api-key argument.\n"
)
render(args, run_state, event_bus)
except BaseException as e:
if isinstance(e, KeyboardInterrupt):
error_message = "Keyboard interrupt"
else:
error_message = str(e) if str(e) else repr(e)
if not isinstance(
e,
(
InvalidFridArgument,
FileNotFoundError,
MissingResource,
TemplateNotFoundError,
PlainSyntaxError,
MissingPreviousFunctionalitiesError,
MissingAPIKey,
InvalidAPIKey,
OutdatedClientVersion,
ConflictingRequirements,
RenderingCreditBalanceTooLow,
NetworkConnectionError,
ModuleDoesNotExistError,
UnsupportedResourceType,
),
):
exc_info = sys.exc_info()
finally:
print_exit_summary(
run_state,
args.filename,
error_message=error_message,
)
if exc_info:
# Log traceback
dump_crash_logs(args)
if args.headless and (exc_info is not None or not run_state.render_succeeded):
sys.exit(1)
if __name__ == "__main__": # noqa: C901
main()