-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMiSAR.py
More file actions
3430 lines (2732 loc) · 120 KB
/
Copy pathMiSAR.py
File metadata and controls
3430 lines (2732 loc) · 120 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
import argparse
import hashlib
import json
import logging
import shutil
import stat
import subprocess
import sys
import tkinter
import webbrowser
from logging.handlers import RotatingFileHandler
from pathlib import Path
from tkinter import filedialog, messagebox
from urllib.request import Request, urlopen
import os
from datetime import datetime
import threading
from importlib.metadata import PackageNotFoundError, version as package_version
# ===============================
# ENVIRONMENT VARIABLES
# ===============================
USER_HOME_DIR = Path.home()
AIO_DIR = Path(__file__).resolve().parent
MISAR_DIR = USER_HOME_DIR / "MiSAR"
INSTALLED_PARSER_DIR = MISAR_DIR / "Parser"
REPOSITORY_PARSER_DIR = AIO_DIR
ACTIVE_PARSER_DIR = INSTALLED_PARSER_DIR
PARSER_PSM_ECORE = ACTIVE_PARSER_DIR / "TransformationEngineNecessities" / "source" / "PSM.ecore"
PARSER_GUI_PATH = ACTIVE_PARSER_DIR / "ParserNecessities" / "MisarParserGUI.py"
PARSER_METADATA_PATH = ACTIVE_PARSER_DIR / "MiSAR.parser.release.json"
PARSER_REPOSITORY_API_URL = "https://api.github.com/repos/MicroServiceArchitectureRecovery/MiSAR-Parser-and-Model-Transformation"
PARSER_REPOSITORY_CLONE_URL = "https://github.com/MicroServiceArchitectureRecovery/MiSAR-Parser-and-Model-Transformation.git"
GMG_RELEASE_API_URL = "https://api.github.com/repos/MicroServiceArchitectureRecovery/misar-plantUML/releases/latest"
GMG_ASSET_NAME = "MiSAR.jar"
GMG_JAR_DIR = USER_HOME_DIR / "MISAR" / "GMG"
GMG_JAR_PATH = GMG_JAR_DIR / GMG_ASSET_NAME
GMG_METADATA_PATH = GMG_JAR_DIR / "MiSAR.release.json"
GMG_VERSION_KEY = "misar.visualiser"
MISAR_DOCUMENTATION_URL = "https://microservicearchitecturerecovery.github.io/MiSAR-Parser-and-Model-Transformation/"
LOG_DIR = AIO_DIR / "logs"
LOG_FILE_PATH = LOG_DIR / f"MiSAR-LOGGER-{datetime.now().strftime('%Y%m%d-%H%M%S')}.log"
LOCAL_RUNTIME_CONFIG_KEY = "runtime.use_repository_parser"
REQUIRED_MODULES = [
("git", "GitPython"),
("pyecore", "pyecore"),
("yaml", "PyYAML"),
("xmltodict", "xmltodict"),
("javalang", "javalang"),
("screeninfo", "ScreenInfo"),
]
VERSION_FILE_PATH = AIO_DIR / "MISAR.versions.json"
CONFIG_FILE_PATH = AIO_DIR / "MISAR.configs.json"
IMAGE_DIR = AIO_DIR / "img"
MISAR_LOGO_PATH = IMAGE_DIR / "MainLogo.png"
BRUNEL_LOGO_PATH = IMAGE_DIR / "brunel_Logo.png"
AUTO_UPDATE_CONFIG_KEY = "updates.auto_check"
MODULE_VERSION_KEYS = {
"MiSAR Parser": ("misar.parser",),
"MiSAR Transformation Engine": ("misar.transofrmer", "misar.transformer"),
"MiSAR Graphical Model Generator": ("misar.visualiser",),
}
LAUNCHER_VERSION_KEYS = ("misar.launcher",)
MISAR_VERSIONS = {}
MISAR_CONFIGS = {}
LOGGER = logging.getLogger("MiSAR-AIO")
LOGGER.propagate = False
main_window = None
the_parser = None
the_transformation_engine = None
the_graphical_model_generator = None
the_help_button = None
# ===============================
# HELPER FUNCTIONS
# ===============================
def config_value_as_bool(value, default=False):
"""Convert config values from JSON/string form into a boolean."""
if isinstance(value, bool):
return value
if value is None:
return default
text_value = str(value).strip().lower()
if text_value in {"1", "true", "yes", "y", "on", "enabled"}:
return True
if text_value in {"0", "false", "no", "n", "off", "disabled"}:
return False
return default
def read_bootstrap_configs():
"""Read minimal startup config before the logger/UI helpers are available."""
if not CONFIG_FILE_PATH.is_file():
return {}
try:
with open(CONFIG_FILE_PATH, "r", encoding="utf-8") as json_file:
data = json.load(json_file)
return data if isinstance(data, dict) else {}
except Exception:
return {}
def resolve_use_repository_parser(cli_enabled=False, configs=None):
"""Return True when the repository parser runtime should be used."""
if cli_enabled:
return True
configs = configs or {}
return config_value_as_bool(configs.get(LOCAL_RUNTIME_CONFIG_KEY), False)
def parse_arguments():
"""Parse MiSAR AIO command-line arguments without interrupting Tkinter."""
parser = argparse.ArgumentParser(description="MiSAR All-in-One launcher")
parser.add_argument(
"--debug",
action="store_true",
help="Enable debug logging to logs/MiSAR-AIO.log and the terminal.",
)
parser.add_argument(
"--psm-path",
"--misar-psm-path",
default=None,
help="Optional PSM Ecore file to pass to the MiSAR Parser when debug mode is enabled.",
)
parser.add_argument(
"--use-repository-parser",
action="store_true",
help="Use parser and transformation files from this repository instead of the installed stable runtime.",
)
return parser.parse_known_args()[0]
ARGS = parse_arguments()
BOOTSTRAP_CONFIGS = read_bootstrap_configs()
DEBUG_MODE = ARGS.debug
USE_REPOSITORY_PARSER = resolve_use_repository_parser(
bool(getattr(ARGS, "use_repository_parser", False)),
BOOTSTRAP_CONFIGS,
)
PARSER_SELECTED_PSM_PATH = Path(ARGS.psm_path).expanduser() if getattr(ARGS, "psm_path", None) else None
def configure_parser_runtime_paths():
"""Point parser paths at either the installed runtime or this repository checkout."""
global ACTIVE_PARSER_DIR, PARSER_PSM_ECORE, PARSER_GUI_PATH, PARSER_METADATA_PATH
ACTIVE_PARSER_DIR = REPOSITORY_PARSER_DIR if USE_REPOSITORY_PARSER else INSTALLED_PARSER_DIR
PARSER_PSM_ECORE = ACTIVE_PARSER_DIR / "TransformationEngineNecessities" / "source" / "PSM.ecore"
PARSER_GUI_PATH = ACTIVE_PARSER_DIR / "ParserNecessities" / "MisarParserGUI.py"
PARSER_METADATA_PATH = ACTIVE_PARSER_DIR / "MiSAR.parser.release.json"
configure_parser_runtime_paths()
def setup_logger():
"""Configure the optional debug logger, leaving logging disabled by default."""
LOGGER.handlers.clear()
if not DEBUG_MODE:
LOGGER.addHandler(logging.NullHandler())
return
LOG_DIR.mkdir(parents=True, exist_ok=True)
LOGGER.setLevel(logging.DEBUG)
formatter = logging.Formatter(
"%(asctime)s | %(levelname)s | %(name)s | %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
file_handler = RotatingFileHandler(
LOG_FILE_PATH,
maxBytes=2 * 1024 * 1024,
backupCount=5,
encoding="utf-8",
)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
console_handler.setFormatter(formatter)
LOGGER.addHandler(file_handler)
LOGGER.addHandler(console_handler)
LOGGER.debug("Logger enabled")
def serialise_log_value(value):
"""Convert log values into JSON-safe data for structured debug events."""
if isinstance(value, Path):
return str(value)
if isinstance(value, Exception):
return str(value)
try:
json.dumps(value)
return value
except TypeError:
return str(value)
def log_event(event, **details):
"""Write a structured debug event when --debug is enabled."""
if not DEBUG_MODE:
return
payload = {key: serialise_log_value(value) for key, value in details.items()}
LOGGER.debug("%s | %s", event, json.dumps(payload, ensure_ascii=False, sort_keys=True))
def log_exception(event, error, **details):
"""Write a structured debug event with exception traceback when --debug is enabled."""
if not DEBUG_MODE:
return
payload = {key: serialise_log_value(value) for key, value in details.items()}
payload["error"] = str(error)
LOGGER.exception("%s | %s", event, json.dumps(payload, ensure_ascii=False, sort_keys=True))
def check_internet():
"""Return True when a short internet connectivity check succeeds."""
log_event("internet_check_started")
try:
request = Request("https://google.com/", headers={"User-Agent": "MiSAR-AIO"})
urlopen(request, timeout=3)
log_event("internet_check_success")
return True
except Exception as error:
log_event("internet_check_failed", error=str(error))
return False
def plural_check(errors):
"""Return a grammatically correct module phrase for user-facing dependency errors."""
return "this required module." if len(errors) == 1 else "these required modules."
def get_json_from_url(url):
"""Fetch and parse JSON from a GitHub API endpoint."""
log_event("github_api_request_started", url=url)
request = Request(
url,
headers={
"Accept": "application/vnd.github+json",
"User-Agent": "MiSAR-AIO",
},
)
with urlopen(request, timeout=20) as response:
payload = json.loads(response.read().decode("utf-8"))
log_event("github_api_request_success", url=url)
return payload
def calculate_sha256_digest(file_path):
"""Calculate a file SHA-256 digest using GitHub's 'sha256:<hash>' format."""
sha256_hash = hashlib.sha256()
with open(file_path, "rb") as file:
for chunk in iter(lambda: file.read(1024 * 1024), b""):
sha256_hash.update(chunk)
digest = "sha256:" + sha256_hash.hexdigest()
log_event("sha256_calculated", file_path=file_path, digest=digest)
return digest
def get_missing_modules():
"""Return required Python modules that are not currently importable."""
missing_modules = []
for import_name, package_name in REQUIRED_MODULES:
try:
if package_name == "GitPython":
package_version(package_name)
else:
__import__(import_name)
except (ModuleNotFoundError, PackageNotFoundError):
missing_modules.append((import_name, package_name))
log_event("dependency_check_completed", missing_modules=[name for name, _ in missing_modules])
return missing_modules
def install_python_package(package_name):
"""Install one Python package using the same interpreter running MiSAR AIO."""
log_event("python_package_install_started", package=package_name)
subprocess.check_call([sys.executable, "-m", "pip", "install", package_name])
log_event("python_package_install_success", package=package_name)
def create_package_install_status_window(package_names):
"""Show a small status dialog while required Python packages are being installed."""
if main_window is None:
return None
package_text = ", ".join(package_names)
status_window = tkinter.Toplevel(main_window)
status_window.title("Installing Python Packages")
status_window.transient(main_window)
status_window.resizable(False, False)
status_window.configure(bg=PALETTE["panel"])
status_window.grab_set()
tkinter.Label(
status_window,
text="Installing required Python packages",
font=ui_font(13, "bold"),
bg=PALETTE["panel"],
fg=PALETTE["title"],
).grid(row=0, column=0, sticky="w", padx=18, pady=(16, 4))
status_window.message_label = tkinter.Label(
status_window,
text="MiSAR is installing packages now. Please wait.",
font=ui_font(11),
bg=PALETTE["panel"],
fg=PALETTE["text"],
justify="left",
wraplength=420,
)
status_window.message_label.grid(row=1, column=0, sticky="w", padx=18, pady=(0, 8))
status_window.package_label = tkinter.Label(
status_window,
text=f"Packages: {package_text}" if package_text else "Checking packages...",
font=ui_font(10),
bg=PALETTE["panel"],
fg=PALETTE["muted"],
justify="left",
wraplength=420,
)
status_window.package_label.grid(row=2, column=0, sticky="w", padx=18, pady=(0, 12))
status_window.progress = ttk.Progressbar(
status_window,
mode="determinate",
maximum=max(len(package_names), 1),
value=0,
)
status_window.progress.grid(row=3, column=0, sticky="ew", padx=18, pady=(0, 16))
status_window.grid_columnconfigure(0, weight=1)
status_window.update_idletasks()
x = main_window.winfo_x() + max((main_window.winfo_width() - status_window.winfo_reqwidth()) // 2, 0)
y = main_window.winfo_y() + max((main_window.winfo_height() - status_window.winfo_reqheight()) // 2, 0)
status_window.geometry(f"+{x}+{y}")
status_window.update_idletasks()
return status_window
def update_package_install_status_window(status_window, package_name, package_index, package_total):
"""Update the Python package installation status dialog."""
if status_window is None:
return
try:
status_window.message_label.configure(
text=f"Installing package {package_index} of {package_total}: {package_name}"
)
status_window.progress.configure(value=package_index - 1)
status_window.update_idletasks()
except tkinter.TclError:
pass
def finish_package_install_status_window(status_window, success):
"""Close the Python package installation status dialog after installation."""
if status_window is None:
return
try:
if success:
status_window.message_label.configure(text="Python packages installed successfully.")
status_window.progress.configure(value=status_window.progress.cget("maximum"))
status_window.update_idletasks()
status_window.grab_release()
status_window.destroy()
except tkinter.TclError:
pass
def check_required_modules():
"""Ensure MiSAR parser dependencies exist, optionally installing missing packages."""
missing_modules = get_missing_modules()
if not missing_modules:
return True
module_names = [package_name for _, package_name in missing_modules]
module_list = "\n".join(module_names)
if len(missing_modules) == 1:
message = (
"The following Python package is currently not installed:\n\n"
+ module_list
+ "\n\nThis package is required for MiSAR.\nWould you like MiSAR to install it now?"
)
else:
message = (
"The following Python packages are currently not installed:\n\n"
+ module_list
+ "\n\nThese packages are required for MiSAR.\nWould you like MiSAR to install them now?"
)
install_modules = messagebox.askquestion("Missing Python Packages", message)
log_event("missing_dependency_user_response", response=install_modules, modules=module_names)
if install_modules != "yes":
messagebox.showerror(
"Error!",
"MiSAR cannot operate correctly without "
+ plural_check(module_names)
+ " Please select yes and try again.",
)
return False
if not check_internet():
messagebox.showerror(
"Error!",
"An internet connection is required to install "
+ plural_check(module_names)
+ " Please connect to the internet and try again.",
)
return False
status_window = create_package_install_status_window(module_names)
set_busy_status("Installing required Python packages. Please wait...", active=True)
refresh_ui_now()
try:
total_packages = len(missing_modules)
for package_index, (_import_name, package_name) in enumerate(missing_modules, start=1):
update_package_install_status_window(status_window, package_name, package_index, total_packages)
set_status(f"Installing Python package {package_index} of {total_packages}: {package_name}")
refresh_ui_now()
install_python_package(package_name)
if get_missing_modules():
raise RuntimeError("Some required modules are still missing after installation.")
finish_package_install_status_window(status_window, success=True)
set_busy_status("Required Python packages installed successfully.", active=False)
messagebox.showinfo("Success!", "The required Python packages were installed successfully.")
return True
except Exception as error:
finish_package_install_status_window(status_window, success=False)
set_busy_status("Python package installation failed.", active=False)
log_exception("dependency_install_failed", error, modules=module_names)
messagebox.showerror(
"Error!",
"The installation of the required Python packages has failed.\nError code:\n" + str(error),
)
return False
def read_json_file(file_path):
"""Read JSON from disk, returning an empty dictionary when the file is unavailable."""
if not file_path.is_file():
log_event("json_file_missing", path=file_path)
return {}
try:
with open(file_path, "r", encoding="utf-8") as json_file:
data = json.load(json_file)
log_event("json_file_read", path=file_path, data=data)
return data
except Exception as error:
log_event("json_file_read_failed", path=file_path, error=str(error))
return {}
def write_json_file(file_path, data):
"""Write JSON metadata to disk, creating the parent directory when required."""
file_path.parent.mkdir(parents=True, exist_ok=True)
with open(file_path, "w", encoding="utf-8") as json_file:
json.dump(data, json_file, indent=2)
log_event("json_file_written", path=file_path, data=data)
def read_version_json_file(file_path):
"""Read MISAR.versions.json from the launcher root, or return empty data if absent."""
if not file_path.is_file():
return {}
try:
with open(file_path, "r", encoding="utf-8") as json_file:
data = json.load(json_file)
return data if isinstance(data, dict) else {}
except Exception as error:
log_event("version_json_file_read_failed", path=file_path, error=str(error))
return {}
def load_misar_versions():
"""Read MiSAR versions from MISAR.versions.json, or return empty data if absent."""
version_keys = {key for keys in MODULE_VERSION_KEYS.values() for key in keys}
version_keys.update(LAUNCHER_VERSION_KEYS)
data = read_version_json_file(VERSION_FILE_PATH)
versions = {key: str(value) for key, value in data.items() if key in version_keys and value}
if versions:
log_event("misar_versions_loaded", path=VERSION_FILE_PATH, versions=versions)
return versions
log_event("misar_versions_unavailable", path=VERSION_FILE_PATH)
return {}
def read_config_json_file(file_path):
"""Read launcher user configuration from MISAR.configs.json."""
if not file_path.is_file():
log_event("config_json_file_missing", path=file_path)
return {}
try:
with open(file_path, "r", encoding="utf-8") as json_file:
data = json.load(json_file)
return data if isinstance(data, dict) else {}
except Exception as error:
log_event("config_json_file_read_failed", path=file_path, error=str(error))
return {}
def load_misar_configs():
"""Read user-selected launcher paths/settings from MISAR.configs.json."""
configs = read_config_json_file(CONFIG_FILE_PATH)
if configs:
log_event("misar_configs_loaded", path=CONFIG_FILE_PATH, configs=configs)
return configs
log_event("misar_configs_unavailable", path=CONFIG_FILE_PATH)
return {}
def write_misar_config(config_key, config_value):
"""Update one launcher config entry and persist it to MISAR.configs.json."""
global MISAR_CONFIGS
config_value = str(config_value).strip() if config_value is not None else ""
config_data = read_config_json_file(CONFIG_FILE_PATH)
if not config_data and MISAR_CONFIGS:
config_data = dict(MISAR_CONFIGS)
if config_value:
config_data[config_key] = config_value
MISAR_CONFIGS[config_key] = config_value
else:
config_data.pop(config_key, None)
MISAR_CONFIGS.pop(config_key, None)
write_json_file(CONFIG_FILE_PATH, config_data)
log_event("misar_config_updated", path=CONFIG_FILE_PATH, key=config_key, value=config_value)
return True
def get_misar_config_bool(config_key, default=False):
"""Read one boolean launcher config from MISAR.configs.json data."""
return config_value_as_bool(MISAR_CONFIGS.get(config_key), default)
def is_auto_update_enabled():
"""Return True when startup parser update checks are enabled."""
return get_misar_config_bool(AUTO_UPDATE_CONFIG_KEY, True)
def bool_to_config_value(value):
"""Serialise a boolean setting for MISAR.configs.json."""
return "true" if bool(value) else "false"
def get_configured_version(version_keys):
"""Return a configured version for the supplied keys, or an empty string when unavailable."""
for version_key in version_keys:
version = MISAR_VERSIONS.get(version_key)
if version:
return str(version)
return ""
def get_module_version(module_name):
"""Return a configured module version, or an empty string when unavailable."""
return get_configured_version(MODULE_VERSION_KEYS.get(module_name, ()))
def get_launcher_version():
"""Return the configured launcher version, or an empty string when unavailable."""
return get_configured_version(LAUNCHER_VERSION_KEYS)
def format_version_text(version):
"""Format a version value for display while allowing empty versions to stay hidden."""
version = str(version).strip() if version else ""
if not version:
return ""
return version if version.lower().startswith("v") else "v" + version
def write_misar_version(version_key, version):
"""Update one entry inside MISAR.versions.json and the in-memory version cache."""
global MISAR_VERSIONS
version = str(version).strip() if version else ""
if not version:
log_event("misar_version_update_skipped", key=version_key, reason="empty_version")
return False
version_data = read_version_json_file(VERSION_FILE_PATH)
if not version_data and MISAR_VERSIONS:
version_data = dict(MISAR_VERSIONS)
previous_version = version_data.get(version_key)
if previous_version == version and MISAR_VERSIONS.get(version_key) == version:
log_event("misar_version_update_skipped", key=version_key, reason="already_current", version=version)
return False
version_data[version_key] = version
write_json_file(VERSION_FILE_PATH, version_data)
MISAR_VERSIONS[version_key] = version
log_event(
"misar_version_updated",
path=VERSION_FILE_PATH,
key=version_key,
previous_version=previous_version,
version=version,
)
return True
def sync_gmg_visualiser_version_from_asset(asset):
"""Persist the latest GMG release tag_name into MISAR.versions.json."""
tag_name = str(asset.get("tag_name") or "").strip()
if not tag_name:
log_event("gmg_version_sync_skipped", reason="missing_tag_name", asset=asset)
return False
try:
updated = write_misar_version(GMG_VERSION_KEY, tag_name)
refresh_gmg_version_display()
log_event("gmg_version_sync_completed", updated=updated, tag_name=tag_name)
return updated
except Exception as error:
log_exception("gmg_version_sync_failed", error, tag_name=tag_name, path=VERSION_FILE_PATH)
return False
def open_documentation():
"""Open the MiSAR online documentation in the user's default browser."""
log_event("documentation_open_requested", url=MISAR_DOCUMENTATION_URL)
if check_internet():
webbrowser.open(MISAR_DOCUMENTATION_URL, new=2)
log_event("documentation_opened", url=MISAR_DOCUMENTATION_URL)
return True
messagebox.showerror(
"No Internet Connection",
"An internet connection is required to open the MiSAR documentation website.",
)
log_event("documentation_open_failed", reason="no_internet")
return False
def uninstall_path(location):
"""Remove an installed MiSAR directory, including read-only files on Windows."""
target_link = ""
read_only = True
location_path = USER_HOME_DIR / Path(location)
log_event("uninstall_started", location=location_path)
while read_only:
read_only = False
try:
location_path.rmdir()
log_event("uninstall_completed", location=location_path)
except OSError:
try:
shutil.rmtree(location_path)
log_event("uninstall_completed", location=location_path)
except FileNotFoundError:
log_event("uninstall_skipped_missing_path", location=location_path)
except PermissionError as error:
log_event("uninstall_permission_error", location=location_path, error=str(error))
error_text = str(error)
comma_activate = False
for character in error_text:
if character == "'" and comma_activate:
comma_activate = False
elif comma_activate:
target_link += character
elif character == "'" and not comma_activate:
comma_activate = True
target_path = Path(target_link)
target_path.chmod(stat.S_IWRITE)
target_path.unlink()
try:
shutil.rmtree(target_path)
except FileNotFoundError:
pass
target_link = ""
read_only = True
def stream_process_output(process, process_name):
"""Stream a child process stdout/stderr into the debug logger without blocking Tkinter."""
if process.stdout is None:
return
try:
for line in process.stdout:
line = line.rstrip()
if line:
LOGGER.debug("%s output | %s", process_name, line)
return_code = process.wait()
log_event("subprocess_completed", process_name=process_name, return_code=return_code)
except Exception as error:
log_exception("subprocess_output_stream_failed", error, process_name=process_name)
def launch_logged_subprocess(command, process_name, cwd=None):
"""Launch a child process without closing or blocking the MiSAR AIO window."""
log_event("subprocess_launch_started", process_name=process_name, command=command, cwd=cwd)
if not DEBUG_MODE:
process = subprocess.Popen(command, cwd=cwd)
log_event("subprocess_launch_completed", process_name=process_name, pid=process.pid)
return process
environment = os.environ.copy()
environment["PYTHONUNBUFFERED"] = "1"
environment["MISAR_AIO_DEBUG"] = "1"
process = subprocess.Popen(
command,
cwd=cwd,
env=environment,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
)
output_thread = threading.Thread(
target=stream_process_output,
args=(process, process_name),
daemon=True,
)
output_thread.start()
log_event("subprocess_launch_completed", process_name=process_name, pid=process.pid)
return process
def run_on_ui_thread(callback, *args, **kwargs):
"""Schedule a callback on the Tkinter UI thread when the main window exists."""
if main_window is not None and hasattr(main_window, "after"):
main_window.after(0, lambda: callback(*args, **kwargs))
else:
callback(*args, **kwargs)
def show_info_on_ui_thread(title, message):
run_on_ui_thread(messagebox.showinfo, title, message)
def show_error_on_ui_thread(title, message):
run_on_ui_thread(messagebox.showerror, title, message)
def ask_question_on_ui_thread(title, message, default="no"):
"""Ask a Tkinter question from worker code and wait for the UI-thread response."""
if main_window is None or not hasattr(main_window, "after"):
return messagebox.askquestion(title, message)
response_holder = {"response": default}
completed = threading.Event()
def ask():
try:
response_holder["response"] = messagebox.askquestion(title, message)
finally:
completed.set()
main_window.after(0, ask)
completed.wait()
return response_holder["response"]
def ask_yesno_on_ui_thread(title, message, default=False):
"""Ask a Tkinter yes/no question from worker code and wait for the UI-thread response."""
if main_window is None or not hasattr(main_window, "after"):
return messagebox.askyesno(title, message)
response_holder = {"response": default}
completed = threading.Event()
def ask():
try:
response_holder["response"] = messagebox.askyesno(title, message)
finally:
completed.set()
main_window.after(0, ask)
completed.wait()
return response_holder["response"]
# ===============================
# INSTALLERS
# ===============================
def install_parser():
"""Install the MiSAR parser and persist repository metadata when available."""
if USE_REPOSITORY_PARSER:
log_event("parser_install_skipped", reason="use_repository_parser", path=ACTIVE_PARSER_DIR)
return is_parser_installed()
repository_metadata = None
try:
if check_internet():
repository_metadata = get_parser_repository_metadata()
except Exception as error:
log_event("parser_repository_metadata_unavailable", error=str(error))
return clone_parser_repository(Path("MiSAR") / "Parser", repository_metadata)
def clone_parser_repository(parser_location, repository_metadata=None):
"""Clone the parser repository into the MiSAR installation directory."""
from git import Repo
parser_path = USER_HOME_DIR / Path(parser_location)
log_event("parser_install_started", path=parser_path)
try:
Repo.clone_from(PARSER_REPOSITORY_CLONE_URL, parser_path, branch="main")
parser_ready = (
parser_path / "TransformationEngineNecessities" / "source" / "PSM.ecore"
).is_file() and (parser_path / "ParserNecessities" / "MisarParserGUI.py").is_file()
if parser_ready:
if repository_metadata is not None and parser_path == INSTALLED_PARSER_DIR:
write_parser_metadata(repository_metadata)
log_event("parser_install_success", path=parser_path)
return True
log_event("parser_install_validation_failed", path=parser_path)
return False
except Exception as error:
log_exception("parser_install_failed", error, path=parser_path)
return False
def install_or_update_gmg():
"""Download or update the Graphical Model Generator JAR from the latest release."""
log_event("gmg_install_or_update_started", jar_path=GMG_JAR_PATH)
try:
asset = get_latest_gmg_jar_asset()
if not should_download_gmg_jar(asset):
sync_gmg_visualiser_version_from_asset(asset)
log_event("gmg_jar_already_current", jar_path=GMG_JAR_PATH)
return True
download_gmg_jar(asset)
write_gmg_metadata(asset)
sync_gmg_visualiser_version_from_asset(asset)
installed = GMG_JAR_PATH.is_file()
log_event("gmg_install_or_update_completed", installed=installed, jar_path=GMG_JAR_PATH)
return installed
except Exception as error:
log_exception("gmg_install_or_update_failed", error, jar_path=GMG_JAR_PATH)
return False
def get_latest_gmg_jar_asset():
"""Return release metadata for the latest valid MiSAR.jar asset."""
release_data = get_json_from_url(GMG_RELEASE_API_URL)
assets_url = release_data.get("assets_url")
if not assets_url:
raise RuntimeError("The latest GMG release does not include an assets URL.")
assets = get_json_from_url(assets_url)
log_event("gmg_release_assets_loaded", asset_count=len(assets))
for asset in assets:
asset_name = asset.get("name", "")
content_type = asset.get("content_type", "")
is_expected_name = asset_name == GMG_ASSET_NAME
is_java_archive = content_type == "application/java-archive"
is_jar_file = asset_name.lower().endswith(".jar")
if is_expected_name and is_jar_file and is_java_archive:
download_url = asset.get("browser_download_url")
if not download_url:
raise RuntimeError("The GMG JAR asset does not include a download URL.")
selected_asset = {
"name": asset_name,
"download_url": download_url,
"digest": asset.get("digest"),
"updated_at": asset.get("updated_at"),
"size": asset.get("size"),
"tag_name": release_data.get("tag_name"),
}
log_event("gmg_release_asset_selected", asset=selected_asset)
return selected_asset
raise RuntimeError("Could not find a valid MiSAR.jar release asset.")
def should_download_gmg_jar(asset):
"""Return True when the local GMG JAR is missing or differs from the release asset."""
if not GMG_JAR_PATH.is_file():
log_event("gmg_download_required", reason="missing_local_jar", jar_path=GMG_JAR_PATH)
return True
expected_digest = asset.get("digest")
if expected_digest:
current_digest = calculate_sha256_digest(GMG_JAR_PATH)
should_download = current_digest != expected_digest
log_event(
"gmg_digest_comparison_completed",
should_download=should_download,
current_digest=current_digest,
expected_digest=expected_digest,
)
return should_download
metadata = read_gmg_metadata()
should_download = metadata.get("updated_at") != asset.get("updated_at")
log_event(
"gmg_updated_at_comparison_completed",
should_download=should_download,
local_updated_at=metadata.get("updated_at"),
remote_updated_at=asset.get("updated_at"),
)
return should_download
def download_gmg_jar(asset):
"""Download the GMG JAR to a temporary file and verify its SHA-256 digest."""
GMG_JAR_DIR.mkdir(parents=True, exist_ok=True)
temp_path = GMG_JAR_PATH.with_suffix(".jar.tmp")
log_event("gmg_download_started", url=asset["download_url"], temp_path=temp_path)
request = Request(asset["download_url"], headers={"User-Agent": "MiSAR-AIO"})
with urlopen(request, timeout=120) as response:
with open(temp_path, "wb") as output_file: