-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.py
135 lines (111 loc) · 4.49 KB
/
command.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
import os
import shutil
import fnmatch
from datetime import datetime
class Executer:
def __init__(self):
self.shell_commands = [
"ls: List files and directories in the current directory.",
"ls -l: List files with detailed information.",
"ls -a: List all files, including hidden ones.",
"cd: Change the current directory.",
"du: Show disk usage of files and directories.",
"pwd: Print the current working directory.",
"man: Display the manual for a command.",
"rmdir: Remove an empty directory.",
"ln file1 file2: Create a physical link between files.",
"ln -s file1 file2: Create a symbolic (soft) link between files.",
"locate: Find a file by searching the file index.",
"echo: Print text to the terminal or a file.",
"df: Show available disk space on mounted filesystems.",
"tar: Archive files or extract files from an archive."
]
def execute(self, command):
command = command.strip().split()
# Case 1: Only 'ls' command (list files and directories)
if len(command) == 1:
if command[0] == "ls":
self.ls()
elif command[0] == "du":
self.du()
elif command[0] == "pwd":
self.pwd()
elif command[0] == "man":
self.man()
elif command[0] == "clear":
self.clear()
elif command[0] == "date":
self.date()
# Case 2: 'ls <folder_name>' (list contents of a specific folder)
elif len(command) == 2:
if command[0] == "ls":
self.ls_folder(command[1])
elif command[0] == "locate":
self.locate(pattern=command[1])
elif len(command) == 3:
if command[0] == "locate":
if os.path.exists(command[2]):
self.locate(pattern=command[1], path=command[2])
def ls(self):
"""List all files and directories in the current directory."""
path = os.getcwd()
with os.scandir(path) as it:
for entry in it:
if not entry.name.startswith('.'):
if entry.is_file():
print(entry.name)
elif entry.is_dir():
print(f"{entry.name} (folder)")
def du(self):
"""Show disk usage of files and directories."""
GB = 2**30 # to convert bytes to gigabytes
TOTAL, USED, FREE = shutil.disk_usage("/")
print(f" Total: {TOTAL/GB} GiB")
print(f" Used: {USED/GB} GiB")
print(f" Free: {FREE/GB} GiB")
def pwd(self):
"""Print the current working directory."""
print(os.getcwd())
def man(self):
"""Display the manual for available commands."""
for line in self.shell_commands:
print(f"\t{line}")
def clear(self):
"""Clear the terminal screen."""
os.system("clear")
def date(self):
"""Display the current date and time."""
print(f"Date: {datetime.now().date()}")
print(f"Time: {datetime.now().time()}")
def ls_folder(self, folder_name,):
"""List the contents of a specified folder."""
current_directory = os.getcwd()
folder_path = os.path.join(current_directory, folder_name)
# Check if the provided folder exists and is a directory
if os.path.isdir(folder_path):
print(f"Listing contents of directory: {folder_path}")
with os.scandir(folder_path) as it:
for entry in it:
if not entry.name.startswith('.'):
if entry.is_dir():
print(f"{entry.name} (folder)")
else:
print(entry.name)
else:
print(f"{folder_name} is not a valid directory or does not exist.")
def locate(self, pattern, path="C:\\"):
result = []
for root, dirs, files in os.walk(path):
try:
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
except PermissionError:
continue
if result:
for file in result:
print(file)
else:
print(f"No files matching '{pattern}' were found.")
def __call__(self):
pass