Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit175801a

Browse files
committed
Convert detect_os to python, add OS platform detection to ash
1 parentc2ce1a4 commit175801a

File tree

5 files changed

+130
-27
lines changed

5 files changed

+130
-27
lines changed

‎setup.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
importos.path
44
importsubprocess
55
importsys
6+
fromsrcimportdetect_os
67

78
is_efi=os.path.exists("/sys/firmware/efi")
89
use_other_iso=""# if using different iso to install target OS, use its id
@@ -17,8 +18,8 @@
1718
distro=sys.argv[3]
1819
distro_name=sys.argv[4]
1920
exceptIndexError:
20-
distro=subprocess.check_output(['./src/detect_os.sh','id']).decode('utf-8').replace('"',"").strip()
21-
distro_name=subprocess.check_output(['./src/detect_os.sh','name']).decode('utf-8').replace('"',"").strip()
21+
distro=detect_os.get_distro_id()
22+
distro_name=detect_os.get_distro_name()
2223

2324
ifdistro:
2425
ifuse_other_iso!="":

‎src/ashpk_core.py‎

Lines changed: 75 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,11 @@
1212
fromastimportliteral_eval
1313
fromconfigparserimportConfigParser,NoOptionError,NoSectionError
1414
fromfilecmpimportcmp
15-
fromos.pathimportexpanduser
1615
fromreimportsub
1716
fromshutilimportcopy
1817
fromtempfileimportTemporaryDirectory
19-
fromurllib.requestimporturlopen
2018
fromurllib.errorimportURLError,HTTPError
19+
fromurllib.requestimporturlopen
2120

2221
# Directories
2322
# All snapshots share one /var
@@ -35,13 +34,8 @@
3534
# /var/lib/ash(/fstree) : ash files, stores fstree, symlink to /.snapshots/ash
3635
# Failed prompts start with "F: "
3736

38-
distro=subprocess.check_output(['/usr/bin/detect_os.sh','id']).decode('utf-8').replace('"',"").strip()
39-
distro_name=subprocess.check_output(['/usr/bin/detect_os.sh','name']).decode('utf-8').strip()
40-
GRUB=subprocess.check_output("ls /boot | grep grub",encoding='utf-8',shell=True).strip()
4137
DEBUG=" >/dev/null 2>&1"# options: "", " >/dev/null 2>&1"
4238
URL="https://raw.githubusercontent.com/ashos/ashos/main/src"
43-
USERNAME=os.getenv("SUDO_USER")oros.getenv("USER")
44-
HOME=os.path.expanduser('~'+USERNAME)# type: ignore
4539

4640
# ------------------------------ CORE FUNCTIONS ------------------------------ #
4741

@@ -88,7 +82,6 @@ def ash_chroot_mounts(i, CHR=""):
8882

8983
# Update ash itself
9084
defash_update(dbg):
91-
dist=distro.split("_")[0]# Remove '_ashos"
9285
mode=stat.S_IXUSR|stat.S_IXGRP|stat.S_IXOTH
9386
withTemporaryDirectory(dir="/.snapshots/tmp",prefix="ashpk.")astmpdir:
9487
try:
@@ -425,9 +418,53 @@ def get_current_snapshot():
425418
withopen("/usr/share/ash/snap","r")ascsnap:
426419
returnint(csnap.read().rstrip())
427420

428-
# This function returns either empty string or underscore plus name of distro if it was appended to sub-volume names to distinguish
421+
defget_distro_id(path_prepend=""):
422+
distro_id=None
423+
whiledistro_id==None:
424+
ifos.path.exists(f"{path_prepend}/etc/lsb-release"):
425+
withopen(f"{path_prepend}/etc/lsb-release","r")astemp:
426+
forlineintemp.readlines():
427+
ifline.startswith("DISTRIB_ID="):
428+
distro_id=line.split('=')[1].lower().strip()
429+
break
430+
ifos.path.exists(f"{path_prepend}/etc/os-release"):
431+
withopen(f"{path_prepend}/etc/os-release","r")astemp:
432+
forlineintemp.readlines():
433+
ifline.startswith("ID="):
434+
distro_id=line.split('=')[1].lower().strip()
435+
break
436+
# otherwise loop through all files in /etc and check for "-release"
437+
foretcfinos.listdir("/etc"):# depth=1, hopefully just 1 file matches
438+
ifetcf.endswith("-release")andetcfnotin ("os-release","lsb-release"):
439+
distro_id=etcf.split('-')[0]
440+
break
441+
returndistro_id
442+
443+
defget_distro_name(path_prepend=""):
444+
distro_name=None
445+
whiledistro_name==None:
446+
ifos.path.exists(f"{path_prepend}/etc/lsb-release"):
447+
withopen(f"{path_prepend}/etc/lsb-release","r")astemp:
448+
forlineintemp.readlines():
449+
ifline.startswith("DISTRIB_DESCRIPTION="):
450+
distro_name=line.split('=')[1].strip()
451+
break
452+
ifos.path.exists(f"{path_prepend}/etc/os-release"):
453+
withopen(f"{path_prepend}/etc/os-release","r")astemp:
454+
forlineintemp.readlines():
455+
ifline.startswith("NAME="):
456+
distro_name=line.split('=')[1].strip()
457+
break
458+
# Last resort loop through all files in /etc and check for "-release"
459+
foretcfinos.listdir("/etc"):
460+
ifetcf.endswith("-release")andetcfnotin ("os-release","lsb-release"):
461+
distro_name=etcf.split('-')[0].capitalize()
462+
break
463+
returndistro_name
464+
465+
# This function returns either empty string or underscore plus name of distribution if it was appended to sub-volume names to distinguish
429466
defget_distro_suffix():
430-
if"ashos"indistro:
467+
ifdistroand"ashos"indistro:
431468
returnf'_{distro.replace("_ashos","")}'
432469
else:
433470
sys.exit(1)### REVIEW before: return ""
@@ -567,7 +604,6 @@ def install_live(pkg, snap=get_current_snapshot()):
567604

568605
# Install a profile from a text file
569606
definstall_profile(prof,snap,force=False,secondary=False,section_only=None):
570-
dist=distro.split("_")[0]# Remove '_ashos"
571607
ifnotos.path.exists(f"/.snapshots/rootfs/snapshot-{snap}"):
572608
print(f"F: Cannot install as snapshot{snap} doesn't exist.")
573609
elifos.path.exists(f"/.snapshots/rootfs/snapshot-chr{snap}"):# Make sure snapshot is not in use by another ash process
@@ -610,7 +646,6 @@ def install_profile(prof, snap, force=False, secondary=False, section_only=None)
610646

611647
# Install profile in live snapshot
612648
definstall_profile_live(prof,snap,force):
613-
dist=distro.split("_")[0]# Remove '_ashos"
614649
tmp=get_tmp()
615650
ash_chroot_mounts(tmp)
616651
print(f"Updating the system before installing profile{prof}.")
@@ -651,7 +686,7 @@ def is_pkg_installed(pkg, snap):
651686
else:
652687
returnNone
653688

654-
# List sub-volumes for the booteddistro only
689+
# List sub-volumes for the booteddistribution only
655690
deflist_subvolumes():
656691
os.system(f"btrfs sub list / | grep -i{get_distro_suffix()} | sort -f -k 9")
657692

@@ -920,7 +955,7 @@ def snapshot_config_edit(snap, skip_prep=False, skip_post=False):
920955

921956
# Get per-snapshot configuration options from /etc/ash.conf
922957
defsnapshot_config_get(snap):
923-
options= {"aur":"False","mutable_dirs":"","mutable_dirs_shared":""}# defaults here ### REVIEW This is notdistro-generic
958+
options= {"aur":"False","mutable_dirs":"","mutable_dirs_shared":""}# defaults here ### REVIEW This is not generic
924959
ifnotos.path.exists(f"/.snapshots/etc/etc-{snap}/ash.conf"):
925960
returnoptions
926961
withopen(f"/.snapshots/etc/etc-{snap}/ash.conf","r")asoptfile:
@@ -943,7 +978,7 @@ def snapshot_unlock(snap):
943978
defswitch_distro():
944979
whileTrue:
945980
map_tmp=subprocess.check_output("cat /boot/efi/EFI/map.txt | awk 'BEGIN { FS = "'"'" === "'"'" } ; { print $1 }'",shell=True).decode('utf-8').strip()
946-
print("Type the name of adistro to switch to: (type 'list' to list them, 'q' to quit)")
981+
print("Type the name of adistribution to switch to: (type 'list' to list them, 'q' to quit)")
947982
next_distro=input("> ")
948983
ifnext_distro=="q":
949984
break
@@ -966,7 +1001,7 @@ def switch_distro():
9661001
#break ### REVIEW
9671002
break
9681003
else:
969-
print("Invaliddistro!")
1004+
print("Invaliddistribution!")
9701005
continue
9711006

9721007
# Switch between /tmp deployments
@@ -1042,7 +1077,7 @@ def tmp_delete(secondary=False):
10421077
# Print out tree with descriptions
10431078
deftree_print(tree):
10441079
csnap=get_current_snapshot()
1045-
forpre,fill,nodeinRenderTree(tree,style=AsciiStyle()):# simpler tree style
1080+
forpre,fill,nodeinRenderTree(tree,style=AsciiStyle()):# simpler tree style # type: ignore
10461081
ifos.path.isfile(f"/.snapshots/ash/snapshots/{node.name}-desc"):
10471082
withopen(f"/.snapshots/ash/snapshots/{node.name}-desc","r")asdescfile:
10481083
desc=descfile.readline()
@@ -1120,7 +1155,7 @@ def tree_sync(tree, tname, force_offline, live):
11201155
post_transactions(snap_to)### IMPORTANT REVIEW 2023 - Moved here from the line immediately after first tree_sync_helper
11211156
print(f"Tree{tname} synced.")
11221157

1123-
# Sync tree helper function ### REVIEW might need to put it indistro-specific ashpk.py
1158+
# Sync tree helper function ### REVIEW might need to put it indistribution-specific ashpk.py
11241159
deftree_sync_helper(CHR,s_f,s_t):
11251160
os.system("mkdir -p /.snapshots/tmp-db/local/")### REVIEW Still resembling Arch pacman folder structure!
11261161
os.system("rm -rf /.snapshots/tmp-db/local/*")### REVIEW
@@ -1216,7 +1251,7 @@ def upgrade(snap, baseup=False):
12161251
elifsnap==0andnotbaseup:
12171252
print("F: Changing base snapshot is not allowed.")
12181253
else:
1219-
# prepare(snap) ### REVIEW Moved to adistro-specific function as it needs to go after setup_aur_if_enabled()
1254+
# prepare(snap) ### REVIEW Moved to adistribution-specific function as it needs to go after setup_aur_if_enabled()
12201255
# Default upgrade behaviour is now "safe" update, meaning failed updates get fully discarded
12211256
excode=upgrade_helper(snap)
12221257
ifexcode:
@@ -1263,10 +1298,28 @@ def yes_no(msg):
12631298
continue
12641299
returne
12651300

1301+
# Define variable
1302+
distro=get_distro_id()
1303+
distro_name=get_distro_name()
1304+
ifdistro:
1305+
dist=distro.split("_")[0]# Remove '_ashos"
1306+
else:
1307+
sys.exit("F: Operating system could not be detected!")
1308+
GRUB=subprocess.check_output("ls /boot | grep grub",encoding='utf-8',shell=True).strip()
1309+
USERNAME=os.getenv("SUDO_USER")oros.getenv("USER")
1310+
HOME=os.path.expanduser('~'+USERNAME)# type: ignore
1311+
12661312
# Main function
12671313
defmain():
1268-
ifos.geteuid()!=0:# TODO 2023 exception: Make 'ash tree' run without root permissions
1314+
# TODO 2023 exception: Make 'ash tree' run without root permissions
1315+
ifsys.platform.startswith("linux")andos.geteuid()!=0:
12691316
exit("sudo/doas is required to run ash!")
1317+
elifsys.platform.startswith("windows"):
1318+
print("TODO")
1319+
elifsys.platform.startswith("darwin"):
1320+
print("TODO")
1321+
elifsys.platform.startswith("cosmo"):
1322+
print("TODO")
12701323
else:
12711324
importer=DictImporter()# Dict importer
12721325
# isChroot = chroot_check() ### TODO
@@ -1405,7 +1458,7 @@ def main():
14051458
editconf_par.add_argument("--snap","--snapshot","-s",type=int,required=False,default=get_current_snapshot(),help="snapshot number")
14061459
editconf_par.set_defaults(func=snapshot_config_edit)
14071460
# Snapshot diff
1408-
diff_par=subparsers.add_parser("diff",aliases=['dif'],allow_abbrev=True,help='Show package diff between snapshots')
1461+
diff_par=subparsers.add_parser("diff",aliases=["dif"],allow_abbrev=True,help='Show package diff between snapshots')
14091462
diff_par.add_argument("snap1",type=int,help="source snapshot")
14101463
diff_par.add_argument("snap2",type=int,help="target snapshot")
14111464
diff_par.set_defaults(func=snapshot_diff)
@@ -1414,7 +1467,7 @@ def main():
14141467
unl_par.add_argument("--snap","--snapshot","-s",type=int,required=False,default=get_current_snapshot(),help="snapshot number")
14151468
unl_par.set_defaults(func=snapshot_unlock)
14161469
# Switch distros
1417-
switch_par=subparsers.add_parser("dist",aliases=["distro","distros"],allow_abbrev=True,help="Switch to anotherdistro")
1470+
switch_par=subparsers.add_parser("dist",aliases=["distro"],allow_abbrev=True,help="Switch to anotherdistribution")
14181471
switch_par.set_defaults(func=switch_distro)
14191472
# Switch to Windows (semi plausible deniability)
14201473
hide_par=subparsers.add_parser("hide",allow_abbrev=False,help="Hide AshOS and switch to Windows")

‎src/detect_os.py‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#!/usr/bin/env python3
2+
# Detect OS/distro id or name
3+
4+
importos
5+
6+
defget_distro_id(path_prepend=""):
7+
distro_id=None
8+
whiledistro_id==None:
9+
ifos.path.exists(f"{path_prepend}/etc/lsb-release"):
10+
withopen(f"{path_prepend}/etc/lsb-release","r")astemp:
11+
forlineintemp.readlines():
12+
ifline.startswith("DISTRIB_ID="):
13+
distro_id=line.split('=')[1].lower().strip()
14+
break
15+
ifos.path.exists(f"{path_prepend}/etc/os-release"):
16+
withopen(f"{path_prepend}/etc/os-release","r")astemp:
17+
forlineintemp.readlines():
18+
ifline.startswith("ID="):
19+
distro_id=line.split('=')[1].lower().strip()
20+
break
21+
# otherwise loop through all files in /etc and check for "-release"
22+
foretcfinos.listdir("/etc"):# depth=1, hopefully just 1 file matches
23+
ifetcf.endswith("-release")andetcfnotin ("os-release","lsb-release"):
24+
distro_id=etcf.split('-')[0]
25+
break
26+
returndistro_id
27+
28+
defget_distro_name(path_prepend=""):
29+
distro_name=None
30+
whiledistro_name==None:
31+
ifos.path.exists(f"{path_prepend}/etc/lsb-release"):
32+
withopen(f"{path_prepend}/etc/lsb-release","r")astemp:
33+
forlineintemp.readlines():
34+
ifline.startswith("DISTRIB_DESCRIPTION="):
35+
distro_name=line.split('=')[1].strip()
36+
break
37+
ifos.path.exists(f"{path_prepend}/etc/os-release"):
38+
withopen(f"{path_prepend}/etc/os-release","r")astemp:
39+
forlineintemp.readlines():
40+
ifline.startswith("NAME="):
41+
distro_name=line.split('=')[1].strip()
42+
break
43+
# Last resort loop through all files in /etc and check for "-release"
44+
foretcfinos.listdir("/etc"):
45+
ifetcf.endswith("-release")andetcfnotin ("os-release","lsb-release"):
46+
distro_name=etcf.split('-')[0].capitalize()
47+
break
48+
returndistro_name
49+

‎src/detect_os.sh‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ case $1 in
3535
esac
3636

3737
#if [ -z "${temp}" ]; then
38-
# echo "Your operating system/distro could not be detected" >/dev/null 2>&1
38+
# echo "F:Your operating system/distro could not be detected!" >/dev/null 2>&1
3939
# break
4040
#fi
4141

‎src/installer_core.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -214,9 +214,9 @@ def post_bootstrap(super_group):
214214
os.system(f"echo '{to_uuid(os_root)}' |{SUDO} tee /mnt/.snapshots/ash/part")
215215
os.system(f"{SUDO} cat ./src/ashpk_core.py ./src/distros/{distro}/ashpk.py > /mnt/.snapshots/ash/ash")
216216
os.system(f"{SUDO} chmod +x /mnt/.snapshots/ash/ash")
217-
os.system(f"{SUDO} cp -a ./src/detect_os.sh /mnt/.snapshots/ash/detect_os.sh")
217+
os.system(f"{SUDO} cp -a ./src/detect_os.py /mnt/.snapshots/ash/detect_os.py")
218218
os.system(f"{SUDO} ln -srf /mnt/.snapshots/ash/ash /mnt/usr/bin/ash")
219-
os.system(f"{SUDO} ln -srf /mnt/.snapshots/ash/detect_os.sh /mnt/usr/bin/detect_os.sh")
219+
# os.system(f"{SUDO} ln -srf /mnt/.snapshots/ash/detect_os.sh /mnt/usr/bin/detect_os.sh")
220220
os.system(f"{SUDO} ln -srf /mnt/.snapshots/ash /mnt/var/lib/ash")
221221
os.system(f"echo {{\\'name\\':\\'root\\',\\'children\\': [{{\\'name\\':\\'0\\'}}]}} |{SUDO} tee /mnt/.snapshots/ash/fstree")# Initialize fstree
222222
# Create user and set password

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp