new file: main.py

new file:   packages/builtin.py
	new file:   packages/nano.py
	new file:   packages/netget.py
	new file:   packages/pakk.conf
This commit is contained in:
ousmblueninja 2023-08-26 20:31:40 -05:00
commit cb54be6887
12 changed files with 461 additions and 0 deletions

238
main.py Normal file
View File

@ -0,0 +1,238 @@
import json
import os
import sys
import importlib
from inspect import isfunction
import random
import time
import ast
import readline
import threading
class color:
green = "\033[1;32m"
blue = "\033[1;34m"
white = "\033[0m"
green = "\033[1;32m"
red = "\033[1;31m"
white = "\033[0m"
blue = "\033[1;34m"
orange = "\033[1;33m"
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
def call(full_module_name, func_name, *args, **kwargs):
module = importlib.import_module(full_module_name)
if func_name in dir(module):
for attribute_name in dir(module):
attribute = getattr(module, attribute_name)
if isfunction(attribute) and attribute_name == func_name:
attribute(*args, **kwargs)
else:
raise Exception("Command Not Found")
def getPrompt():
path = "USERNAME" if os.name == "nt" else "USER"
username = os.environ.get(path)
if username is None:
username = ""
path = os.getcwd()
# Set up tab completion for file and directory names
completer = readline.get_completer()
readline.set_completer_delims(' \t\n')
readline.parse_and_bind("tab: complete")
prompt = color.white + "" + color.green + username + color.white + ":" + color.blue + path + color.white + "\n└ $ "
return prompt
def getInput():
print(getPrompt(), end="")
return input()
def getIndex( packages:list, package: str) -> str:
for key in packages:
if packages[key] == package:
return key
def toList(List: str) -> list:
newList = ast.literal_eval(List)
if isinstance(newList, list):
return newList
class packages:
def __init__(self):
try:
with open(("./packages/pakk.conf"), "r") as f:
self.packages = toList(f.readline())
except Exception as e:
print(e)
self.packages = [["builtin", "packages.builtin", ["echo", "ls", "rm", "clear", "cd", "ll"]]]
self.update(self.packages)
def update(self, packages):
with open(("./packages/pakk.conf"), "w") as f:
f.write(str(packages))
Packages = packages()
class packagemanager:
def __init__(self, args):
if len(args) <= 1:
print("Options:\ninstall <package name> | installs package \nlist | lists installed packages\nremove <package name> | uninstall packages\navailable | lists available commands")
elif args[1] == "install":
self.install(args[2])
elif args[1] == "list":
self.list()
elif args[1] == "remove":
self.uninstall(args[2])
elif args[1] == "available":
self.commands("./packages")
else:
print("Options:\ninstall <package name> | installs package \nlist | lists installed packages\nremove <package name> | uninstall packages\navailable | lists available commands")
return
def commands(self, directory):
with os.scandir(directory) as entries:
for entry in entries:
if entry.name.endswith(".py"):
package_name = entry.name[:-3] # Remove the ".py" extension
if package_name not in [row[0] for row in Packages.packages]:
print(f"Package '{package_name}' is not installed.")
def install(self, name: str) -> int:
try:
print("Checking for package source.")
with open(("./packages/"+name+".py"), "r") as f:
f.close()
except FileNotFoundError:
raise Exception("Package could not be found, make sure package source is in [ packages ] folder.")
try:
if name in [row[0] for row in Packages.packages]:
raise Exception("Package already installed")
with open(("./packages/"+name+".py"), "r") as f:
line = f.readline()
line = line.strip("#")
# ... (existing code)
print("Installing Package")
Packages.packages.append(toList(line))
Packages.update(Packages.packages)
print(f"\n{color.green}Success:{color.white} Successfully installed {name}.")
except Exception as e:
raise Exception(e)
def list(self):
print("Installed Packages: \n"+ "\n".join([row[0] for row in Packages.packages]))
def uninstall(self, name:str):
#print(Packages.packages)
print(f"Uninstalling {name}")
for package in Packages.packages:
if name in package[0]:
Packages.packages.remove(package)
Packages.update(Packages.packages)
print(f"{color.green}Sucess:{color.white} Uninstalled {name}.")
#print(Packages.packages)
def handleCommands(command: list) -> list:
try:
if command[0] == "help":
print("Type pakk for more help installing packages" )
return [0,None]
if command[0] == "pakk":
try:
PackageManager = packagemanager(command)
except Exception as e:
print(e)
return [0,None]
except Exception as e:
raise Exception(e)
try:
ran = False
for package in Packages.packages:
if command[0] in package[2]:
call(package[1], command[0], command[1:])
ran = True
return [0,None]
return [1, 'Command not Found']
except Exception as e:
print(e)
return [1, "A Faital error has acured while running commmand"]
def main():
while True:
command = getInput()
if command == "":
pass
else:
command = command.split(" ")
error = handleCommands(command)
if error[0]==1:
print(f"{color.red}ERROR{color.white}:{color.red} {error[1]}{color.white}")
if __name__ == '__main__':
main()

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

128
packages/builtin.py Normal file
View File

@ -0,0 +1,128 @@
#["builtin", "packages.builtin", ["echo", "ls", "rm", "clear", "cd", "ll"]]
import os
import stat
import pwd
import grp
import time
def echo(message: list) -> int:
try:
print(" ".join(message))
except:
return
def ls(args):
del args
pass
def rm(files: list):
for file in files:
os.remove(file)
def clear(args):
del args
os.system('cls' if os.name == 'nt' else 'clear')
def cd(args):
if len(args) == 0 or args[0] == "~":
new_path = os.path.expanduser("~") # Get the home directory path
elif len(args) == 1:
new_path = os.path.abspath(args[0]) # Get the absolute path
else:
print("Usage: cd <path> or cd ~")
return
try:
os.chdir(new_path) # Change the current working directory
except FileNotFoundError:
print("Directory not found.")
except Exception as e:
print(f"An error occurred: {e}")
def ls(args):
del args # You can remove this line if you're not using args
blue_color = '\033[34m'
green_color = '\033[32m'
white_color = '\033[37m'
reset_color = '\033[0m'
dir_path = os.getcwd()
try:
with os.scandir(dir_path) as entries:
for entry in entries:
if not entry.name.startswith('.'):
file_path = os.path.join(dir_path, entry.name)
file_stat = os.stat(file_path)
if stat.S_ISDIR(file_stat.st_mode):
print(blue_color + entry.name + '/' + reset_color, end=' ')
elif file_stat.st_mode & stat.S_IXUSR:
print(green_color + entry.name + '*' + reset_color, end=' ')
else:
print(white_color + entry.name + reset_color, end=' ')
print() # Newline after listing
except Exception as e:
print(f"An error occurred: {e}")
def ll(args):
del args
dir_path = os.getcwd()
green_color = '\033[32m'
blue_color = '\033[34m'
whiteColor = '\033[37m'
orange_color = '\033[33m'
reset_color = '\033[0m'
try:
with os.scandir(dir_path) as entries:
for entry in entries:
file_stat = entry.stat()
file_name = entry.name
pw = pwd.getpwuid(file_stat.st_uid)
gr = grp.getgrgid(file_stat.st_gid)
is_hidden = (file_name and file_name[0] == '.')
time_str = time.ctime(file_stat.st_mtime)
if time_str.endswith('\n'):
time_str = time_str[:-1] # Remove newline character
permission_str = (
(green_color + "r" if file_stat.st_mode & stat.S_IRUSR else whiteColor + "-") +
(blue_color + "w" if file_stat.st_mode & stat.S_IWUSR else whiteColor + "-") +
((orange_color if is_hidden else green_color) + "x" if file_stat.st_mode & stat.S_IXUSR else whiteColor + "-") +
(green_color + "r" if file_stat.st_mode & stat.S_IRGRP else whiteColor + "-") +
(blue_color + "w" if file_stat.st_mode & stat.S_IWGRP else whiteColor + "-") +
((orange_color if is_hidden else green_color) + "x" if file_stat.st_mode & stat.S_IXGRP else whiteColor + "-") +
(green_color + "r" if file_stat.st_mode & stat.S_IROTH else whiteColor + "-") +
(blue_color + "w" if file_stat.st_mode & stat.S_IWOTH else whiteColor + "-") +
((orange_color if is_hidden else green_color) + "x" if file_stat.st_mode & stat.S_IXOTH else whiteColor + "-")
)
print(
"{:<11}{:>4} {:<8} {:<8} {:>8} {} {}{}".format(
permission_str,
file_stat.st_nlink,
pw.pw_name,
gr.gr_name,
file_stat.st_size,
time_str,
(blue_color if entry.is_dir() else (orange_color if is_hidden else green_color) if file_stat.st_mode & stat.S_IXUSR else whiteColor),
file_name,
reset_color
)
)
except Exception as e:
print(f"An error occurred: {e}")

71
packages/nano.py Normal file
View File

@ -0,0 +1,71 @@
#["nano", "packages.nano", ["nano"]]
import os
class TextEditor:
def __init__(self):
self.lines = []
self.file = ""
def load_file(self, filename):
try:
with open(filename, "r") as file:
self.lines = file.readlines()
except FileNotFoundError:
print(f"File '{filename}' not found.")
def save_file(self, filename):
if filename == "":
filename = self.file
with open(filename, "w") as file:
file.writelines(self.lines)
def edit(self):
while True:
os.system('cls' if os.name == 'nt' else 'clear')
self.display()
action = input("\nCommands: [e]dit, [n]ewline, [s]ave, [q]uit: ").lower()
if action == "e":
self.edit_lines()
elif action == "n":
self.newline()
elif action == "s":
filename = input("Enter filename to save: ")
self.save_file(filename)
print(f"File '{filename}' saved.")
elif action == "q":
print("Exiting the text editor.")
break
else:
print("Invalid command.")
def display(self):
print("Editing: "+self.file)
for i, line in enumerate(self.lines):
print(f"{i + 1}: {line}", end="")
def newline(self):
self.lines.append("\n")
def edit_lines(self):
line_number = int(input("Enter line number to edit: ")) - 1
if 0 <= line_number < len(self.lines):
new_line = input("Enter new text: ")
self.lines[line_number] = new_line + "\n"
else:
print("Invalid line number.")
def nano(args):
if len(args) != 1:
print("Usage: nano <filename>")
else:
os.system('cls' if os.name == 'nt' else 'clear')
filename = args[0]
editor = TextEditor()
editor.file = filename
editor.load_file(filename)
editor.edit()

23
packages/netget.py Normal file
View File

@ -0,0 +1,23 @@
#["netget", "packages.netget", ["netget"]]
# Made By OusmeBlueNinja
import os, sys
def netget(command: list):
print(command, len(command))
if len(command) != 2:
print("comand requires [ url ] [ path ]")
url = command[0]
location = command[1]
try:
import wget
wget.download(url, location)
except ImportError:
os.system(f"wget {url} -O {location}")
except:
print("cannot download")

1
packages/pakk.conf Normal file
View File

@ -0,0 +1 @@
[['builtin', 'packages.builtin', ['echo', 'ls', 'rm', 'clear', 'cd', 'll']], ['nano', 'packages.nano', ['nano']]]