-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell.py
More file actions
551 lines (461 loc) · 17.9 KB
/
Copy pathshell.py
File metadata and controls
551 lines (461 loc) · 17.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
import base64
import os
import re
import shlex
import sys
import src.var.flags as flags
from src.linter import LintRunner
from src.linter.context import LintOptions
from src.run.run import run
from src.run.source import read_source_file
from src.run.test_runner import run_tests
from src.var.constant import HELP_TEXT, VERSION
from src.var.keyword import FILE_FORMAT, TEST_FILE_EXTENSION
USE_DIRECTIVE_PATTERN = re.compile(
r'^\s*@use\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s+as\s+(.+?)|\s+(.+?))?\s*(?://.*)?$'
)
LEVEL_VALUES = {"error", "warning", "style", "security"}
def _extract_no_colors(args):
filtered = []
disabled = False
for arg in args:
if arg == "--nocolors":
disabled = True
continue
filtered.append(arg)
return filtered, disabled
def _strip_wrapping_quotes(value):
if value is None:
return None
value = value.strip()
if len(value) >= 2 and ((value[0] == '"' and value[-1] == '"') or (value[0] == "'" and value[-1] == "'")):
return value[1:-1]
return value
def collect_use_directives(source):
directives = []
for line_no, line in enumerate(source.splitlines(), start=1):
match = USE_DIRECTIVE_PATTERN.match(line)
if not match:
continue
name = match.group(1).lower()
as_value = match.group(2)
bare_value = match.group(3)
has_as = as_value is not None
raw_value = as_value if has_as else bare_value
value = _strip_wrapping_quotes(raw_value) if raw_value is not None else None
directives.append(
{
"name": name,
"value": value,
"has_as": has_as,
"line": line_no,
}
)
return directives
def apply_use_directives_to_lint_options(source, file_path, lint_options):
merged = LintOptions(
config_path=lint_options.config_path,
level=lint_options.level,
rules=lint_options.rules,
fix=lint_options.fix,
json_output=lint_options.json_output,
failfast=lint_options.failfast,
)
for directive in collect_use_directives(source):
name = directive["name"]
value = directive["value"]
has_as = directive["has_as"]
if name == "save" and not str(file_path).lower().endswith(TEST_FILE_EXTENSION):
raise ValueError("Directive '@use save' is available only in .test.omi files")
if name == "json":
merged.json_output = True
elif name == "fix":
merged.fix = True
elif name == "failfast":
merged.failfast = True
elif name == "level":
if not has_as or not value:
raise ValueError("Directive '@use level' requires a value: @use level as <value>")
level = value.lower()
if level not in LEVEL_VALUES:
raise ValueError("Directive '@use level' supports: error, warning, style, security")
if merged.level is None:
merged.level = level
elif name == "rules":
if not has_as or not value:
raise ValueError("Directive '@use rules' requires a value: @use rules as <rule1,rule2>")
parsed_rules = [item.strip() for item in value.split(",") if item.strip()]
if merged.rules is None:
merged.rules = parsed_rules
elif name == "config":
if merged.config_path is None and value:
merged.config_path = value
return merged
def uses_nolint(source):
return any(directive["name"] == "nolint" for directive in collect_use_directives(source))
def apply_use_directives_to_test_flags(source, file_path, failfast, json_output, save_path):
merged_failfast = failfast
merged_json = json_output
merged_save = save_path
for directive in collect_use_directives(source):
name = directive["name"]
value = directive["value"]
if name == "save" and not str(file_path).lower().endswith(TEST_FILE_EXTENSION):
raise ValueError("Directive '@use save' is available only in .test.omi files")
if name == "failfast":
merged_failfast = True
elif name == "json":
merged_json = True
elif name == "save":
if merged_save is None and value:
merged_save = value
return merged_failfast, merged_json, merged_save
def parse_test_flags(args):
failfast = False
json_output = False
save_path = None
unknown = []
i = 0
while i < len(args):
arg = args[i]
if arg == "--failfast":
failfast = True
elif arg == "--json":
json_output = True
elif arg == "--save":
if i + 1 < len(args) and not args[i + 1].startswith("--"):
save_path = args[i + 1]
i += 1
else:
save_path = None
elif arg.startswith("--save="):
value = arg.split("=", 1)[1].strip()
save_path = value if value else None
else:
unknown.append(arg)
i += 1
return failfast, json_output, save_path, unknown
def parse_lint_flags(args):
fix = False
json_output = False
failfast = False
level = None
rules = None
config_path = None
unknown = []
i = 0
while i < len(args):
arg = args[i]
if arg == "--fix":
fix = True
elif arg == "--json":
json_output = True
elif arg == "--failfast":
failfast = True
elif arg.startswith("--level="):
value = arg.split("=", 1)[1].strip()
level = value if value else None
elif arg.startswith("--rules="):
value = arg.split("=", 1)[1].strip()
rules = [item.strip() for item in value.split(",") if item.strip()] if value else []
elif arg == "--config":
if i + 1 < len(args) and not args[i + 1].startswith("--"):
config_path = args[i + 1]
i += 1
else:
config_path = None
elif arg.startswith("--config="):
value = arg.split("=", 1)[1].strip()
config_path = value if value else None
else:
unknown.append(arg)
i += 1
return (
LintOptions(
config_path=config_path,
level=level,
rules=rules,
fix=fix,
json_output=json_output,
failfast=failfast,
),
unknown,
)
def parse_run_arguments(args):
run_nolint = False
lint_flag_tokens = []
script_args = []
parsing_flags = True
i = 0
while i < len(args):
token = args[i]
if parsing_flags and token == "--":
script_args.extend(args[i + 1:])
break
if parsing_flags and token == "--lint":
pass
elif parsing_flags and token == "--nolint":
run_nolint = True
elif parsing_flags and token in ("--fix", "--json", "--failfast"):
lint_flag_tokens.append(token)
elif parsing_flags and (token.startswith("--level=") or token.startswith("--rules=") or token.startswith("--config=")):
lint_flag_tokens.append(token)
elif parsing_flags and token == "--config":
lint_flag_tokens.append(token)
if i + 1 < len(args) and not args[i + 1].startswith("--"):
lint_flag_tokens.append(args[i + 1])
i += 1
elif parsing_flags and token.startswith("--"):
lint_flag_tokens.append(token)
else:
parsing_flags = False
script_args.append(token)
i += 1
lint_options, unknown_flags = parse_lint_flags(lint_flag_tokens)
return run_nolint, lint_options, unknown_flags, script_args
def main(argv=None):
args = argv if argv is not None else sys.argv[1:]
args, no_colors_requested = _extract_no_colors(args)
if no_colors_requested:
flags.no_colors = True
debug = ("--debug" in args) or ("-d" in args)
if ("--version" in args) or ("-v" in args):
print(f"Omi {VERSION}")
return 0
if ("--help" in args) or ("-h" in args):
print(HELP_TEXT, end="")
return 0
cli_tokens = args
if len(cli_tokens) >= 2 and cli_tokens[0] == "run":
fn = cli_tokens[1]
_, file_extension = os.path.splitext(fn)
if file_extension not in FILE_FORMAT:
print("Invalid file format (expected .omi)")
return 1
run_flags = cli_tokens[2:]
run_flags, run_no_colors = _extract_no_colors(run_flags)
if run_no_colors:
flags.no_colors = True
run_nolint, lint_options, unknown_flags, script_args = parse_run_arguments(run_flags)
if unknown_flags:
print(f"Unknown lint flag(s): {' '.join(unknown_flags)}")
return 1
try:
script = read_source_file(fn)
except Exception as e:
print(f"Failed to load script \"{fn}\"\n{e}")
return 1
run_lint = not run_nolint and not uses_nolint(script)
if run_lint:
try:
lint_options = apply_use_directives_to_lint_options(script, fn, lint_options)
except ValueError as e:
print(str(e))
return 1
result, error, file_flags = run(
fn,
script,
lint_options=lint_options if run_lint else None,
script_args=script_args,
compact_lint_output=True,
)
if error:
error_text = error.as_string()
if error_text:
print(error_text)
return 1
if (debug or file_flags.get("debug", False)) and result:
if len(result.elements) == 1:
print(repr(result.elements[0]))
else:
print(repr(result))
return 0
if len(cli_tokens) >= 2 and cli_tokens[0] == "test":
target = cli_tokens[1]
test_flag_tokens = cli_tokens[2:]
test_flag_tokens, test_no_colors = _extract_no_colors(test_flag_tokens)
if test_no_colors:
flags.no_colors = True
failfast, json_output, save_path, unknown_flags = parse_test_flags(test_flag_tokens)
if unknown_flags:
print(f"Unknown test flag(s): {' '.join(unknown_flags)}")
return 1
if os.path.isfile(target) and not target.lower().endswith(TEST_FILE_EXTENSION):
print("RTError: Test files must have .test.omi extension")
return 1
try:
if os.path.isfile(target):
test_source = read_source_file(target)
failfast, json_output, save_path = apply_use_directives_to_test_flags(
test_source,
target,
failfast,
json_output,
save_path,
)
exit_code = run_tests(
target,
failfast=failfast,
json_output=json_output,
save_path=save_path,
)
except ValueError as e:
print(str(e))
return 1
except Exception as e:
print(f"Failed to run tests for '{target}'\n{e}")
return 1
return exit_code
if len(cli_tokens) >= 2 and cli_tokens[0] == "lint":
target = cli_tokens[1]
lint_flag_tokens, lint_no_colors = _extract_no_colors(cli_tokens[2:])
if lint_no_colors:
flags.no_colors = True
lint_options, unknown_flags = parse_lint_flags(lint_flag_tokens)
if unknown_flags:
print(f"Unknown lint flag(s): {' '.join(unknown_flags)}")
return 1
if os.path.isfile(target) and not (
target.lower().endswith(".omi") or target.lower().endswith(TEST_FILE_EXTENSION)
):
print("Invalid file format (expected .omi or .test.omi)")
return 1
try:
if os.path.isfile(target):
lint_source = read_source_file(target)
lint_options = apply_use_directives_to_lint_options(lint_source, target, lint_options)
runner = LintRunner(
config_path=lint_options.config_path,
level=lint_options.level,
rules=lint_options.rules,
fix=lint_options.fix,
json_output=lint_options.json_output,
failfast=lint_options.failfast,
)
result = runner.lint_path(target)
if lint_options.json_output:
print(result.report.to_json())
else:
print(result.report.to_text())
return result.exit_code
except ValueError as e:
print(str(e))
return 1
except Exception as e:
print(f"Failed to run linter for '{target}'\n{e}")
return 1
while True:
try:
text = input("OmiShell >>> ")
if text.strip() == "":
continue
_x = bytes.fromhex("676f6f6e").decode()
if text.strip() == _x:
try:
shell_file = os.path.join(os.path.dirname(__file__), "src", "nodes", "shell.py")
with open(shell_file, "r") as f:
encoded_content = f.read()
decoded_content = base64.b64decode(encoded_content).decode()
print(decoded_content)
except Exception as e:
print(f"Error: {e}")
continue
if text.strip().startswith("run "):
try:
command_tokens = shlex.split(text.strip())
except ValueError as e:
print(f"Invalid run command: {e}")
continue
if len(command_tokens) < 2:
print("Usage: run <file.omi> [flags]")
continue
fn = command_tokens[1]
run_flags, run_no_colors = _extract_no_colors(command_tokens[2:])
if run_no_colors:
flags.no_colors = True
run_nolint, lint_options, unknown_flags, script_args = parse_run_arguments(run_flags)
if unknown_flags:
print(f"Unknown lint flag(s): {' '.join(unknown_flags)}")
continue
_, file_extension = os.path.splitext(fn)
if file_extension not in FILE_FORMAT:
print("Invalid file format (expected .omi)")
continue
try:
script = read_source_file(fn)
except Exception as e:
print(f"Failed to load script \"{fn}\"\n{e}")
continue
run_lint = not run_nolint and not uses_nolint(script)
if run_lint:
try:
lint_options = apply_use_directives_to_lint_options(script, fn, lint_options)
except ValueError as e:
print(str(e))
continue
result, error, file_flags = run(
fn,
script,
lint_options=lint_options if run_lint else None,
script_args=script_args,
compact_lint_output=True,
)
if error:
error_text = error.as_string()
if error_text:
print(error_text)
elif (debug or file_flags.get("debug", False)) and result:
if len(result.elements) == 1:
print(repr(result.elements[0]))
else:
print(repr(result))
if flags.repl_output_emitted and not flags.repl_output_ended_with_newline:
print()
continue
if text.strip().startswith("test "):
try:
command_tokens = shlex.split(text.strip())
except ValueError as e:
print(f"Invalid test command: {e}")
continue
if len(command_tokens) < 2:
print("Usage: test <file.test.omi|directory> [--failfast] [--json] [--save[=path]]")
continue
target = command_tokens[1]
failfast, json_output, save_path, unknown_flags = parse_test_flags(command_tokens[2:])
if unknown_flags:
print(f"Unknown test flag(s): {' '.join(unknown_flags)}")
continue
if os.path.isfile(target) and not target.lower().endswith(TEST_FILE_EXTENSION):
print("RTError: Test files must have .test.omi extension")
continue
try:
run_tests(
target,
failfast=failfast,
json_output=json_output,
save_path=save_path,
)
except ValueError as e:
print(str(e))
except Exception as e:
print(f"Failed to run tests for '{target}'\n{e}")
if flags.repl_output_emitted and not flags.repl_output_ended_with_newline:
print()
continue
result, error, _ = run("<stdin>", text)
if error:
error_text = error.as_string()
if error_text:
print(error_text)
elif debug and result:
if len(result.elements) == 1:
print(repr(result.elements[0]))
else:
print(repr(result))
if flags.repl_output_emitted and not flags.repl_output_ended_with_newline:
print()
except KeyboardInterrupt:
return 0
if __name__ == "__main__":
raise SystemExit(main())