-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommandParser.cs
More file actions
229 lines (195 loc) · 7.55 KB
/
CommandParser.cs
File metadata and controls
229 lines (195 loc) · 7.55 KB
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
using Spectre.Console;
using System.Diagnostics;
namespace NShell.Shell.Commands;
/// <summary>
/// <c>CommandParser</c> class handles loading and execution of shell commands.
/// It supports custom commands, system commands, and privilege management (e.g., sudo).
/// </summary>
public class CommandParser
{
public static readonly Dictionary<string, ICustomCommand> CustomCommands = new();
public static readonly HashSet<string> SystemCommands = new();
private static readonly HashSet<string> InteractiveCommands = new()
{
"vim", "nano", "less", "more", "top", "htop", "man", "ssh", "apt"
};
/// <summary>
/// Constructor that loads the commands when the parser is instantiated.
/// </summary>
public CommandParser()
{
LoadCommands();
}
/// <summary>
/// Loads all the custom commands and system commands from predefined directories.
/// </summary>
private void LoadCommands()
{
foreach (var command in CommandRegistry.GetAll())
{
CustomCommands[command.Name] = command;
AnsiConsole.MarkupLine($"\t[[[green]+[/]]] - Loaded custom command: [yellow]{command.Name}[/]");
}
LoadSystemCommands();
var total = CustomCommands.Count + SystemCommands.Count;
AnsiConsole.MarkupLine(total > 0
? $"[bold grey]→ Total commands loaded:[/] [bold green]{total}[/]"
: $"[bold grey]→ Total commands loaded:[/] [yellow]{total}[/]");
}
/// <summary>
/// Loads system commands from typical binary directories.
/// </summary>
private void LoadSystemCommands()
{
var paths = new[] { "/usr/bin", "/usr/local/bin", "/usr/games", "/bin", "/sbin", "/usr/sbin" };
foreach (var dir in paths)
{
if (!Directory.Exists(dir)) continue;
foreach (var file in Directory.GetFiles(dir))
{
var cmd = Path.GetFileName(file);
if (!string.IsNullOrWhiteSpace(cmd))
{
SystemCommands.Add(cmd);
}
}
}
}
/// <summary>
/// Attempts to execute a command from the provided command line input.
/// Handles variable expansion, root privileges, and command execution.
/// </summary>
/// <param name="commandLine">The command line string entered by the user.</param>
/// <param name="context">The shell context that contains environment variables and the current directory.</param>
/// <returns>Returns true if the command was successfully executed, false otherwise.</returns>
public bool TryExecute(string commandLine, ShellContext context)
{
var expanded = context.ExpandVariables(commandLine);
var parts = expanded.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0) return false;
var usedSudo = parts[0] == "sudo";
if (usedSudo) parts = parts.Skip(1).ToArray();
if (parts.Length == 0) return false;
var cmdName = parts[0];
var args = parts.Skip(1).ToArray();
if (cmdName.StartsWith("./"))
{
return ExecuteLocalFile(commandLine);
}
if (CustomCommands.TryGetValue(cmdName, out var customCmd))
{
if (customCmd is IMetadataCommand meta && meta.RequiresRoot && !(usedSudo || IsRootUser()))
{
AnsiConsole.MarkupLine("[red][[-]] - This command requires root privileges. Prefix with [bold yellow]sudo[/] or run as root.[/]");
return true;
}
customCmd.Execute(context, args);
return true;
}
if (SystemCommands.Contains(cmdName))
{
var fullPath = ResolveSystemCommandPath(cmdName);
if (fullPath != null)
{
RunSystemCommand(fullPath, args, usedSudo);
if ((cmdName == "apt" || cmdName == "apt-get") && args.Length > 0 && args[0] == "install")
{
CommandLoader.RefreshCommands();
}
return true;
}
}
AnsiConsole.MarkupLine($"[[[red]-[/]]] - Unknown command: [bold yellow]{cmdName}[/]");
return true;
}
/// <summary>
/// Executes a local shell file.
/// </summary>
private static bool ExecuteLocalFile(string commandLine)
{
try
{
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "/bin/bash",
Arguments = $"-c \"{commandLine}\"",
UseShellExecute = false
}
};
process.Start();
process.WaitForExit();
return true;
}
catch (Exception ex)
{
AnsiConsole.MarkupLine($"[[[red]-[/]]] - Error executing file: {ex.Message}");
return true;
}
}
/// <summary>
/// Resolves the full path of a system command by searching in common system directories.
/// </summary>
private static string? ResolveSystemCommandPath(string cmdName)
{
var paths = new[] { "/usr/bin", "/usr/local/bin", "/usr/games", "/bin", "/sbin", "/usr/sbin" };
return paths.Select(path => Path.Combine(path, cmdName))
.FirstOrDefault(fullPath => File.Exists(fullPath) && IsExecutable(fullPath));
}
/// <summary>
/// Checks if a file is executable.
/// </summary>
private static bool IsExecutable(string path)
{
return new FileInfo(path).Exists;
}
/// <summary>
/// Runs a system command, optionally using `sudo`, and handles interactive vs non-interactive command behavior.
/// </summary>
private static bool RunSystemCommand(string path, string[] args, bool useSudo)
{
var isInteractive = InteractiveCommands.Contains(Path.GetFileName(path));
var startInfo = new ProcessStartInfo
{
FileName = useSudo ? "/usr/bin/sudo" : path,
Arguments = useSudo ? $"{path} {string.Join(' ', args)}" : string.Join(' ', args),
UseShellExecute = isInteractive,
RedirectStandardOutput = !isInteractive,
RedirectStandardError = !isInteractive,
CreateNoWindow = false
};
using var process = new Process { StartInfo = startInfo };
if (!isInteractive)
{
process.OutputDataReceived += (_, e) =>
{
if (!string.IsNullOrWhiteSpace(e.Data)) Console.WriteLine(e.Data);
};
process.ErrorDataReceived += (_, e) =>
{
if (!string.IsNullOrWhiteSpace(e.Data))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e.Data);
Console.ResetColor();
}
};
}
process.Start();
if (!isInteractive)
{
process.BeginOutputReadLine();
process.BeginErrorReadLine();
}
process.WaitForExit();
return process.ExitCode == 0;
}
/// <summary>
/// Checks if the current user is root.
/// </summary>
private static bool IsRootUser()
{
return Environment.UserName == "root" || Environment.GetEnvironmentVariable("USER") == "root";
}
}