I’m stuck on Stage #MG5. (The type builtin: executable files)
In this stage, we have to extend the type
builtin to search for executable files using [PATH]
During testing, when I run
type my_exe
my program outputs:
my_exe is /tmp/baz/my_exe
but the test expects:
my_exe is /tmp/foo/my_exe
Here are my logs:
[tester::#MG5] Running tests for Stage #MG5 (The type builtin: executable files)
[tester::#MG5] [setup] export PATH=/tmp/quz:$PATH
[tester::#MG5] [setup] export PATH=/tmp/bar:$PATH
[tester::#MG5] [setup] export PATH=/tmp/foo:$PATH
[tester::#MG5] [setup] PATH is now: /tmp/foo:/tmp/bar:/tmp/quz:...
[tester::#MG5] [setup] Available executables:
[tester::#MG5] [setup] - my_exe
[tester::#MG5] Running ./your_program.sh
[your-program] $ type cat
[your-program] cat is /bin/cat
[tester::#MG5] ✓ Received expected response
[your-program] $ type cp
[your-program] cp is /bin/cp
[tester::#MG5] ✓ Received expected response
[your-program] $ type mkdir
[your-program] mkdir is /bin/mkdir
[tester::#MG5] ✓ Received expected response
[your-program] $ type my_exe
[your-program] my_exe is /tmp/baz/my_exe
[tester::#MG5] ^ Line does not match expected value.
[tester::#MG5] Expected: "my_exe is /tmp/bar/my_exe"
[tester::#MG5] Received: "my_exe is /tmp/baz/my_exe"
[your-program] $
[tester::#MG5] Assertion failed.
[tester::#MG5] Test failed
And here’s a snippet of my code:
import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
String input = "";
String[] words;
String command;
String[] arguments;
String argumentString; // to store rest of the arguments as a string
boolean loop = true;
while (loop) {
System.out.print("$ ");
input = scanner.nextLine().trim();
words = input.split(" ");
command = words[0];
arguments = Arrays.copyOfRange(words, 1, words.length);
argumentString = String.join(" ", arguments);
switch (command) {
case "exit":
if (arguments.length > 0 && !arguments[0].isEmpty())
System.exit(Integer.parseInt(arguments[0]));
else
System.exit(0);
break;
case "echo":
System.out.println(argumentString);
break;
case "type":
System.out.println(getType(argumentString));
break;
default:
System.out.println(input + ": command not found");
}
}
}
public static String getType(String argument) {
String[] builtin_commands = {"exit", "echo", "type"};
String path_commands = System.getenv("PATH");
String[] path_command = path_commands.split(File.pathSeparator);
for (String command : builtin_commands) {
if (command.equals(argument)) {
return argument + " is a shell builtin";
}
}
for (String path: path_command) {
File file = new File(path, argument);
if (file.exists()) {
return argument + " is " + file.getAbsolutePath();
}
}
return argument + ": not found";
}
}