-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple-mod.py
1223 lines (971 loc) · 48.3 KB
/
simple-mod.py
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
# =====================================================================
# SIMPLE-MOD
# (Singularity Integrated Module-key Producer for Loadable
# Environment MODules)
# Developer: Jason Li ([email protected])
# Version: 1.0
# Dependency: PyQt5
# =====================================================================
import sys, json, os, tempfile
from string import Template
from PyQt5 import QtGui
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget,
QVBoxLayout, QHBoxLayout, QFormLayout, QMessageBox,
QLineEdit, QTextEdit, QTableWidget, QTableWidgetItem, QComboBox, QPushButton, QLabel, QDialog, QDialogButtonBox, QAction, QFileDialog)
# Main window
class MainWindow(QMainWindow):
#============================================================
# Constructor
#============================================================
def __init__(self):
"""
Constructor
"""
super().__init__()
# Load preferences
self.loadPreferences()
# Key attributes
self.title = "SIMPLE-MOD "
# Window title
self.flagDBChanged = False # Whether the database is changed from creation or opening
self.db = {} # Loaded database dictionary (empty if it's new)
self.currentModule = self.retEmptyModule() # Current opened module
#--------------------------------------------------------
# Menu bar
#--------------------------------------------------------
# Menu
self.menubar = self.menuBar()
# Menu 1
self.fileMenu = self.menubar.addMenu('\n File ')
self.newDBAct = QAction('New Database', self)
self.newDBAct.triggered.connect(self.newDB)
self.newDBAct.setShortcut("Ctrl+N")
self.fileMenu.addAction(self.newDBAct)
self.openDBAct = QAction('Open Database...', self)
self.openDBAct.triggered.connect(self.openDB)
self.openDBAct.setShortcut("Ctrl+O")
self.fileMenu.addAction(self.openDBAct)
self.saveDBAct = QAction('Save Database...', self)
self.saveDBAct.triggered.connect(self.saveDB)
self.saveDBAct.setShortcut("Ctrl+S")
self.fileMenu.addAction(self.saveDBAct)
self.fileMenu.addSeparator()
self.exitAct = QAction('Exit', self)
self.exitAct.triggered.connect(self.close)
self.exitAct.setShortcut("Alt+F4")
self.fileMenu.addAction(self.exitAct)
# Menu 2
self.settingsMenu = self.menubar.addMenu(' Settings ')
self.preferencesAct = QAction('Preferences...', self)
self.preferencesAct.triggered.connect(self.preferencesDialog)
self.preferencesAct.setShortcut("Ctrl+P")
self.settingsMenu.addAction(self.preferencesAct)
# Menu 3
self.helpMenu = self.menubar.addMenu(' Help ')
self.aboutAct = QAction('About', self)
self.aboutAct.triggered.connect(self.aboutDialog)
self.aboutAct.setShortcut("F1")
self.helpMenu.addAction(self.aboutAct)
self.aboutQTAct = QAction('About QT', self)
self.aboutQTAct.triggered.connect(self.aboutQtDialog)
self.helpMenu.addAction(self.aboutQTAct)
#--------------------------------------------------------
# Block1: Choose / create module
#--------------------------------------------------------
# Header
self.blk1Label = QLabel('Module List')
self.blk1Label.setStyleSheet('QLabel { font-size: 16px; font-weight: bold; }')
# Module name dropdown menu
self.nameDrop = QComboBox(self)
self.nameDrop.currentTextChanged.connect(self.nameDropChanged)
self.nameDropUpdateFromDB()
# Module version dropdown menu
self.versionDrop = QComboBox(self)
self.versionDrop.currentTextChanged.connect(self.versionDropChanged)
# Add / Delete buttons
self.addBtn = QPushButton("Add a new module", self)
self.addBtn.clicked.connect(self.addMod)
self.copyBtn = QPushButton("Copy current module", self)
self.copyBtn.clicked.connect(self.copyMod)
self.delBtn = QPushButton("Delete selected module", self)
self.delBtn.clicked.connect(self.delMod)
self.blk1BtnLayout = QHBoxLayout()
self.blk1BtnLayout.addWidget(self.addBtn)
self.blk1BtnLayout.addWidget(self.copyBtn)
self.blk1BtnLayout.addWidget(self.delBtn)
# Combine module choose layout
self.moduleChooseLayout = QFormLayout()
self.moduleChooseLayout.addRow("Module name", self.nameDrop)
self.moduleChooseLayout.addRow("Module version", self.versionDrop)
self.moduleChooseLayout.addRow(self.blk1BtnLayout)
#--------------------------------------------------------
# Block2: Module details
#--------------------------------------------------------
# Header
self.blk2Label = QLabel('Module Details')
self.blk2Label.setStyleSheet('QLabel { font-size: 16px; font-weight: bold; }')
# Conflicts
self.conflictText = QLineEdit(self)
self.conflictText.setPlaceholderText("(Seperate by space. Itself is already added.)")
pal = self.conflictText.palette()
pal.setColor(QtGui.QPalette.PlaceholderText, QtGui.QColor("#BBBBBB"))
# Placeholder text color palette. Will be reused.
self.conflictText.setPalette(pal)
self.conflictText.textChanged.connect(self.setTitleForUnsavedChanges)
# What-is
self.whatisText = QLineEdit(self)
self.whatisText.textChanged.connect(self.setTitleForUnsavedChanges)
# Singularity image path (editable text field and file picker button)
self.singularityImageText = QLineEdit(self)
self.singularityImageText.textChanged.connect(self.setTitleForUnsavedChanges)
self.singularityImagePickerBtn = QPushButton("Browse", self)
self.singularityImagePickerBtn.clicked.connect(self.pickSingularityImageFile)
self.singularityImageLayout = QHBoxLayout()
self.singularityImageLayout.addWidget(self.singularityImageText)
self.singularityImageLayout.addWidget(self.singularityImagePickerBtn)
# Singularity binding path
self.singularityBindText = QLineEdit(self)
self.singularityBindText.setPlaceholderText(f"(Already bound: /home,/tmp,{self.config['defaultBindingPath']})")
self.singularityBindText.setPalette(pal)
self.singularityBindText.textChanged.connect(self.setTitleForUnsavedChanges)
# Singularity flags
self.singularityFlagsText = QLineEdit(self)
self.singularityFlagsText.setPlaceholderText(f"(Already enabled: {self.config['defaultFlags']})")
self.singularityFlagsText.setPalette(pal)
self.singularityFlagsText.textChanged.connect(self.setTitleForUnsavedChanges)
# Commands to replace
self.cmdsText = QTextEdit(self)
self.cmdsText.setPlaceholderText("(Seperate by space or new line)")
self.cmdsText.setPalette(pal)
self.cmdsText.textChanged.connect(self.setTitleForUnsavedChanges)
# Environment variables to set up
self.envsTable = QTableWidget(1, 2, self)
self.envsUpdateFromDB()
self.envsTable.itemChanged.connect(self.setTitleForUnsavedChanges)
# Environment variables add / delete entry
self.envsAddBtn = QPushButton("Add", self)
self.envsAddBtn.clicked.connect(self.envsAdd)
self.envsDelBtn = QPushButton("Delete", self)
self.envsDelBtn.clicked.connect(self.envsDel)
self.envsBtnLayout = QHBoxLayout()
self.envsBtnLayout.addWidget(self.envsAddBtn)
self.envsBtnLayout.addWidget(self.envsDelBtn)
# Template file path (editable text field and file picker button)
self.templateText = QLineEdit(self)
self.templateText.textChanged.connect(self.setTitleForUnsavedChanges)
self.templatePickerBtn = QPushButton("Browse", self)
self.templatePickerBtn.clicked.connect(self.pickTemplate)
self.templateLayout = QHBoxLayout()
self.templateLayout.addWidget(self.templateText)
self.templateLayout.addWidget(self.templatePickerBtn)
# Combine module edit layout
self.moduleEditLayout = QFormLayout()
self.moduleEditLayout.addRow("Conflicts", self.conflictText)
self.moduleEditLayout.addRow("Software description", self.whatisText)
self.moduleEditLayout.addRow("Singularity image path", self.singularityImageLayout)
self.moduleEditLayout.addRow("Singularity binding paths", self.singularityBindText)
self.moduleEditLayout.addRow("Additional Singularity flags", self.singularityFlagsText)
self.moduleEditLayout.addRow("Commands to map", self.cmdsText)
self.moduleEditLayout.addRow("Set up environmental variable", self.envsTable)
self.moduleEditLayout.addRow("", self.envsBtnLayout)
self.moduleEditLayout.addRow("Module key template", self.templateLayout)
#--------------------------------------------------------
# Block3: Confirmation buttons
#--------------------------------------------------------
# Add / edit buttons
self.genBtn = QPushButton("\nGenerate current module key\n", self)
self.genBtn.clicked.connect(self.genModKey)
self.exportBtn = QPushButton("\nGenerate all module keys from current database\n", self)
self.exportBtn.clicked.connect(self.genAllModKeys)
self.confirmationBtnsLayout = QHBoxLayout()
self.confirmationBtnsLayout.addWidget(self.genBtn)
self.confirmationBtnsLayout.addWidget(self.exportBtn)
#--------------------------------------------------------
# Combine all to create main window
#--------------------------------------------------------
# Create main layout
self.mainLayout = QVBoxLayout()
#self.mainLayout.addWidget(QLabel("", self))
self.mainLayout.addWidget(self.blk1Label)
self.mainLayout.addLayout(self.moduleChooseLayout)
self.mainLayout.addWidget(QLabel("", self))
self.mainLayout.addWidget(self.blk2Label)
self.mainLayout.addLayout(self.moduleEditLayout)
self.mainLayout.addWidget(QLabel("", self))
self.mainLayout.addLayout(self.confirmationBtnsLayout)
# Create container
container = QWidget()
container.setLayout(self.mainLayout)
self.setCentralWidget(container)
# Set main window properties
self.setWindowTitle(self.title)
self.setGeometry(100, 100, 750, 750)
#============================================================
# Menu methods
#============================================================
def newDB(self):
"""
Create a new empty database.
"""
# Check any unsaved changes
if (self.cancelForUnsavedChanges()): return
# Reset database to empty
self.db = {}
self.currentModule = self.retEmptyModule()
# Update current form
self.nameDropUpdateFromDB()
self.versionDropUpdateFromDB()
# Mark database as unchanged
self.flagDBChanged = False
# Update window title
self.setTitleForUnsavedChanges()
def openDB(self):
"""
Select and open database file.
"""
# Check any unsaved changes
if (self.cancelForUnsavedChanges()): return
# Pick a database file to open
fname, _ = QFileDialog.getOpenFileName(self, 'Open Database', "database/", filter="JSON Files (*.json)")
# If successfully picked a file...
if fname:
# Try if this file is writable:
# If writable, continue saving; if not, return False
try:
f = open(fname)
except:
QMessageBox.critical(self, 'Error!', 'You cannot read this file!')
return(False)
# Read to "db" dictionary
self.db = json.load(f)
f.close()
# Update currrent form
self.nameDropUpdateFromDB()
self.versionDropUpdateFromDB()
# Mark database as unchanged
self.flagDBChanged = False
# Update window title
self.setTitleForUnsavedChanges()
def saveDB(self):
"""
Save database to file. To avoid data loss, always ask for confirmation.
Return:
True: Successfully saved
False: Not saved
"""
# At least one module (current) must exist, or return error:
if (self.nameDrop.currentText() and self.nameDrop.currentText()):
# Pick a database file to save
fname, _ = QFileDialog.getSaveFileName(self, 'Save Database', "database/", filter="JSON Files (*.json)")
# If successfully picked a file...
if fname:
# Add ".json" extension of not already added
if (fname.split(".")[-1] != "json"):
fname += ".json"
# Try if this file is writable:
# If writable, continue saving; if not, return False
try:
fw = open(fname, "w")
except:
QMessageBox.critical(self, 'Error!', 'Saving failed! You do not have permission to write to this file!')
return(False)
# Set current form to currentModule
self.modSaveToDB()
# Save currentModule to database
self.db[self.nameDrop.currentText()][self.versionDrop.currentText()] = self.currentModule
# Save database to file
json.dump(self.db, fw, indent=4)
fw.close()
# Mark database as unchanged
self.flagDBChanged = False
# Update window title
self.setTitleForUnsavedChanges()
# Return successful
return(True)
else:
QMessageBox.critical(self, 'Error!', 'At least one module must exist to save!')
# If has not successfully returned at this point, return False
return(False)
def preferencesDialog(self):
"""
Preferences settingsMenu
"""
# Open a dialog
prefDial = PreferenceDialog(self)
# If confirmed, save preferences
if prefDial.exec_():
# Save preferences to self.config
self.config["defaultBindingPath"] = prefDial.defaultBindingPathText.text()
self.config["defaultFlags"] = prefDial.defaultFlagsText.text()
self.config["defaultImagePath"] = prefDial.defaultImagePathText.text()
self.config["defaultTemplate"] = prefDial.defaultTemplateText.text()
self.config["defaultModKeyPath"] = prefDial.defaultModKeyPathText.text()
# Write to configuration file
with open(os.path.expanduser('~/.simple-modrc'), "w") as fw:
json.dump(self.config, fw, indent=4)
# Update prompts
self.singularityBindText.setPlaceholderText(f"(Already bound: /home,/tmp,{self.config['defaultBindingPath']})")
self.singularityFlagsText.setPlaceholderText(f"(Already enabled: {self.config['defaultFlags']})")
def aboutDialog(self):
"""
Show about information
"""
QMessageBox.about(self, "About", \
f"""{self.title}
(Singularity Integrated Module-key Producer for Loadable Environment MODules)
SIMPLE-MOD is a QT-based GUI tool to automatically generate module keys for easy access of container-based software packages.
Version: \t1.0
Author: \tJason Li
Home: \thttps://github.com/lsuhpchelp/SIMPLE-MOD
License: \tMIT License
""")
def aboutQtDialog(self):
"""
Show about information
"""
QMessageBox.aboutQt(self, "About QT")
#============================================================
# Dropdown menu methods
#============================================================
def nameDropUpdateFromDB(self):
"""
Update module name dropdown menu.
"""
self.nameDrop.currentTextChanged.disconnect()
self.nameDrop.clear()
self.nameDrop.addItems(sorted(self.db.keys()))
self.nameDropCurrentText = self.nameDrop.currentText()
self.nameDrop.currentTextChanged.connect(self.nameDropChanged)
def nameDropSetCurrentText(self, text):
"""
Set (silently) current text for name dropdown menu.
"""
self.nameDrop.currentTextChanged.disconnect()
self.nameDrop.setCurrentText(text)
self.nameDropCurrentText = text
self.nameDrop.currentTextChanged.connect(self.nameDropChanged)
def nameDropChanged(self, text):
"""
When selected module name is changed.
"""
# Check any unsaved changes in the current module form
if (self.cancelForUnsavedModChanges()):
# If choose to stay for unsaved changes, revert all
self.nameDrop.currentTextChanged.disconnect()
self.nameDrop.setCurrentText(self.nameDropCurrentText)
self.nameDrop.currentTextChanged.connect(self.nameDropChanged)
else:
# Otherwise continue, update version dropdown menu
self.nameDropCurrentText = text
self.versionDropUpdateFromDB()
def versionDropUpdateFromDB(self):
"""
Update module version dropdown menu.
"""
self.versionDrop.currentTextChanged.disconnect()
self.versionDrop.clear()
if (self.nameDrop.currentText()) :
self.versionDrop.addItems(sorted(self.db[self.nameDrop.currentText()].keys(), reverse=True))
self.modUpdateFromDB()
self.versionDrop.currentTextChanged.connect(self.versionDropChanged)
def versionDropSetCurrentText(self, text):
"""
Set (silently) current text for version dropdown menu.
"""
self.versionDrop.currentTextChanged.disconnect()
self.versionDrop.setCurrentText(text)
self.versionDropCurrentText = text
self.versionDrop.currentTextChanged.connect(self.versionDropChanged)
def versionDropChanged(self, text):
"""
When selected module version is changed.
"""
# Check any unsaved changes
if (self.cancelForUnsavedModChanges()):
# If choose to stay for unsaved changes, revert all
self.versionDrop.currentTextChanged.disconnect()
self.versionDrop.setCurrentText(self.versionDropCurrentText)
self.versionDrop.currentTextChanged.connect(self.versionDropChanged)
else:
# Otherwise continue, update module form to current selected module
self.versionDropCurrentText = text
self.modUpdateFromDB()
#============================================================
# Module form methods
#============================================================
def modUpdateFromDB(self):
"""
Update module form from database ("currentModule" dictionary)
"""
#global currentModule
# If a non-empty module is selected, update currentModule from database and enable all fields;
# If not, meaning nothing is selected, disable all fields
if (self.nameDrop.currentText() and self.versionDrop.currentText()) :
self.currentModule = self.db[self.nameDrop.currentText()][self.versionDrop.currentText()]
self.enableForm(True)
else:
self.enableForm(False)
# Set all values from currentModule dict
self.conflictText.setText(self.currentModule["conflict"])
self.whatisText.setText(self.currentModule["module_whatis"])
self.singularityImageText.setText(self.currentModule["singularity_image"])
self.singularityBindText.setText(self.currentModule["singularity_bindpaths"])
self.singularityFlagsText.setText(self.currentModule["singularity_flags"])
self.cmdsText.setText(self.currentModule["cmds"])
self.envsUpdateFromDB()
self.templateText.setText(self.currentModule["template"])
# Update window title
self.setTitleForUnsavedChanges()
def modSaveToDB(self):
"""
Save module form to database ("currentModule" dictionary)
"""
# Save all values to currentModule dict
self.currentModule["conflict"] = self.conflictText.text()
self.currentModule["module_whatis"] = self.whatisText.text()
self.currentModule["singularity_image"] = self.singularityImageText.text()
self.currentModule["singularity_bindpaths"] = self.singularityBindText.text()
self.currentModule["singularity_flags"] = self.singularityFlagsText.text()
self.currentModule["cmds"] = self.cmdsText.toPlainText()
self.envsSaveToDB()
self.currentModule["template"] = self.templateText.text()
def pickSingularityImageFile(self):
"""
Pick Singularity image file in file browser.
"""
# Pick a database file to open
fname, _ = QFileDialog.getOpenFileName(self, 'Choose Singularity Image File', self.config["defaultImagePath"], filter="Singularity Image (*.sif *.img)")
if fname:
self.singularityImageText.setText(fname)
def pickTemplate(self):
"""
Pick template file in file browser.
"""
# Pick a database file to open
fname, _ = QFileDialog.getOpenFileName(self, 'Choose Module Key Template File', "template", filter="All files (*)")
if fname:
self.templateText.setText(fname)
#============================================================
# Add / Delete module
#============================================================
def addMod(self):
"""
Add a module.
"""
# Check any unsaved changes
if (self.cancelForUnsavedModChanges()): return
# Open a dialog
newModDial = NewModuleDialog(self)
# If confirmed, create module
if newModDial.exec_():
# Strip module name and version
modName = newModDial.modNameText.text()
modVersion = newModDial.modVersionText.text()
# Check a module with the same name already exist:
if (modName in self.db.keys()):
# If the module of the same name and version exists, warn and do nother
if (modVersion in self.db[modName].keys()):
QMessageBox.critical(self, 'Error', 'Module of the same name and version already exists!')
return
else:
# If the module name is found but version is not, add a new version to existing module name
self.db[modName][modVersion] = self.retEmptyModule()
else:
# If the module name is not found, add a new module name
self.db[modName] = {
modVersion : self.retEmptyModule()
}
# Update dropdown menu
self.nameDropUpdateFromDB()
self.nameDropSetCurrentText(newModDial.modNameText.text())
self.versionDropUpdateFromDB()
self.versionDropSetCurrentText(newModDial.modVersionText.text())
self.modUpdateFromDB()
# Mark database as changed
self.flagDBChanged = True
# Update window title
self.setTitleForUnsavedChanges()
def copyMod(self):
"""
Copy current module.
"""
# Check any unsaved changes
if (self.cancelForUnsavedModChanges()): return
# Open a dialog
newModDial = NewModuleDialog(self)
# If confirmed, create module
if newModDial.exec_():
# Strip module name and version
modName = newModDial.modNameText.text()
modVersion = newModDial.modVersionText.text()
# Check a module with the same name already exist:
if (modName in self.db.keys()):
# If the module of the same name and version exists, warn and do nother
if (modVersion in self.db[modName].keys()):
QMessageBox.critical(self, 'Error', 'Module of the same name and version already exists!')
return
else:
# If the module name is found but version is not, add a new version to existing module name
self.db[modName][modVersion] = self.currentModule.copy()
else:
# If the module name is not found, add a new module name
self.db[modName] = {
modVersion : self.currentModule.copy()
}
# Update dropdown menu
self.nameDropUpdateFromDB()
self.nameDropSetCurrentText(newModDial.modNameText.text())
self.versionDropUpdateFromDB()
self.versionDropSetCurrentText(newModDial.modVersionText.text())
self.modUpdateFromDB()
# Mark database as changed
self.flagDBChanged = True
# Update window title
self.setTitleForUnsavedChanges()
def delMod(self):
"""
Delete selected module.
"""
# Confirm whether to delete
reply = QMessageBox.question(self, 'Confirmation',
"Are you sure you want to delete this module? This change cannot be reverted!", QMessageBox.Yes |
QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
# Check whether this module has multiple versions
if len(self.db[self.nameDrop.currentText()].keys()) > 1:
# If so, only delete the selected version
del self.db[self.nameDrop.currentText()][self.versionDrop.currentText()]
# Select next available version
self.versionDropUpdateFromDB()
else:
# If not (this is the only version), delete the entire module entry
del self.db[self.nameDrop.currentText()]
# Update the name dropdown menu
self.nameDropUpdateFromDB()
self.versionDropUpdateFromDB()
# Mark database as changed
self.flagDBChanged = True
# Update window title
self.setTitleForUnsavedChanges()
#============================================================
# Environment variable table related methods
#============================================================
def envsAdd(self):
"""
Add a new environmental variable.
"""
self.envsTable.setRowCount(self.envsTable.rowCount()+1)
item = QTableWidgetItem(f"ENV_{self.envsTable.rowCount()}")
self.envsTable.setItem(self.envsTable.rowCount()-1, 0, item)
item = QTableWidgetItem("")
self.envsTable.setItem(self.envsTable.rowCount()-1, 1, item)
def envsDel(self):
"""
Delete the selected environmental variable(s).
"""
items = self.envsTable.selectedItems()
for item in items:
self.envsTable.removeRow(item.row())
# Update window title (Manually update because "itemChanged" signal is not triggered at deletion)
self.setTitleForUnsavedChanges()
def envsTableToDict(self):
"""
Convert environmental variable table to dictionary and return.
"""
# Clear the current data in currentModule
ret = {}
# Save current values in the table to dictionary
for row in range(self.envsTable.rowCount()):
if self.envsTable.item(row,0) and self.envsTable.item(row,1):
ret[self.envsTable.item(row,0).text()] = self.envsTable.item(row,1).text()
# Returm
return(ret)
def envsUpdateFromDB(self):
"""
Update environmental variable table from database ("currentModule" dictionary)
"""
# Clear current values
self.envsTable.clear()
# Reset table
keys = list(self.currentModule["envs"].keys())
self.envsTable.setHorizontalHeaderLabels(["Name", "Value"])
self.envsTable.setRowCount(len(keys))
# Add new entries
for row in range(len(keys)):
item = QTableWidgetItem(keys[row])
self.envsTable.setItem(row, 0, item)
item = QTableWidgetItem(self.currentModule["envs"][keys[row]])
self.envsTable.setItem(row, 1, item)
def envsSaveToDB(self):
"""
Save environmental variable table to database ("currentModule" dictionary)
"""
# Save current values in the table to dictionary
self.currentModule["envs"] = self.envsTableToDict()
#============================================================
# Execution buttons methods
#============================================================
def genModKey(self):
"""
Generate module key for current form. Saving is not assumed.
"""
# Asked the user to select a directory
directory = QFileDialog.getExistingDirectory(self, 'Select Directory to Save Module Keys', self.config["defaultModKeyPath"])
# If a directory is successfully selected...
if directory:
# Try if the directory is writable:
# If writable, continue generating; if not, return False
try:
fw = tempfile.TemporaryFile(dir=directory)
except:
QMessageBox.critical(self, 'Error!', 'Failed! You do not have permission to write to this directory!')
return(False)
# Save a temporary module dict (allows exporting current module without saving)
tmpModule = {
"conflict": self.conflictText.text(),
"module_whatis": self.whatisText.text(),
"singularity_image": self.singularityImageText.text(),
"singularity_bindpaths": self.singularityBindText.text(),
"singularity_flags": self.singularityFlagsText.text(),
"cmds": self.cmdsText.toPlainText(),
"envs": self.envsTableToDict(),
"template": self.templateText.text()
}
# Create folder if not exist
pathModKey = f"{directory}/{self.nameDrop.currentText()}/{self.versionDrop.currentText()}"
dir = os.path.dirname(pathModKey)
if not os.path.exists(dir):
os.makedirs(dir)
# Export module file
with open(pathModKey, "w") as fw:
fw.write(self.retModKey(dictModule=tmpModule))
# Pop a successful message
QMessageBox.information(self, 'Success!', 'You have successfully generated the current module key!')
def genAllModKeys(self):
"""
Generate module keys for current database. Must save first.
"""
# Check any unsaved changes
if (self.cancelForUnsavedChanges()): return
# Asked the user to select a directory
directory = QFileDialog.getExistingDirectory(self, 'Select Directory to Save Module Keys', self.config["defaultModKeyPath"])
# If a directory is successfully selected...
if directory:
# Try if the directory is writable:
# If writable, continue generating; if not, return False
try:
fw = tempfile.TemporaryFile(dir=directory)
except:
QMessageBox.critical(self, 'Error!', 'Failed! You do not have permission to write to this directory!')
return(False)
# Loop over all modules in db to create module keys
for modName in self.db.keys():
# Then export all module keys
for modVersion in self.db[modName].keys():
# Create folder if not exist
pathModKey = f"{directory}/{modName}/{modVersion}"
dir = os.path.dirname(pathModKey)
if not os.path.exists(dir):
os.makedirs(dir)
# Export module file
with open(pathModKey, "w") as fw:
fw.write(self.retModKey(modName, modVersion, self.db[modName][modVersion]))
# Pop a successful message
QMessageBox.information(self, 'Success!', 'You have successfully generated all module keys from the current database!')
#============================================================
# Module key template
#============================================================
def retModKey(self, modName=None , modVersion=None, dictModule=None):
"""
Return module key from a template.
"""
# Default module name, version, and module dictionary to current if not given
modName = modName or self.nameDrop.currentText()
modVersion = modVersion or self.versionDrop.currentText()
dictModule = dictModule or self.currentModule
# Parse environmental variable dictionary into a single string
envsStr = ""
for key, value in dictModule["envs"].items():
envsStr += f"setenv {key} \"{value}\"\n"
# Set up module key template
with open(dictModule["template"]) as f:
tmpModKey = Template(f.read())
# Return formatted module key string based on the template
return tmpModKey.safe_substitute(
modName = modName,
#modNameCap = modName.upper(),
conflict = dictModule["conflict"],
whatis = dictModule["module_whatis"],
modVersion = modVersion,
singularity_image = dictModule["singularity_image"],
singularity_bindpaths = ",".join((self.config["defaultBindingPath"], dictModule["singularity_bindpaths"])),
singularity_flags = " ".join((self.config["defaultFlags"], dictModule["singularity_flags"])),
cmds_dummy = dictModule["cmds"],
envs = envsStr
)
#============================================================
# Misc
#============================================================
def loadPreferences(self):
"""
Load preferences from "~/.simple-modrc". Create the file if it does not exist.
"""
# Check if "~/.simple-modrc" exist.
# If exists, open and read preference settings.
# If not, create it with default settings.
if os.path.exists(os.path.expanduser('~/.simple-modrc')):
with open(os.path.expanduser('~/.simple-modrc')) as f:
self.config = json.load(f)
else:
self.config = {
"defaultBindingPath": "/work,/project,/usr/local/packages,/var/scratch",
"defaultFlags": "",
"defaultImagePath": "/project/containers/images",
"defaultTemplate": "./template/template.tcl",
"defaultModKeyPath": "./modulekey"
}
with open(os.path.expanduser('~/.simple-modrc'), "w") as fw:
json.dump(self.config, fw, indent=4)
def retEmptyModule(self):
"""
Return an empty module dictionary.
"""
return {
"conflict": "",
"module_whatis": "",
"singularity_image": "",
"singularity_bindpaths": "",
"singularity_flags": "",
"cmds": "",
"envs": { },
"template": self.config["defaultTemplate"]
}
def closeEvent(self, event):
"""
Exit SIMPLE-MOD.
"""
# Check any unsaved changes
if (self.cancelForUnsavedChanges()):
event.ignore()
def resizeEnvsColumns(self):
self.envsTable.setColumnWidth(0, int(0.28*self.envsTable.width()))
self.envsTable.setColumnWidth(1, int(0.68*self.envsTable.width()))
def resizeEvent(self, event):
self.resizeEnvsColumns()
super().resizeEvent(event)
def enableForm(self, isEnabled):
"""
Enable/Disable current module form.
"""
self.saveDBAct.setEnabled(isEnabled)
self.conflictText.setEnabled(isEnabled)
self.whatisText.setEnabled(isEnabled)
self.singularityImageText.setEnabled(isEnabled)
self.singularityImagePickerBtn.setEnabled(isEnabled)
self.singularityBindText.setEnabled(isEnabled)
self.singularityFlagsText.setEnabled(isEnabled)
self.cmdsText.setEnabled(isEnabled)
self.envsTable.setEnabled(isEnabled)
self.envsAddBtn.setEnabled(isEnabled)
self.envsDelBtn.setEnabled(isEnabled)
self.templateText.setEnabled(isEnabled)
self.templatePickerBtn.setEnabled(isEnabled)
self.copyBtn.setEnabled(isEnabled)
self.delBtn.setEnabled(isEnabled)
self.genBtn.setEnabled(isEnabled)
self.exportBtn.setEnabled(isEnabled)
def isDBChanged(self):
"""
Check if the database is changed (added / deleted module keys) from creation (new or open)
"""
return(self.flagDBChanged)
def isModKeyChanged(self):
"""
Check if the current form (module key) is changed from currentModule
"""