-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspark
970 lines (873 loc) · 27.4 KB
/
spark
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
#!/usr/bin/python3
import os
import glob
import sys
import tarfile
import subprocess
import platform
import requests
from pathlib import Path
from itertools import cycle
from shutil import get_terminal_size
from threading import Thread
from time import *
from pkg import packager
#
# ==============================================
# MERROR
# ==============================================
#
point = "•"
class merrors:
def __init__(self):
self.errors = []
def error(self, msg):
print("\u001b[31m", point, f"[ERROR] {msg}")
self.errors += ["Error", msg, time.strftime("%H:%M:%S", time.localtime())]
def bigpanik(self):
print("\u001b[31m", point,
f"[PANIC] The program could not handle the request")
self.errors += ["Panic", time.strftime("%H:%M:%S", time.localtime())]
def getall(self):
return self.errors
#USAGE
#error("Could not load anything oopsie")
#
# ==============================================
# LOADER
# ==============================================
#
class Loader:
def __init__(self, desc="Loading...", end="Done!", timeout=0.1):
"""
A loader-like context manager
Args:
desc (str, optional): The loader's descrpition. Defaults to "Loading...".
end (str, optional): Final print. Defaults to "Done!".
timeout (float, optional): Sleep time between prints. Defaults to 0.1.
"""
self.desc = desc
self.end = end
self.timeout = timeout
self._thread = Thread(target=self._animate, daemon=True)
self.steps = ["⢿", "⣻", "⣽", "⣾", "⣷", "⣯", "⣟", "⡿"]
self.done = False
def start(self):
self._thread.start()
return self
def _animate(self):
for c in cycle(self.steps):
if self.done:
break
print(f"\r{self.desc} {c}", flush=True, end="")
sleep(self.timeout)
def __enter__(self):
self.start()
def stop(self):
self.done = True
cols = get_terminal_size((80, 20)).columns
print("\r" + " " * cols, end="", flush=True)
print(f"\r{self.end}", flush=True)
def __exit__(self, exc_type, exc_value, tb):
# handle exceptions with those variables ^
self.stop()
#
# ==============================================
# Ezconf
# ==============================================
#
import json
import re
class ezconfig:
def __init__(self):
self.filename = ""
self.datajson = None
def read(self,filename):
"""
Reads the config file and saves the values
:return:
"""
try:
with open(str(filename),"r") as f:
data = f.read()
#check if the loaded file is json
try:
datajson = json.loads(data)
except Exception as e:
print('could not load '+str(filename)+', add a basic entry to the config like {"name":"Example"}. Python error: '+str(e))
return 1
self.datajson = datajson
self.filename = filename
f.close()
return 0
except:
return 1
def get(self,var,*args):
"""
Return a variable
:param var: variable to get
:return var_val:
"""
# colours
fail = "\u001b[31m"
reset = "\u001b[0m"
#update datajson
self.read(self.filename)
try:
var_val = self.datajson[str(var)]
if bool(args)!=False:
p = re.compile('(?<!\\\\)\'')
var_val = p.sub('\"', str(var_val))
return json.loads(str(var_val))[str(args[0])]
except Exception as e:
print(fail+"[1] "+reset+ "could not get variable ["+str(var)+"] does it exist in "+self.filename+"?\nPython error: "+str(e))
print(self.datajson)
quit()
if var_val == None:
print(fail+"[2] "+reset+ "could not get variable ["+str(var)+"]. It equals to None, is there a python problem?")
quit()
else:
return var_val
def update(self,var,*args):
"""
Update a variable
:param var: variable to update
"""
#update datajson
self.read(self.filename)
try:
self.datajson[str(var)] = str(args[0])
except Exception as e:
merrors.error("could not update variable, does it exist? Did you parse a new value? Python error: "+str(e))
jsonFile = open(str(self.filename), "w+")
jsonFile.write(json.dumps(self.datajson))
jsonFile.close()
def update_all(self):
"""
Update all
"""
jsonFile = open(str(self.filename), "w+")
jsonFile.write(json.dumps(self.datajson))
jsonFile.close()
def pretty(self):
"""
Return pretty print
:return prettyprint:
"""
#update datajson
self.read(self.filename)
try:
return json.dumps(self.datajson, indent=4, sort_keys=True)
except Exception as e:
merrors.error("could not pretty print, did you load the config? Python error: "+str(e))
quit()
def nested(self,main,name,var):
self.read(self.filename)
tmp = []
try:
old_nested = self.get(str(main))
except Exception as e:
merrors.error("could not create a nested value, does the main value exist? Python error: "+str(e))
quit()
for elem in old_nested:
tmp.append(elem)
tmp.append({str(name):str(var)})
self.datajson[str(main)] = tmp
file = open(str(self.filename), "w")
json.dump(self.datajson,file)
file.close()
def add(self,name,var):
file = open(str(self.filename), "w")
self.datajson[str(name)] = str(var)
json.dump(self.datajson,file)
file.close()
#
# ==============================================
# Styling
# ==============================================
#
# Setup path and style_file
src = os.path.dirname("~/.config/spark/")
style_file = os.path.join(src, 'style')
rc_file = os.path.join(src, 'sparkrc')
# Setup ezconf
global style
style = ezconfig()
style.read(os.path.expanduser(style_file))
# Colours
RESET = '\033[0m'
def get_color(tuple, background=False):
r,g,b = tuple
return '\033[{};2;{};{};{}m'.format(48 if background else 38, r, g, b)
def hex_to_rgb(hex):
hex = hex.replace('#', '')
return tuple(int(hex[i:i+2], 16) for i in (0, 2, 4))
# *boss music plays*
#
# ==============================================
# Spark
# ==============================================
#
# Path (made vars so easy to manage)
checkfile = "/usr/spark/spark.check"
dimensions_cfg = "/usr/spark/dimensions/dimensions.config"
# Colours:
reset = "\u001b[0m"
valid = "\u001b[32m"
fail = "\u001b[31m"
# Paths
def dirs(sudo):
try:
with open(checkfile ,"r") as f:
f.read()
return 0
except:
os.system("mkdir -p /usr/spark" )
os.system("mkdir -p /usr/spark/tmp" )
os.system("mkdir -p /usr/spark/packs && touch /usr/spark/packs/installed && touch /usr/spark/spark.check && chmod 777 /usr/spark/packs/installed" )
os.system("mkdir -p /usr/spark/dimensions && touch /usr/spark/dimensions/dimensions.config" )
os.system("mkdir -p /usr/spark/installed/_local" )
return 1
# Help command
def help():
print("""
Spark - a simple package manager for IgniteOS
Welcome to spark, the following package manager is in beta and will not work as intended until a stable release is finished.
Usage:
\t spark < -i / install > <package name> = Installs a package
\t spark < -l / list > = Shows installed packages
\t spark < -d / dimension > = Adds dimension
\t spark < -u / update > <package name> = Updates sources
\t spark < -ls / list-sources > = Shows available sources
\t spark < -ci / installed > = Shows intalled packages
\t spark < -up / upgrade > = Upgrades spark
""")
# Get dimensions information
# this is not a dic joke :kek:
sample_dim = ("""
{
"name":"dimensions_config",
"sources":[{
"name":"spark_official",
"url":"https://sparkofficial.ubuntulove2004.repl.co/",
"date":"",
"packs":[
"none"
]
}]
}""")
def dim():
dimensions = ezconfig()
try:
exit_code = dimensions.read("/usr/spark/dimensions/dimensions.config")
if exit_code == 1:
with open("/usr/spark/dimensions/dimensions.config","w+") as f:
f.write(sample_dim)
return "No dimensions set, fixing... "+valid+"fixed!"+reset
return 0
except Exception as e:
return e
# Update dimensions information
def up_dim(silent=False):
dimensions = ezconfig()
try:
# dimensions_cfg: /usr/spark/dimensions/dimensions.config
exit_code = dimensions.read(dimensions_cfg)
if exit_code == 1:
return 1
else:
for source in dimensions.get('sources'):
if not silent:
print("Updating "+source['name']+" on "+source['url']+"... ",end='')
try:
r = requests.get(source['url']+'/packs')
source['packs'] = r.json()
#print(source)
dimensions.update_all()
if not silent:
print(valid+"✔"+reset)
except Exception as e:
print("Failed to update ",source['name'],"reason:",e,fail+"\nPerhaps run as root?")
return 1
return 0
except Exception as e:
return e
# Checks before install
def run_checks():
print("Checking paths... ",end="")
exit_code = dirs(sudo)
if exit_code == 0:
print(valid+"✔"+reset)
else:
print(fail+"✕ - Created paths"+reset)
print("Checking dimensions... ",end="")
exit_code = dim()
if exit_code == 0:
print(valid+"✔"+reset)
else:
print("\nDimensions file not found? Please run: \n\tspark update\n")
print(fail+"✕ - "+str(exit_code)+reset)
quit()
# Update
def update(silent=False):
if not silent:
print("Checking for dimensions file... ",end="")
exit_code = dim()
if exit_code == 0:
if not silent:
print(valid+"✔"+reset)
else:
if not silent:
print(fail+"✕ - "+str(exit_code)+reset)
quit()
else:
quit()
if not silent:
print("Updating dimensions file... ")
exit_code = up_dim(silent=True)
if exit_code == 0:
if not silent:
print(valid+"Updated All ✔"+reset)
else:
if not silent:
print(fail+"Failed to Update ✕"+reset)
quit()
# Find package
def find_pkg(name,dimensions, spec_ver=None):
for source in dimensions.get('sources'):
for pack in source['packs']:
if name.lower() == pack['name'].lower():
if spec_ver:
if spec_ver == pack['version']:
return pack
else:
for version in pack['altver']:
if version == spec_ver:
pack['altver'][version]['version'] = version
return pack['altver'][version]
else:
return pack
return None
# Install
def install(package,force=False, spec_ver=None):
dimensions = ezconfig()
# check if it exists
print("Reading dimensions file... ",end="")
exit_code = dimensions.read("/usr/spark/dimensions/dimensions.config")
if exit_code == 0:
print(valid+"✔"+reset)
else:
print(fail+"✕ - "+str(exit_code)+reset)
quit()
print("Checking if package is installed... "+valid+"✔"+reset)
#print(get_local_version(package))
#nput()
if spec_ver == None:
if not force:
if check_installed(package):
pack = find_pkg(package,dimensions)
if str(pack['version']) != str(get_local_version(package)):
print("Package is installed but a new version is available")
elif str(pack['version']) == str(get_local_version(package)):
print("Package is already installed at the version",get_local_version(package))
print("Repo latest is",pack['version'])
quit()
else:
print("Package is installed to the latest recommended version")
else:
print("You are about to install a specific version:",spec_ver)
print("Preparing to install",package,"..."+valid+"✔"+reset)
pack = find_pkg(package,dimensions,spec_ver=spec_ver)
if pack == None:
print("No candidates with the name",package)
quit()
if 'depends' not in pack:
deps = None
predeps = "none"
dep_missing = False
inst=False
inst_list = []
else:
deps = [] # unused var?
predeps = pack['depends']
inst=False
inst_list = []
dep_missing = False
for dep in predeps:
#print("dep in predeps 1 loop:",dep)
if '==' in dep:
#print("custom version")
tempdep = find_pkg(dep.split('==')[0].lower(),dimensions,spec_ver=dep.split('==')[-1])
else:
tempdep = find_pkg(dep.lower(),dimensions)
#print(tempdep)
if tempdep != None:
if 'depends' in tempdep:
if tempdep['depends'] != "none":
if type(tempdep['depends']) is str:
predeps.append(tempdep['depends'])
elif type(tempdep['depends']) is list:
for dep in tempdep['depends']:
#print(dep)
if not dep in predeps:
predeps.append(dep)
else:
print("Dependency {} was not found?".format(dep))
dep_missing = True
if check_installed(dep.split('==')[0].lower()):
inst=True
inst_list.append(dep)
if dep_missing:
print("One or more dependencies are not present in your sources. Refusing to install...")
quit()
print(valid)
print("Name:",package)
if get_local_version(package) != False:
print("Version:",pack['version'],"({} is installed)".format(get_local_version(package)))
else:
print("Version:",pack['version'])
print("Size:",pack['size'],"mb - upon installation")
print("Depends on:",predeps)
if inst:
print("Dependencies that are present:",inst_list)
print(reset)
inp = input("Install? [y/n] ")
if inp in ['Y', 'y']:
if 'depends' in pack:
if pack['depends']:
predeps.reverse()
for dep in predeps:
if check_installed(dep.split('==')[0].lower()) and not force:
print("installed already")
else:
if '==' in dep:
dpack = find_pkg(dep.split('==')[0].lower(),dimensions,spec_ver=dep.split('==')[-1])
#print("need",dep.split('==')[0].lower(),"at",dep.split('==')[-1])
spec_ver = dep.split('==')[-1]
dep = dep.split('==')[0].lower()
spec = True
else:
dpack = find_pkg(dep,dimensions)
spec = False
#print(dpack)
if dpack == None:
print("Could not install {} :/".format(dep))
quit()
local = get_src(dpack['url'],dep,dpack['version'])
###
### modify for new packages (Artur)
###
unpack(dep,local)
build(dep,dpack['build'])
#print(dep,dpack)
if spec:
add_installed(dep,spec_ver=spec_ver)
else:
add_installed(dep)
#input()
if 'url' in pack:
local = get_src(pack['url'],package,pack['version'])
unpack(package,local)
build(package,pack['build'])
else:
print("Detected a test package! Skipping download. Building...")
build(package,pack['build'],test=True)
return False
return True
return False
###
###
###
# Uninstall
def uninstall(package,force=False):
installed = ezconfig()
installed.read("/usr/spark/installed.json")
ver = None
for pack in installed.get('packages'):
if pack == package:
ver = installed.get('packages')[package]['version']
print("Found",package,"version",ver," "+valid+"✔"+reset)
print("Locating in ~/.local/_dist/"+package,end="... ")
ver_found = True
if ver == None:
print("Failed to locate package")
quit()
ver_found = False
### What the fuck is the code below
#print('~/.local/_dist/'+package)
# if test -d ~/.local/_dist/emacs; then echo "exist"; fi
#a= os.popen('whoami').read()
#print(a)
#os.system('whoami')
if "y" in os.popen(f'if test -d ~/.local/_dist/{package}; then echo "y"; fi ').read():
print(valid+"✔"+reset)
# Fuckery here
'''
cd $HOME/.local
for file in $(tar tzf package.tgz | grep -v '/$'); do
rm -f "$file"
done
'''
#os.system("cd /root/.local/_dist/"+package+"/ && ls")
txt = glob.glob("/root/.local/_dist/"+package+"/*.tar*")
for tar in txt:
os.system("rm -rf "+tar)
try:
path_dir = glob.glob("/root/.local/_dist/"+package+"/"+package+"*")[0]
except:
print(fail+"Can't locate package source but directory is present?"+reset)
if ver_found:
print("If you manually removed the package,\nwould you like to remove it's entry?")
c = input("Remove? [Y/N] ")
if c in ['Y', 'y']:
return True
else:
return False
quit()
#print(path_dir)
#quit()
make_dir = glob.glob(path_dir+"/Makefile*")[0]
#print(make_dir)
with open(make_dir) as file:
make = file.read()
if "uninstall" in make:
#print("Makefile has uninstall!")
c = input("Uninstall? [Y/N] ")
if c in ['Y', 'y']:
os.system("cd "+path_dir+" && make uninstall")
return True
else:
return False
print(fail+"Can't locate package source but directory is present?"+reset)
print("If you manually removed the package,\nwould you like to remove it's entry?")
c = input("Remove? [Y/N] ")
if c in ['Y', 'y']:
return True
else:
return False
else:
print(fail+"✕"+reset)
if ver_found:
print(fail+"Package is installed but the source path is missing!"+reset)
print("If you manually removed the package,\nwould you like to remove it's entry?")
c = input("Remove? [Y/N] ")
if c in ['Y', 'y']:
return True
else:
return False
else:
print(fail+"Package is not installed!"+reset)
quit()
# Get package source
def get_src(uri,packname,version):
print("Checking if source is available locally ...",end=" ")
inst = glob.glob("/usr/spark/tmp/"+packname+"*")
if inst:
print(valid+"✔"+reset)
if version in inst[0]:
return "local"
print("Downloading source from ",uri,"...")
os.system("cd /usr/spark/tmp && rm -r "+packname+"* > /dev/null")
os.system("cd /usr/spark/tmp && wget -q "+uri)
return None
def unpack(packname,local):
os.system("cd /usr/spark/tmp")
if not local:
os.system("cd /usr/spark/tmp && tar xf "+packname+"*")
os.system("mkdir -p ~/.local/_dist")
os.system("rm -r ~/.local/_dist/"+packname)
os.system("mkdir -p ~/.local/_dist/"+packname)
def build(packname,buildinst,test=False):
buildinst = ' '.join(buildinst.split()).replace('\\','')
#print(buildinst)
if not test:
with Loader("Building... "):
os.popen("cd /usr/spark/tmp/"+packname+"* &&"+buildinst.replace('\t','').replace(' ',' ')).read()
# cd /usr/spark/tmp && sudo cp -r emacs* ~/.local/_dist/emacs
os.system("cd /usr/spark/tmp && cp -r "+packname+"* ~/.local/_dist/"+packname)
else:
os.system(buildinst)
def list_packs(pattern=None):
sources_count = 0
package_count = 0
dimensions = ezconfig()
dimensions.read("/usr/spark/dimensions/dimensions.config")
for source in dimensions.datajson['sources']:
sources_count += 1
found = False
print(fail+source['name']+reset,"has:")
for pack in source['packs']:
if pattern:
if pattern in pack['name']:
print(pack['name'],"version",pack['version'])
found = True
package_count+=1
else:
print(pack['name'],"version",pack['version'])
package_count +=1
if not found:
print("No matches in this source")
print(package_count,'packages available from',sources_count,'repos')
def get_version(name):
dimensions = ezconfig()
dimensions.read("/usr/spark/dimensions/dimensions.config")
for source in dimensions.datajson['sources']:
#print(fail+source['name']+reset,"has:")
for pack in source['packs']:
if pack['name'].lower() == name.lower():
return pack['version']
else:
#print(pack['name'],name,"no match")
continue
return False
def get_local_version(name):
installed = ezconfig()
installed.read("/usr/spark/installed.json")
try:
return installed.get('packages')[name.lower()]['version']
except KeyError:
return None
def list_sources():
dimensions = ezconfig()
dimensions.read("/usr/spark/dimensions/dimensions.config")
for source in dimensions.datajson['sources']:
print(valid+source['name']+reset)
def add_dimension(url):
dimensions = ezconfig()
print("Contacting source... ",end='')
r = requests.get(url+'/')
print(valid+"✔"+reset)
dimensions.read("/usr/spark/dimensions/dimensions.config")
print("Saving source... ",end='')
dimensions.datajson['sources'].append(r.json())
dimensions.update_all()
print(valid+"✔"+reset)
def add_installed(name,spec_ver=None):
dimensions = ezconfig()
# check if it exists
print("Reading dimensions file... ",end="")
exit_code = dimensions.read("/usr/spark/dimensions/dimensions.config")
if exit_code == 0:
print(valid+"✔"+reset)
else:
print(fail+"✕ - "+str(exit_code)+reset)
quit()
installed = ezconfig()
try:
exit_code = installed.read("/usr/spark/installed.json")
if exit_code == 1:
"First install?"
print("This is your first package installed using spark!")
print("No installed file, fixing... "+valid+"fixed!"+reset)
with open("/usr/spark/installed.json","w+") as f:
f.write("""
{
"packages":
{
"spark":{
"version":"0.0.0",
"source":"github.com/HUSKI3/Spark",
"depends":"none",
"altver":pain:{"a":"a"}
}
}
""")
except Exception as e:
print(e)
quit()
if name == "spark":
pack = {}
pack['version'] = spec_ver
pack['url'] = "https://github.com/HUSKI3/Spark"
else:
pack = find_pkg(name,dimensions,spec_ver)
packs = installed.get("packages")
#print(packs)
packs[name] ={
"version":pack['version'],
"source":pack['url']
}
#print(packs)
installed.update_all()
def remove_installed(name):
dimensions = ezconfig()
# check if it exists
print("Reading dimensions file... ",end="")
exit_code = dimensions.read("/usr/spark/dimensions/dimensions.config")
if exit_code == 0:
print(valid+"✔"+reset)
else:
print(fail+"✕ - "+str(exit_code)+reset)
quit()
installed = ezconfig()
pack = find_pkg(name,dimensions)
try:
exit_code = installed.read("/usr/spark/installed.json")
if exit_code == 1:
"First install?"
print("No packages are installed.")
except Exception as e:
print(e)
quit()
packs = installed.get("packages")
del packs[name]
installed.update_all()
print("Removed! "+valid+"✔"+reset)
def list_installed():
print("Reading... ",end="")
update_avail = False
installed = ezconfig()
exit_code = installed.read("/usr/spark/installed.json")
if exit_code == 0:
print(valid+"✔"+reset)
else:
print(fail+"✕ - "+str(exit_code)+reset)
quit()
#print(installed.get('packages'))
for package in installed.get('packages'):
# weird
pkg = installed.get('packages')[package]
#print(pkg)
if pkg['version'] != get_version(package) and get_version(package) != False:
print(valid+"[UPDATE]"+reset,package,"at",pkg['version']+", an update is available to",get_version(package))
update_avail = True
else:
print(package,"at",pkg['version'])
if update_avail:
print("Shard is recommended to update packages!")
def check_installed(name):
installed = ezconfig()
exit_code = installed.read("/usr/spark/installed.json")
if exit_code == 1:
print("Failed to read (installed.json), fixing... ",end='')
with open("/usr/spark/installed.json","w+") as f:
f.write("""
{
"packages":{
"spark":{
"version":"0.0.0",
"source":"github.com/HUSKI3/Spark",
"author":"HUSKI3",
"depends":"none"
}
}
}
""")
print(valid+"✔"+reset)
quit()
#print(installed.get('packages'))
for package in installed.get('packages'):
if name == package:
return True
return False
def list_versions(name):
dimensions = ezconfig()
dimensions.read("/usr/spark/dimensions/dimensions.config")
for source in dimensions.datajson['sources']:
#print(fail+source['name']+reset,"has:")
for pack in source['packs']:
if pack['name'].lower() == name.lower():
print('Package versions for:',pack['name'])
for bit in pack['altver']:
print('version|size')
print(bit,'\t',pack['altver'][bit]['size'])
def update_spark():
version = get_local_version("spark")
#print(version)
#quit()
response = requests.get("https://api.github.com/repos/HUSKI3/Spark/releases/latest")
sparky = response.json()
print(valid+f"======== {sparky['name']} ========\n"+reset+" Bringing life to your machine ;)")
print(valid+"Changes:\n"+reset+" "+sparky['body'])
print(valid+"Uploader: "+reset+sparky['assets'][0]['uploader']['login'])
if sparky['tag_name'] != version:
print(valid+"This is a new version!"+reset)
r = requests.get(f"https://github.com/HUSKI3/Spark/releases/download/{sparky['tag_name']}/spark")
if r.status_code != 200:
print("Failed to fetch version?")
print(r.text)
quit()
add_installed("spark",version)
os.system("cd /usr/spark/ && rm -r spark > /dev/null")
os.system(f"cd /usr/spark/ && wget -q https://github.com/HUSKI3/Spark/releases/download/{sparky['tag_name']}/spark && chmod +x spark")
#os.system("rm -r /bin/spark > /dev/null")
os.system("ln -sf /usr/spark/spark /bin/spark")
def checkPKG(argv):
update(silent=True)
print({
"installed":get_local_version(argv[-1]),
"latest":get_version(argv[-1])
})
def main(*argv):
# Check arguments
argv=argv[0]
global sudo
if "--no-sudo" in argv:
sudo = False
else:
sudo = True
if "-h" in argv or "help" in argv:
help()
elif "-i" in argv or "install" in argv:
#update(silent=True)
if "==" in argv[-1]:
#print(argv[-1])
pkg_name = argv[-1].split("==")[0]
pkg_ver = argv[-1].split("==")[1]
else:
pkg_name = argv[-1]
if "-r" in argv:
run_checks()
if install(pkg_name, force=True, spec_ver=pkg_ver):
add_installed(pkg_name,spec_ver=pkg_ver)
else:
run_checks()
if install(pkg_name):
add_installed(pkg_name)
elif "-ci" in argv or "installed" in argv:
#update(silent=True)
list_installed()
elif "-u" in argv or "update" in argv:
run_checks()
update()
elif "-up" in argv or "upgrade" in argv:
#run_checks()
update_spark()
elif "-d" in argv or "dimension" in argv:
run_checks()
add_dimension(argv[-1])
update(silent=True)
elif "-l" in argv or "list" in argv:
if '-q' in argv:
list_packs(pattern=argv[-1])
else:
list_packs()
elif "-un" in argv or "uninstall" in argv:
run_checks()
if uninstall(argv[-1]):
remove_installed(argv[-1])
elif "-c" in argv or "clean" in argv:
run_checks()
os.system("cd /usr/spark/tmp && rm -r *")
update(silent=True)
elif "-ls" in argv or "list-sources" in argv:
run_checks()
list_sources()
elif "-lv" in argv or "list-versions" in argv:
run_checks()
list_versions(argv[-1])
elif "-nv" in argv:
checkPKG(argv)
elif "-p" in argv:
packager(argv[-1])
elif "-dp" in argv:
packager(argv[-1], False)
elif "-cm" in argv:
if "-l" in argv:
packager(argv[-1], False, meta=True, longg=True)
else:
packager(argv[-1], False, meta=True)
else:
help()
if __name__ == "__main__":
main(sys.argv)