-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdoscript.py
More file actions
2313 lines (2106 loc) · 104 KB
/
doscript.py
File metadata and controls
2313 lines (2106 loc) · 104 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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
DoScript v0.6.7 - Content-based file organization
Changes:
- if_file_contains "keyword" - organize files by their text content
- if_file_not_contains "keyword" - inverse content check
- read_content "file.txt" into var - read file content into variable
- contains() function in expressions - check if string contains substring
- Auto-injects {file_content} variable in for_each loops (text files)
Previous version (0.6.6):
- Fixed URL parsing bug
Previous version (0.6.4):
- replace_in_file: Find and replace text in files
- replace_regex_in_file: Regex-based find and replace
- http_get, http_post, http_put, http_delete: HTTP request commands
- random_number: Generate random integers
- random_string: Generate random alphanumeric strings
- random_choice: Pick random item from list
- system_cpu, system_memory, system_disk: System resource monitoring
Previous version (0.6.3):
- path add/remove: Windows PATH environment variable support
- Added --system flag for system-wide PATH modification
- Broadcasts WM_SETTINGCHANGE to notify Windows of PATH changes
Previous version (0.6.2):
- do_new: Execute a new DoScript instance
- Template creation: Use 'make file script.do' and write your own content
Previous version (0.6.1):
- Built-in time variables (time, today, now, year, month, day, hour, minute, second)
- JSON operations: json_read, json_write, json_get
- CSV operations: csv_read, csv_write, csv_get
- Archive operations: zip, unzip, zip_list
- Added: update checker, open_link command, Windows shutdown command
"""
import os
import sys
import re
import glob
import shutil
import subprocess
import urllib.request
import urllib.error
import ast
import operator
import time as time_module
import json
import csv
import zipfile
import webbrowser
import random
import string
from typing import Any, Dict, List, Optional, Tuple
from datetime import datetime
# Try to import psutil for system info (optional)
try:
import psutil
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
# Current interpreter version
VERSION = "0.6.7"
# ----------------------------
# Script Template
# ----------------------------
SCRIPT_TEMPLATE = '''# DoScript Automation Script
# Created: {timestamp}
# Description: Add your description here
# Declare your variables
global_variable = myVar
# Your automation code here
say "Script started!"
# Example: Process files in current directory
# for_each file_in here
# say "Found: {file_name}"
# end_for
say "Script completed!"
'''
# ----------------------------
# Exceptions with context
# ----------------------------
class DoScriptError(Exception):
def __init__(self, message: str, file: Optional[str] = None, line: Optional[int] = None, source: Optional[str] = None):
super().__init__(message)
self.message = message
self.file = file
self.line = line
self.source = source
class FileError(DoScriptError):
pass
class NetworkError(DoScriptError):
pass
class ProcessError(DoScriptError):
pass
class DataError(DoScriptError):
pass
# ----------------------------
# Update checker helper
# ----------------------------
def _to_raw_github(url: str) -> str:
"""
Convert a github.com blob URL to raw.githubusercontent.com if possible.
Example:
https://github.com/owner/repo/blob/main/version.txt
-> https://raw.githubusercontent.com/owner/repo/main/version.txt
"""
if 'github.com' in url and '/blob/' in url:
return url.replace('github.com', 'raw.githubusercontent.com').replace('/blob/', '/')
return url
def check_for_updates(interp, version_url: str, repo_url: str, timeout: int = 5):
"""
Check remote version file and if newer, prompt user to open repo_url.
Non-fatal on network errors (logs a verbose message).
"""
raw_url = _to_raw_github(version_url)
try:
req = urllib.request.Request(raw_url, headers={'User-Agent': 'DoScript-Updater/1.0'})
with urllib.request.urlopen(req, timeout=timeout) as resp:
text = resp.read().decode('utf-8', errors='ignore').strip()
# try to find a version-like token in the response
m = re.search(r'(\d+\.\d+\.\d+)', text)
if m:
remote_ver = m.group(1)
else:
# if the file is just one-line, use stripped content
remote_ver = text.splitlines()[0].strip() if text else ''
if not remote_ver:
interp.log_verbose("Update check: couldn't parse remote version.")
return
def ver_tuple(v):
return tuple(int(x) for x in v.split('.') if x.isdigit())
try:
if ver_tuple(remote_ver) > ver_tuple(VERSION):
# prompt user
prompt = f"Update available: {VERSION} -> {remote_ver}. Open repository to update? (y/N): "
ans = input(prompt).strip().lower()
if ans in ('y','yes'):
interp.log_info(f"Opening repository: {repo_url}")
try:
webbrowser.open(repo_url)
except Exception as e:
interp.log_error(f"Failed to open browser: {e}")
else:
interp.log_info("User chose not to open repository.")
else:
interp.log_verbose(f"No update: remote {remote_ver} <= local {VERSION}")
except Exception as e:
interp.log_verbose(f"Version comparison failed: {e}")
except urllib.error.URLError as e:
interp.log_verbose(f"Update check failed (network): {e}")
except Exception as e:
interp.log_verbose(f"Update check failed: {e}")
# ----------------------------
# Interpreter
# ----------------------------
class DoScriptInterpreter:
def __init__(self, dry_run: bool = False, verbose: bool = False):
# runtime
self.script_path_stack: List[str] = []
self.global_vars: Dict[str, Any] = {}
self.declared_globals: set = set()
self.functions: Dict[str, Dict[str, Any]] = {}
self.macros: Dict[str, List[str]] = {}
self.local_scope: Optional[Dict[str, Any]] = None
self.included_files: set = set()
self.loop_var_stack: List[str] = []
# flags
self.dry_run = dry_run
self.verbose = verbose
# execution context for error reporting
self.current_file: Optional[str] = None
self.current_line: Optional[int] = None
self.current_source: Optional[str] = None
# Initialize time variables (read-only)
self._init_time_variables()
# CLI args initialization (filled by CLI runner)
# populate arg1..arg32 with empty strings and mark as declared (read-only)
for i in range(1, 33):
name = f'arg{i}'
self.declared_globals.add(name)
self.global_vars[name] = ""
def _init_time_variables(self):
"""Initialize built-in time variables"""
now = datetime.now()
timestamp = int(time_module.time())
# Built-in time variables (read-only)
time_vars = {
'time': timestamp, # Unix timestamp
'today': now.strftime('%Y-%m-%d'), # 2024-02-08-like
'now': now.strftime('%H:%M:%S'), # 14:30:45-like
'year': now.year,
'month': now.month,
'day': now.day,
'hour': now.hour,
'minute': now.minute,
'second': now.second,
}
for name, value in time_vars.items():
self.declared_globals.add(name)
self.global_vars[name] = value
# ----------------------------
# Helpers: error / logging
# ----------------------------
def raise_error(self, exc_cls, message: str):
raise exc_cls(message, self.current_file, self.current_line, self.current_source)
def log_info(self, msg: str):
print(f"[INFO] {msg}")
def log_warn(self, msg: str):
print(f"[WARN] {msg}")
def log_error(self, msg: str):
print(f"[ERROR] {msg}")
def log_verbose(self, msg: str):
if self.verbose:
print(f"[VERBOSE] {msg}")
def log_dry(self, msg: str):
print(f"[DRY] {msg}")
# ----------------------------
# Path resolution
# ----------------------------
def resolve_path(self, path: str) -> str:
if os.path.isabs(path):
return path
if self.script_path_stack:
return os.path.join(self.script_path_stack[-1], path)
return path
# ----------------------------
# Interpolation
# ----------------------------
def interpolate_string(self, s: str) -> str:
s = s.replace(r'\{', '\x00').replace(r'\}', '\x01')
def repl(m):
name = m.group(1)
try:
val = self.get_variable(name)
except DoScriptError:
val = ""
return str(val) if val is not None else ""
s = re.sub(r'\{(\w+)\}', repl, s)
s = s.replace('\x00', '{').replace('\x01', '}')
return s
def interpolate_if_needed(self, s: str) -> str:
if '{' in s and '}' in s:
return self.interpolate_string(s)
return s
# ----------------------------
# Variables (argN and time vars are read-only)
# ----------------------------
def get_variable(self, name: str) -> Any:
if self.local_scope is not None and name in self.local_scope:
return self.local_scope[name]
if name in self.global_vars:
return self.global_vars[name]
self.raise_error(DoScriptError, f"Variable '{name}' is not defined")
def set_variable(self, name: str, value: Any):
# protect argN read-only
if re.match(r'^arg([1-9]|[12]\d|3[0-2])$', name):
self.raise_error(DoScriptError, f"CLI argument '{name}' is read-only")
# protect time variables (read-only)
if name in ('time', 'today', 'now', 'year', 'month', 'day', 'hour', 'minute', 'second'):
self.raise_error(DoScriptError, f"Built-in time variable '{name}' is read-only")
if self.local_scope is not None and name in self.local_scope:
self.local_scope[name] = value
return
if name in self.declared_globals:
self.global_vars[name] = value
return
self.raise_error(DoScriptError, f"Variable '{name}' used before declaration")
# ----------------------------
# Expression evaluation (safe)
# ----------------------------
def evaluate_expression(self, expr: str) -> Any:
expr = expr.strip()
if not expr:
return ""
# String literal double-quoted -> decode escapes
if (expr.startswith('"') and expr.endswith('"')) and len(expr) >= 2:
inner = expr[1:-1]
try:
return bytes(inner, "utf-8").decode("unicode_escape")
except Exception:
return inner
# Single-quoted -> interpolate
if (expr.startswith("'") and expr.endswith("'")) and len(expr) >= 2:
return self.interpolate_string(expr[1:-1])
# booleans
if expr == 'true':
return True
if expr == 'false':
return False
# numbers
try:
if '.' in expr:
return float(expr)
return int(expr)
except ValueError:
pass
# function call / builtins
m = re.match(r'^(\w+)\((.*)\)$', expr)
if m:
fname = m.group(1)
args_raw = m.group(2).strip()
args = [a.strip() for a in self._split_args(args_raw)] if args_raw else []
if fname == 'exists' and len(args) == 1:
return os.path.exists(self.resolve_path(self.evaluate_expression(args[0])))
if fname == 'extension' and len(args) == 1:
val = self.evaluate_expression(args[0])
return os.path.splitext(str(val))[1]
if fname == 'read_file' and len(args) == 1:
p = self.resolve_path(self.evaluate_expression(args[0]))
try:
with open(p, 'r', encoding='utf-8') as f:
return f.read()
except Exception as e:
self.raise_error(FileError, f"read_file failed: {e}")
if fname == 'startswith' and len(args) == 2:
return str(self.evaluate_expression(args[0])).startswith(str(self.evaluate_expression(args[1])))
if fname == 'endswith' and len(args) == 2:
return str(self.evaluate_expression(args[0])).endswith(str(self.evaluate_expression(args[1])))
if fname == 'contains' and len(args) == 2:
return str(self.evaluate_expression(args[1])).lower() in str(self.evaluate_expression(args[0])).lower()
if fname == 'contains_case' and len(args) == 2:
# case-sensitive version
return str(self.evaluate_expression(args[1])) in str(self.evaluate_expression(args[0]))
if fname == 'notcontains' and len(args) == 2:
return str(self.evaluate_expression(args[1])).lower() not in str(self.evaluate_expression(args[0])).lower()
if fname == 'split':
if len(args) == 1:
return str(self.evaluate_expression(args[0])).split()
if len(args) == 2:
return str(self.evaluate_expression(args[0])).split(str(self.evaluate_expression(args[1])))
return []
if fname in self.functions:
evaluated_args = [self.evaluate_expression(a) for a in args]
return self.call_function(fname, evaluated_args)
self.raise_error(DoScriptError, f"Unknown function '{fname}'")
# exists "path" shorthand
exists_match = re.match(r'^exists\s+"([^"]+)"$', expr)
if exists_match:
path = exists_match.group(1)
return os.path.exists(self.resolve_path(path))
# simple identifier
if re.match(r'^\w+$', expr):
return self.get_variable(expr)
# safe AST eval
try:
namespace = {'true': True, 'false': False, '__builtins__': {}}
if self.local_scope:
namespace.update(self.local_scope)
namespace.update(self.global_vars)
tree = ast.parse(expr, mode='eval')
return self._eval_node(tree.body, namespace)
except DoScriptError:
raise
except Exception as e:
self.raise_error(DoScriptError, f"Failed to evaluate '{expr}': {e}")
def _split_args(self, s: str) -> List[str]:
if not s:
return []
parts = []
cur = ''
in_double = False
in_single = False
i = 0
while i < len(s):
c = s[i]
if c == '"' and not in_single:
in_double = not in_double
cur += c
elif c == "'" and not in_double:
in_single = not in_single
cur += c
elif c == ',' and not in_double and not in_single:
parts.append(cur.strip())
cur = ''
else:
cur += c
i += 1
if cur.strip():
parts.append(cur.strip())
return parts
def _eval_node(self, node, ns):
if isinstance(node, ast.Constant):
return node.value
if isinstance(node, ast.Name):
if node.id in ns:
return ns[node.id]
self.raise_error(DoScriptError, f"Unknown name '{node.id}'")
if isinstance(node, ast.BinOp):
left = self._eval_node(node.left, ns)
right = self._eval_node(node.right, ns)
ops = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, ast.Mod: operator.mod}
if type(node.op) in ops:
return ops[type(node.op)](left, right)
if isinstance(node, ast.UnaryOp):
val = self._eval_node(node.operand, ns)
if isinstance(node.op, ast.USub):
return -val
if isinstance(node.op, ast.Not):
return not val
if isinstance(node, ast.Compare):
left = self._eval_node(node.left, ns)
for op, comp in zip(node.ops, node.comparators):
right = self._eval_node(comp, ns)
if isinstance(op, ast.Eq):
if not (left == right): return False
elif isinstance(op, ast.NotEq):
if not (left != right): return False
elif isinstance(op, ast.Lt):
if not (left < right): return False
elif isinstance(op, ast.Gt):
if not (left > right): return False
elif isinstance(op, ast.LtE):
if not (left <= right): return False
elif isinstance(op, ast.GtE):
if not (left >= right): return False
left = right
return True
if isinstance(node, ast.BoolOp):
if isinstance(node.op, ast.And):
for v in node.values:
if not self._eval_node(v, ns): return False
return True
if isinstance(node.op, ast.Or):
for v in node.values:
if self._eval_node(v, ns): return True
return False
self.raise_error(DoScriptError, f"Unsupported AST node {type(node).__name__}")
# ----------------------------
# Function call
# ----------------------------
def call_function(self, name: str, args: List[Any]) -> Any:
if name not in self.functions:
self.raise_error(DoScriptError, f"Function '{name}' not defined")
f = self.functions[name]
params = f['params']
body = f['body']
prev_local = self.local_scope
self.local_scope = {}
for i, p in enumerate(params):
self.local_scope[p] = args[i] if i < len(args) else None
ret = None
try:
for s in body:
r = self._exec_statement(s)
if r is not None and r[0] == 'return':
ret = r[1]
break
if r is not None and r[0] in ('break','continue'):
self.raise_error(DoScriptError, f"'{r[0]}' not valid inside function")
finally:
self.local_scope = prev_local
return ret
# ----------------------------
# Parsing
# ----------------------------
def parse_script(self, filename: str) -> List[str]:
try:
with open(filename, 'r', encoding='utf-8') as f:
raw = f.readlines()
except Exception as e:
self.raise_error(FileError, f"Failed to open script '{filename}': {e}")
out: List[str] = []
cur = ""
for line in raw:
# remove comments (quote-aware - don't remove # or // inside strings)
line = self._remove_comments(line)
line = line.rstrip('\n\r')
t = line.strip()
if t:
cur += (" " + t) if cur else t
out.append(cur)
cur = ""
return out
def _remove_comments(self, line: str) -> str:
"""Remove comments but preserve # and // inside quoted strings"""
result = []
in_double_quote = False
in_single_quote = False
i = 0
while i < len(line):
char = line[i]
# Track quote state
if char == '"' and not in_single_quote and (i == 0 or line[i-1] != '\\'):
in_double_quote = not in_double_quote
result.append(char)
elif char == "'" and not in_double_quote and (i == 0 or line[i-1] != '\\'):
in_single_quote = not in_single_quote
result.append(char)
# Check for comments outside quotes
elif not in_double_quote and not in_single_quote:
if char == '#':
# Rest of line is comment
break
elif char == '/' and i + 1 < len(line) and line[i + 1] == '/':
# Rest of line is comment
break
else:
result.append(char)
else:
# Inside quotes, keep everything
result.append(char)
i += 1
return ''.join(result)
def extract_string(self, s: str) -> str:
s = s.strip()
if s.startswith('"') and s.endswith('"'):
inner = s[1:-1]
# Process escape sequences manually (in correct order) to avoid unicode_escape deprecation
# First, handle escaped backslashes
result = inner.replace('\\\\', '\x00') # Temporary placeholder
result = result.replace('\\n', '\n')
result = result.replace('\\t', '\t')
result = result.replace('\\r', '\r')
result = result.replace('\\"', '"')
result = result.replace('\x00', '\\') # Restore escaped backslashes
return result
if s.startswith("'") and s.endswith("'"):
return self.interpolate_string(s[1:-1])
return s
# ----------------------------
# Block extraction
# ----------------------------
def execute_block(self, lines: List[str], start_idx: int, end_keyword: str) -> Tuple[int, List[str]]:
block: List[str] = []
i = start_idx
depth = 1
start_keywords = {
'end_function': 'function',
'end_loop': 'loop',
'end_repeat': 'repeat',
'end_if': 'if',
'end_try': 'try',
'end_command': 'make a_command',
'end_for': 'for_each',
}
start_keyword = start_keywords.get(end_keyword, '')
while i < len(lines):
line = lines[i].strip()
if start_keyword and line.startswith(start_keyword):
depth += 1
elif line == end_keyword or line.startswith(end_keyword + ' '):
depth -= 1
if depth == 0:
return i, block
block.append(lines[i])
i += 1
self.raise_error(DoScriptError, f"Missing {end_keyword}")
# ----------------------------
# Execute single statement
# ----------------------------
def _exec_statement(self, stmt: str) -> Optional[Tuple[str, Any]]:
stmt = stmt.strip()
if not stmt:
return None
# logging commands
if stmt.startswith('log '):
msg = self.evaluate_expression(stmt[4:].strip())
self.log_info(str(msg))
return None
if stmt.startswith('warn '):
msg = self.evaluate_expression(stmt[5:].strip())
self.log_warn(str(msg))
return None
if stmt.startswith('error '):
msg = self.evaluate_expression(stmt[6:].strip())
self.log_error(str(msg))
return None
# JSON operations
if stmt.startswith('json_read '):
m = re.match(r'json_read\s+"([^"]+)"\s+to\s+(\w+)$', stmt)
if m:
filepath, varname = m.groups()
resolved = self.resolve_path(filepath)
try:
with open(resolved, 'r', encoding='utf-8') as f:
data = json.load(f)
# Ensure variable is declared
if varname not in self.declared_globals:
self.declared_globals.add(varname)
self.global_vars[varname] = None
self.set_variable(varname, data)
self.log_verbose(f"Loaded JSON from {resolved}")
except Exception as e:
self.raise_error(DataError, f"Failed to read JSON from '{filepath}': {e}")
return None
if stmt.startswith('json_write '):
m = re.match(r'json_write\s+(\w+)\s+to\s+"([^"]+)"$', stmt)
if m:
varname, filepath = m.groups()
resolved = self.resolve_path(filepath)
data = self.get_variable(varname)
if self.dry_run:
self.log_dry(f"json_write {varname} -> {resolved}")
else:
try:
os.makedirs(os.path.dirname(resolved) or '.', exist_ok=True)
with open(resolved, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
self.log_info(f"Wrote JSON to {resolved}")
except Exception as e:
self.raise_error(DataError, f"Failed to write JSON to '{filepath}': {e}")
return None
if stmt.startswith('json_get '):
m = re.match(r'json_get\s+(\w+)\s+"([^"]+)"\s+to\s+(\w+)$', stmt)
if m:
source_var, key, dest_var = m.groups()
data = self.get_variable(source_var)
try:
# Support dot notation for nested keys
keys = key.split('.')
value = data
for k in keys:
if isinstance(value, dict):
value = value[k]
elif isinstance(value, list):
value = value[int(k)]
else:
self.raise_error(DataError, f"Cannot access key '{k}' in non-dict/list")
if dest_var not in self.declared_globals:
self.declared_globals.add(dest_var)
self.global_vars[dest_var] = None
self.set_variable(dest_var, value)
except (KeyError, IndexError, ValueError) as e:
self.raise_error(DataError, f"Key '{key}' not found in {source_var}: {e}")
return None
# CSV operations
if stmt.startswith('csv_read '):
m = re.match(r'csv_read\s+"([^"]+)"\s+to\s+(\w+)$', stmt)
if m:
filepath, varname = m.groups()
resolved = self.resolve_path(filepath)
try:
with open(resolved, 'r', encoding='utf-8', newline='') as f:
reader = csv.DictReader(f)
data = list(reader)
if varname not in self.declared_globals:
self.declared_globals.add(varname)
self.global_vars[varname] = None
self.set_variable(varname, data)
self.log_verbose(f"Loaded CSV from {resolved} ({len(data)} rows)")
except Exception as e:
self.raise_error(DataError, f"Failed to read CSV from '{filepath}': {e}")
return None
if stmt.startswith('csv_write '):
m = re.match(r'csv_write\s+(\w+)\s+to\s+"([^"]+)"$', stmt)
if m:
varname, filepath = m.groups()
resolved = self.resolve_path(filepath)
data = self.get_variable(varname)
if self.dry_run:
self.log_dry(f"csv_write {varname} -> {resolved}")
else:
try:
if not isinstance(data, list) or not data:
self.raise_error(DataError, "CSV data must be a non-empty list of dictionaries")
os.makedirs(os.path.dirname(resolved) or '.', exist_ok=True)
with open(resolved, 'w', encoding='utf-8', newline='') as f:
fieldnames = data[0].keys()
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
self.log_info(f"Wrote CSV to {resolved} ({len(data)} rows)")
except Exception as e:
self.raise_error(DataError, f"Failed to write CSV to '{filepath}': {e}")
return None
if stmt.startswith('csv_get '):
m = re.match(r'csv_get\s+(\w+)\s+row\s+(\d+)\s+"([^"]+)"\s+to\s+(\w+)$', stmt)
if m:
source_var, row_str, column, dest_var = m.groups()
data = self.get_variable(source_var)
try:
row_idx = int(row_str)
if not isinstance(data, list) or row_idx >= len(data):
self.raise_error(DataError, f"Row {row_idx} out of range")
value = data[row_idx].get(column)
if dest_var not in self.declared_globals:
self.declared_globals.add(dest_var)
self.global_vars[dest_var] = None
self.set_variable(dest_var, value)
except (KeyError, ValueError) as e:
self.raise_error(DataError, f"Failed to get CSV value: {e}")
return None
# ZIP operations
if stmt.startswith('zip ') and ' to ' in stmt:
m = re.match(r'zip\s+"([^"]+)"\s+to\s+"([^"]+)"$', stmt)
if m:
source, zipfile_path = m.groups()
source_resolved = self.resolve_path(source)
zip_resolved = self.resolve_path(zipfile_path)
if self.dry_run:
self.log_dry(f"zip {source_resolved} -> {zip_resolved}")
else:
try:
os.makedirs(os.path.dirname(zip_resolved) or '.', exist_ok=True)
with zipfile.ZipFile(zip_resolved, 'w', zipfile.ZIP_DEFLATED) as zf:
if os.path.isfile(source_resolved):
zf.write(source_resolved, os.path.basename(source_resolved))
elif os.path.isdir(source_resolved):
for root, dirs, files in os.walk(source_resolved):
for file in files:
file_path = os.path.join(root, file)
arcname = os.path.relpath(file_path, os.path.dirname(source_resolved))
zf.write(file_path, arcname)
self.log_info(f"Created archive {zip_resolved}")
except Exception as e:
self.raise_error(FileError, f"Failed to create zip '{zipfile_path}': {e}")
return None
if stmt.startswith('unzip '):
m = re.match(r'unzip\s+"([^"]+)"(?:\s+to\s+"([^"]+)")?$', stmt)
if m:
zipfile_path = m.group(1)
dest = m.group(2) if m.group(2) else '.'
zip_resolved = self.resolve_path(zipfile_path)
dest_resolved = self.resolve_path(dest)
if self.dry_run:
self.log_dry(f"unzip {zip_resolved} -> {dest_resolved}")
else:
try:
os.makedirs(dest_resolved, exist_ok=True)
with zipfile.ZipFile(zip_resolved, 'r') as zf:
zf.extractall(dest_resolved)
self.log_info(f"Extracted {zip_resolved} to {dest_resolved}")
except Exception as e:
self.raise_error(FileError, f"Failed to unzip '{zipfile_path}': {e}")
return None
if stmt.startswith('zip_list '):
m = re.match(r'zip_list\s+"([^"]+)"\s+to\s+(\w+)$', stmt)
if m:
zipfile_path, varname = m.groups()
zip_resolved = self.resolve_path(zipfile_path)
try:
with zipfile.ZipFile(zip_resolved, 'r') as zf:
files = zf.namelist()
if varname not in self.declared_globals:
self.declared_globals.add(varname)
self.global_vars[varname] = None
self.set_variable(varname, files)
self.log_verbose(f"Listed {len(files)} files from {zip_resolved}")
except Exception as e:
self.raise_error(FileError, f"Failed to list zip '{zipfile_path}': {e}")
return None
# script_path
if stmt.startswith('script_path add '):
path = self.extract_string(stmt[16:])
self.script_path_stack.append(os.path.abspath(path))
self.log_verbose(f"script_path added {path}")
return None
if stmt.startswith('script_path remove '):
path = self.extract_string(stmt[19:])
rp = os.path.abspath(path)
if rp in self.script_path_stack:
self.script_path_stack.remove(rp)
return None
if stmt == 'script_path list':
for p in self.script_path_stack:
print(p)
return None
# path (system PATH) - installer-style (must respect dry-run)
if stmt.startswith('path add '):
rest = stmt[9:].strip()
# Check for --system flag
use_system = False
if rest.startswith('--system '):
use_system = True
rest = rest[9:].strip()
p = self.extract_string(rest)
resolved = os.path.abspath(self.resolve_path(p))
if self.dry_run:
scope = "SYSTEM" if use_system else "USER"
self.log_dry(f"path add [{scope}] {resolved}")
else:
if sys.platform == 'win32':
try:
import winreg
# Choose registry key based on scope
if use_system:
key_path = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
root_key = winreg.HKEY_LOCAL_MACHINE
scope_name = "SYSTEM"
else:
key_path = r'Environment'
root_key = winreg.HKEY_CURRENT_USER
scope_name = "USER"
# Open registry key
key = winreg.OpenKey(root_key, key_path, 0, winreg.KEY_READ | winreg.KEY_WRITE)
try:
# Read current PATH
current_path, _ = winreg.QueryValueEx(key, 'Path')
except FileNotFoundError:
current_path = ''
# Split into components
paths = [p.strip() for p in current_path.split(';') if p.strip()]
# Add new path if not already present
if resolved not in paths:
paths.append(resolved)
new_path = ';'.join(paths)
# Write back to registry
winreg.SetValueEx(key, 'Path', 0, winreg.REG_EXPAND_SZ, new_path)
winreg.CloseKey(key)
# Broadcast environment change
try:
import ctypes
HWND_BROADCAST = 0xFFFF
WM_SETTINGCHANGE = 0x001A
SMTO_ABORTIFHUNG = 0x0002
result = ctypes.c_long()
SendMessageTimeoutW = ctypes.windll.user32.SendMessageTimeoutW
SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0, 'Environment', SMTO_ABORTIFHUNG, 5000, ctypes.byref(result))
except:
pass # Broadcasting is optional
self.log_info(f"Added to {scope_name} PATH: {resolved}")
else:
self.log_info(f"Path already in {scope_name} PATH: {resolved}")
winreg.CloseKey(key)
except PermissionError:
self.raise_error(ProcessError, f"Permission denied. {'Administrator' if use_system else 'User'} rights required to modify PATH.")
except Exception as e:
self.raise_error(ProcessError, f"Failed to add to PATH: {e}")
else:
# Unix-like systems
self.log_info("path add on Unix requires manual shell profile edit (~/.bashrc, ~/.zshrc, etc.)")
self.log_info(f"Add this line: export PATH=\"$PATH:{resolved}\"")
return None
if stmt.startswith('path remove '):
rest = stmt[12:].strip()
# Check for --system flag
use_system = False
if rest.startswith('--system '):
use_system = True
rest = rest[9:].strip()
p = self.extract_string(rest)
resolved = os.path.abspath(self.resolve_path(p))
if self.dry_run:
scope = "SYSTEM" if use_system else "USER"
self.log_dry(f"path remove [{scope}] {resolved}")
else:
if sys.platform == 'win32':
try:
import winreg
# Choose registry key based on scope
if use_system:
key_path = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
root_key = winreg.HKEY_LOCAL_MACHINE
scope_name = "SYSTEM"
else:
key_path = r'Environment'
root_key = winreg.HKEY_CURRENT_USER
scope_name = "USER"
# Open registry key
key = winreg.OpenKey(root_key, key_path, 0, winreg.KEY_READ | winreg.KEY_WRITE)
try:
# Read current PATH
current_path, _ = winreg.QueryValueEx(key, 'Path')
except FileNotFoundError:
current_path = ''
# Split into components
paths = [p.strip() for p in current_path.split(';') if p.strip()]
# Remove the path if present
if resolved in paths:
paths.remove(resolved)
new_path = ';'.join(paths)
# Write back to registry
winreg.SetValueEx(key, 'Path', 0, winreg.REG_EXPAND_SZ, new_path)
winreg.CloseKey(key)
# Broadcast environment change
try:
import ctypes
HWND_BROADCAST = 0xFFFF
WM_SETTINGCHANGE = 0x001A
SMTO_ABORTIFHUNG = 0x0002
result = ctypes.c_long()
SendMessageTimeoutW = ctypes.windll.user32.SendMessageTimeoutW
SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0, 'Environment', SMTO_ABORTIFHUNG, 5000, ctypes.byref(result))
except:
pass # Broadcasting is optional
self.log_info(f"Removed from {scope_name} PATH: {resolved}")
else:
self.log_info(f"Path not found in {scope_name} PATH: {resolved}")
winreg.CloseKey(key)
except PermissionError:
self.raise_error(ProcessError, f"Permission denied. {'Administrator' if use_system else 'User'} rights required to modify PATH.")
except Exception as e:
self.raise_error(ProcessError, f"Failed to remove from PATH: {e}")
else:
# Unix-like systems
self.log_info("path remove on Unix requires manual shell profile edit (~/.bashrc, ~/.zshrc, etc.)")
self.log_info(f"Remove this from PATH: {resolved}")
return None
# include
if stmt.startswith('include '):
file_expr = stmt[8:].strip()
file_path = self.extract_string(file_expr)
resolved = os.path.abspath(self.resolve_path(file_path))
if resolved in self.included_files:
return None
if not os.path.exists(resolved):
self.raise_error(FileError, f"Included file not found: {file_path}")
self.included_files.add(resolved)
lines = self.parse_script(resolved)
# execute included file with context