-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main.java
100 lines (97 loc) · 3.16 KB
/
Main.java
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
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Scanner;
import java.util.Set;
public class Main
{
public static void main(String[] args) throws Exception
{
Set<String> commands = Set.of("cd", "echo", "exit", "pwd", "type");
Scanner scanner = new Scanner(System.in);
String cwd = Path.of("").toAbsolutePath().toString();
while (true)
{
System.out.print("$ ");
String input = scanner.nextLine();
if (input.equals("exit 0"))
{
System.exit(0);
}
else if (input.startsWith("echo "))
{
System.out.println(input.substring(5));
}
else if (input.startsWith("type "))
{
String arg = input.substring(5);
if (commands.contains(arg))
{
System.out.printf("%s is a shell builtin%n", arg);
}
else
{
String path = getPath(arg);
if (path == null)
{
System.out.printf("%s: not found%n", arg);
}
else
{
System.out.printf("%s is %s%n", arg, path);
}
}
}
else if (input.equals("pwd"))
{
System.out.println(cwd);
}
else if (input.startsWith("cd "))
{
String dir = input.substring(3);
if (dir.equals("~"))
{
dir = System.getenv("HOME");
}
else if(!dir.startsWith("/"))
{
dir = cwd + "/" + dir;
}
if (Files.isDirectory(Path.of(dir)))
{
cwd = Path.of(dir).normalize().toString();
}
else
{
System.out.printf("cd: %s: No such file or directory%n", dir);
}
}
else
{
String command = input.split(" ")[0];
String path = getPath(command);
if (path == null)
{
System.out.printf("%s: command not found%n", command);
}
else
{
String fullPath = path + input.substring(command.length());
Process p = Runtime.getRuntime().exec(fullPath.split(" "));
p.getInputStream().transferTo(System.out);
}
}
}
}
private static String getPath(String command)
{
for (String path : System.getenv("PATH").split(":"))
{
Path fullPath = Path.of(path, command);
if (Files.isRegularFile(fullPath))
{
return fullPath.toString();
}
}
return null;
}
}