Skip to content
This repository has been archived by the owner on Mar 27, 2021. It is now read-only.

Commit

Permalink
Merge pull request #2 from fabiopolancoe/Dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
fabiopolancoe authored Nov 17, 2020
2 parents 279c8bb + 4d7ff2f commit a2c222b
Show file tree
Hide file tree
Showing 7 changed files with 295 additions and 55 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ celerybeat.pid
*.sage.py

# Environments
.env
.venv
env/
venv/
Expand Down Expand Up @@ -140,4 +141,4 @@ dmypy.json
.pytype/

# Cython debug symbols
cython_debug/
cython_debug/
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,17 @@
A simple terminal **simulator** written in Python3.

## Setup
- The only dependence of this project is [**DotEnv**](https://pypi.org/project/dotenv/) module.
- There are some optional dependencies:
- Nano Editor
- IPython3
- [**DotEnv**](https://pypi.org/project/python-dotenv/)
- [**Art**](https://pypi.org/project/art/) module

- pip3

## Usage
Run the _main.py_ file, you can execute `python3 main.py` on Linux/MacOS or `python main.py` on Windows.
We recommend to run `setup.py` script before using the program. But you can also run the program en then execute the `install` command.
To run the program, you can execute `python3 main.py` on Linux/MacOS or `python main.py` on Windows.
You will see the ASCII Art Text logo, a welcome message and the prompt, to get started, type _help_.

## Making apps
Expand All @@ -23,4 +26,4 @@ I decided to make it easier for users to create their own apps for FakeOS, just
## Files
There's a folder named home, where all the files of the "user" are saved by default, you can edit apps.py to use another folder.

Thanks to @KelviNosse for his feedback. And also thanks to @FRostri and @Sebastian-byte for their collaboration
Thanks to @KelviNosse for his feedback. And also thanks to @FRostri, @Sebastian-byte and @SuajCarrot for their collaboration
108 changes: 73 additions & 35 deletions apps.py
Original file line number Diff line number Diff line change
@@ -1,78 +1,116 @@
#!/usr/bin/env/ python3

# Apps module originally created by Sebastian-Byte, FabioPolancoE and FRostri
# Edited by Suaj

import os
import subprocess
import sys
import setup
import subprocess
from random import randint
from dotenv import load_dotenv


load_dotenv()

all_commands = {"hello": "A simple command that prints 'Hello World!'", "numguess": "An awesome Guess-The-Number Game", "ls": "Lists all the files and directories inside the home folder", "new": "Creates a new file, use with 'new [filename]', i.e 'new hi.txt', do never use whitespace.", "show": "Prints the contents of a file", "help": "Shows information about a available commands", "exit": "Stops the execution of FakeOS", "pyshell": "Opens an embedded python3 shell", "pyrun": "Executes a python3 file, place the file inside the home folder and type 'pyrun [filename]', i.e. 'pyrun hello.py'", "interactive": "Opens an interactive python3 shell, requires 'ipython' installed", "edit": "Edit or create files, type 'edit [filename]', i.e. 'edit note.txt', requires 'nano' installed"}
# Each command's description
all_commands = {"hello": "A simple command that prints 'Hello World!'",
"numguess": "An awesome Guess-The-Number Game",
"ls": "Lists all the files and directories inside the home folder",
"new": "Creates a new file, use with 'new [filename]', i.e 'new hi.txt', do never use whitespace.",
"show": "Prints the contents of a file",
"help": "Shows information about a available commands",
"exit": "Stops the execution of FakeOS",
"pyshell": "Opens an embedded python3 shell",
"pyrun": "Executes a python3 file, place the file inside the home folder and type 'pyrun [filename]', i.e. 'pyrun hello.py'",
"interactive": "Opens an interactive python3 shell, requires 'ipython3' installed",
"edit": "Edit or create files, type 'edit [filename]', i.e. 'edit note.txt', requires a text editor installed",
"install": "Activates setup script",
"clear": "Clears the console"}

# Definition of the commands
def hello():
print("Hello World!")
print("Hello, World!")

def numguess():
number = randint(1, 10)
guess = int(input("I'm thinking a number from 1 to 10, try to guess it > "))

if guess == number:
print("¡Wow, you did it! :D")
else:
print("Bad luck, you failed D:")
while True:
guess = int(input("I'm thinking of a number between 1 and 10, try\
to guess it...\n"))
if guess == number:
print("Wow, you did it! :D")
break
else:
print("Oops! that isn't the number I'm thinking of D:")

def ls():
home = os.listdir("./home")

if home:
for element in home:
print(element+"\n")
else:
print("Home is empty, fill it with anything you want :D")
for i in home:
print(i)
elif not home or len(home) == 0:
print("The home folder is empty.")

def new(filename):
if sys.platform == 'win32':
os.system("type nul > " + ".\\home\\" + filename)
if sys.platform.startswith("win32"):
os.system(f"type nul > ./home/{filename}")
else:
subprocess.call(["touch", "./home/" + filename])
subprocess.call(["touch", f"./home/{filename}"])

def show(filename):
if sys.platform == 'win32':
os.system('type ' + '.\\home\\' + filename)
else:
subprocess.call(["cat", "./home/" + filename])
with open(f"./home/{filename}", "r") as f:
fcontent = f.readlines()
for i in fcontent:
print(i, end='') # Each line already has the \n char at the end

def help(*method):
def help(method=False):
if method:
print(all_commands.get(method[0]))
print(all_commands[method])
else:
print("Running 'help' will print data about all commands, if you want info about only one command, type 'help [command]', i.e. 'help hello'\n")
for command in all_commands.keys():
print(command+": "+all_commands.get(command)+"\n")
print("All available commands:\n")
for i in all_commands.keys():
print(f"{i}: {all_commands[i]}\n")

def pyrun(filename):
if sys.platform == 'win32':
subprocess.call(["python", filename])
if sys.platform.startswith("win32"):
os.system(f"python {filename}")
else:
subprocess.call(["python3", filename])

def pyshell():
print("")
if sys.platform == 'win32':
subprocess.call("python")
if sys.platform.startswith("win32"):
os.system("python")
else:
subprocess.call("python3")
print("")

def interactive():
print("")
if sys.platform == 'win32':
subprocess.call('ipython')
if sys.platform.startswith("win32"):
os.system('ipython')
else:
subprocess.call("ipython3")
print("")

def edit(filename):
editor = os.getenv("TEXT_EDITOR")
subprocess.call([editor, "./home/" + filename])
try:
editor = os.getenv("EDITOR")
if sys.platform.startswith("win32"):
os.system(f"{editor} {filename}")
else:
subprocess.call([editor, filename])
except: # There should be an specific exception here
if sys.platform.startswith("win32"):
os.system(f"start notepad.exe {filename}")
else:
subprocess.call(["nano", f"./home/{filename}"])

def clear():
if sys.platform.startswith("win32"):
os.system("cls")
else:
subprocess.call(["tput reset"])

def install():
print("Setup is not available for now, I'm working on it, sorry D:")
setup.start()
79 changes: 79 additions & 0 deletions logs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
#!usr/bin/env python3

# Logging module, originally created by Suaj commited for FakeOS

import os.path
from datetime import datetime, date


# The only purpose of this function is to save some lines in the main file
def ask_for_logging():
while True:
log_conf = input("Do you want to create log files about the\
program's excecution? [Y/n/exit]\n")
if log_conf.lower() in ("y", "yes", "1"):
return True
elif log_conf.lower() in ("n", "no", "2", "0"):
return False
elif log_conf.lower() == "exit":
print("Exiting...")
exit()
else:
print("Please enter a valid option.")

# When the user turns off logging, we simply convert every call to the
# functions into nothing so we don't have to change the code.
class Logging:
def __init__(self, conf, verbose=False, path=f"{date.today()} Log.txt"):
self.conf = conf
if self.conf:
self.verbose = verbose
self.path = path

self.header = "This file was generated by FakeOS on\
{} at {}.\n\n".format(date.today(), datetime.now().strftime("%H:%M:%S"))

if os.path.isfile(self.path):
with open(self.path, "r+") as self.file:
self.file.seek(0)
self.file_content = self.file.readline()
# Write the header, if the file is empty
if len(self.file_content) == 0:
self.file.writelines(self.header)

else: # Create the file and apply the header
with open(self.path, "w") as self.file:
self.file.writelines(self.header)
else:
pass

# Log the given text to a file
# The last parameter allows us to individually control the printing
# regardless of the "verbose" option earlier.
# Errorlvl has a default value because most logs are about information
def log(self, text, errorlvl=0, printlog=False):
if self.conf:
self.text = text
self.errorlvl = errorlvl

# UERROR = User Error. Errorlvl is just playing with the index
self.errorlvls = ("INFO", "UERROR", "ERROR", "FATAL ERROR")
self.errorlvl = self.errorlvls[self.errorlvl]

with open(f"{self.path}", "a", encoding="utf-8") as self.file:
self.text2file = "{} - {}: {}\n".format(
datetime.now().strftime("%H:%M:%S"), self.errorlvl,
self.text)
self.file.writelines(self.text2file)
if self.verbose or printlog:
print(self.text)
else:
pass

# Debug
if __name__ == "__main__":
log = Logging(ask_for_logging(), verbose=True)
log.log("Normal log")
log.log("User error log", 1)
log.log("Oops log", 2)
log.log("UH OH", 3)
43 changes: 27 additions & 16 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
#!/usr/bin/env python3

# Main module, originally created by FabioPolancoE
# Edited by Suaj

import signal

# Print the name, if the text2art module is found.
try:
from art import text2art
print(text2art("FakeOS"))
except:
except ModuleNotFoundError:
pass

print("Welcome to FakeOS!")
from getpass import getuser # To get the current PC user.

print("Welcome to FakeOS!") # Welcome message, printed always.


def signal_handler(signal, frame):
Expand All @@ -17,35 +23,40 @@ def signal_handler(signal, frame):


def handle_command(data):
'''Handles the command the user entered. If the command is not
processed for any reason, the function returns False.'''
if data:
method = data[0]
del data[0]

if method == "exit":
sure = input("Do you really want to logout? [Y/N] ")
if sure == "Y" or sure == "y":
print("Bye ;D!")
if method.lower() == "exit":
sure = input("Do you really want to log out? [Y/n]: ")
if sure.lower() in ["y", "yes"]:
print("Bye! ;D")
quit()
elif sure == "N" or sure == "n":
return

elif sure.lower() in ["n", "no", "nope"]:
return False
else:
print("You haven't chosen a correct option. Canceling logout...")
return
print("You did not choose a correct option.")
return False
else:
import apps
try:
if data:
eval("apps." + method+"(*data)")
eval("apps." + method + "(*data)")
return True
else:
eval("apps." + method)()
return True
except:
print("Couldn't handle that command D:")
return
return False
else:
pass

return False
signal.signal(signal.SIGINT, signal_handler)

# User input
while True:
command = input("FOS > ")
command = input(f"[{getuser()}@FakeOS]$ ")
handle_command(command.split())

Loading

0 comments on commit a2c222b

Please sign in to comment.