Skip to content
50 changes: 48 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,16 @@

<groupId>com.github.podllev</groupId>
<artifactId>shell-java</artifactId>
<version>0.3.0</version>
<version>0.4.0</version>
<name>shell-java</name>
<description>A custom shell implementation in Java with builtins and external command execution</description>
<description>A custom shell implementation in Java with builtins, I/O redirection, tab completion, and external command execution</description>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<lombok.version>1.18.36</lombok.version>
<jline.version>3.27.1</jline.version>
</properties>

<dependencies>
Expand All @@ -24,6 +25,51 @@
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jline</groupId>
<artifactId>jline</artifactId>
<version>${jline.version}</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<compilerArgs>
<arg>--enable-preview</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<finalName>shell-java-${project.version}</finalName>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<appendAssemblyId>false</appendAssemblyId>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>Main</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

</project>
68 changes: 47 additions & 21 deletions src/main/java/Shell.java
Original file line number Diff line number Diff line change
@@ -1,44 +1,70 @@
import command.CommandRegistry;
import util.Environment;
import util.ParseResult;
import util.Tokenizer;
import util.UnterminatedQuoteException;
import completer.CandidateCollector;
import org.jline.reader.*;
import org.jline.reader.impl.DefaultParser;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import util.*;

import java.io.IOException;
import java.util.List;
import java.util.Scanner;

public class Shell {

private final CommandRegistry registry;
private final Environment env;
private final Tokenizer tokenizer;

public Shell() {
Environment env = new Environment();
this.env = new Environment();
this.registry = new CommandRegistry(env);
this.tokenizer = new Tokenizer();
}

public void run() {
Scanner scanner = new Scanner(System.in);
try (Terminal terminal = TerminalBuilder.builder()
.system(true)
.build()) {

while (true) {
System.out.print("$ ");
System.out.flush();
String input = scanner.nextLine().trim();
if (input.isEmpty()) continue;
DefaultParser parser = new DefaultParser();
parser.setEscapeChars(null);

try {
ParseResult result = tokenizer.tokenize(input);
List<String> tokens = result.tokens();
if (tokens.isEmpty()) continue;
Completer completer = (reader, line, candidates) ->
candidates.addAll(CandidateCollector.of(registry, env).collect(reader, line));

String command = tokens.get(0);
List<String> argTokens = tokens.subList(1, tokens.size());
LineReader reader = LineReaderBuilder.builder()
.terminal(terminal)
.completer(completer)
.parser(parser)
.option(LineReader.Option.AUTO_MENU, true)
.option(LineReader.Option.AUTO_LIST, true)
.option(LineReader.Option.MENU_COMPLETE, true)
.build();

registry.execute(command, argTokens, result.redirect());
} catch (UnterminatedQuoteException e) {
System.err.println(e.getMessage());
while (true) {
try {
String input = reader.readLine("$ ").trim();
if (input.isEmpty()) continue;

ParseResult result = tokenizer.tokenize(input);
List<String> tokens = result.tokens();
if (tokens.isEmpty()) continue;

String command = tokens.get(0);
List<String> argTokens = tokens.subList(1, tokens.size());

registry.execute(command, argTokens, result.redirect());
} catch (UnterminatedQuoteException e) {
System.err.println(e.getMessage());
} catch (UserInterruptException e) {
// Ctrl+C — JLine clears current line, loop continues
} catch (EndOfFileException e) {
// Ctrl+D — exit shell
return;
}
}
} catch (IOException e) {
System.err.printf("terminal error: %s%n", e.getMessage());
}
}

Expand Down
4 changes: 4 additions & 0 deletions src/main/java/command/CommandRegistry.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,8 @@ public void execute(String command, List<String> arguments, Redirect redirect) {
}
}

public Set<String> getBuiltinNames() {
return builtins.keySet();
}

}
3 changes: 2 additions & 1 deletion src/main/java/command/builtin/BuiltinFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ public enum BuiltinFactory {

PWD(PwdBuiltin::new),
CD(CdBuiltin::new),
LS(LsBuiltin::new);
LS(LsBuiltin::new),
COMPLETE(CompleteBuiltin::new);

private final Function<Environment, Builtin> factory;

Expand Down
48 changes: 48 additions & 0 deletions src/main/java/command/builtin/CompleteBuiltin.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package command.builtin;

import lombok.RequiredArgsConstructor;
import redirect.OutputWriter;
import redirect.Redirect;
import util.Environment;

import java.util.List;

@RequiredArgsConstructor
public final class CompleteBuiltin implements Builtin {

private final Environment env;

@Override
public String name() {
return "complete";
}

@Override
public void execute(String command, List<String> args, Redirect redirect) {
if (args.isEmpty()) return;

switch (args.get(0)) {
case "-p" -> {
if (args.size() >= 2) handlePrint(args.get(1), redirect);
}
case "-C" -> {
if (args.size() >= 3) handleRegister(args.get(1), args.get(2));
}
case "-r" -> {
if (args.size() >= 2) env.removeCompletion(args.get(1));
}
}
}

private void handlePrint(String target, Redirect redirect) {
env.getCompletion(target).ifPresentOrElse(
script -> OutputWriter.write("complete -C '" + script + "' " + target, redirect),
() -> OutputWriter.writeError("complete: " + target + ": no completion specification", redirect)
);
}

private void handleRegister(String scriptPath, String commandName) {
env.registerCompletion(commandName, scriptPath);
}

}
82 changes: 82 additions & 0 deletions src/main/java/completer/CandidateCollector.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package completer;

import command.CommandRegistry;
import lombok.RequiredArgsConstructor;
import org.jline.builtins.Completers;
import org.jline.reader.Candidate;
import org.jline.reader.Completer;
import org.jline.reader.LineReader;
import org.jline.reader.ParsedLine;
import org.jline.reader.impl.completer.StringsCompleter;
import util.Environment;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RequiredArgsConstructor
public final class CandidateCollector {

private final Completer builtinCompleter;
private final Completer binaryCompleter;
private final Completer filesCompleter;
private final Completer directoriesCompleter;
private final Environment env;

public static CandidateCollector of(CommandRegistry registry, Environment env) {
return new CandidateCollector(
new StringsCompleter(registry.getBuiltinNames()),
new SystemBinaryCompleter(env),
new Completers.FilesCompleter(env.getCurrentDir()),
new Completers.DirectoriesCompleter(env.getCurrentDir()),
env
);
}

public List<Candidate> collect(LineReader reader, ParsedLine pl) {
List<Candidate> candidates = new ArrayList<>();
if (pl.wordIndex() == 0) {
builtinCompleter.complete(reader, pl, candidates);
binaryCompleter.complete(reader, pl, candidates);
} else {
String command = pl.words().get(0);
Optional<String> script = env.getCompletion(command);
if (script.isPresent()) {
runScript(script.get(), command, reader, pl, candidates);
} else {
filesCompleter.complete(reader, pl, candidates);
directoriesCompleter.complete(reader, pl, candidates);
}
}
return candidates;
}

private void runScript(String scriptPath, String command, LineReader reader, ParsedLine pl, List<Candidate> candidates) {
String word = pl.word();
String preceding = pl.wordIndex() >= 1 ? pl.words().get(pl.wordIndex() - 1) : "";

try {
ProcessBuilder pb = new ProcessBuilder(scriptPath, command, word, preceding);
pb.environment().put("COMP_LINE", pl.line());
pb.environment().put("COMP_POINT", String.valueOf(pl.cursor()));
pb.directory(env.getCurrentDir());
pb.redirectErrorStream(true);

Process process = pb.start();
try (BufferedReader br = new BufferedReader(
new InputStreamReader(process.getInputStream()))) {
br.lines()
.filter(line -> !line.isBlank())
.map(Candidate::new)
.forEach(candidates::add);
}
process.waitFor();
} catch (IOException | InterruptedException e) {
filesCompleter.complete(reader, pl, candidates);
}
}

}
66 changes: 66 additions & 0 deletions src/main/java/completer/SystemBinaryCompleter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package completer;

import lombok.RequiredArgsConstructor;
import org.jline.reader.Candidate;
import org.jline.reader.Completer;
import org.jline.reader.LineReader;
import org.jline.reader.ParsedLine;
import util.Environment;

import java.io.File;
import java.util.List;
import java.util.Set;

@RequiredArgsConstructor
public final class SystemBinaryCompleter implements Completer {

private static final Set<String> WINDOWS_EXECUTABLE_EXTENSIONS = Set.of(
".exe", ".bat", ".cmd", ".com"
);

private final Environment env;

@Override
public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
if (line.wordIndex() != 0) return;

String word = line.word().toLowerCase();
String pathEnv = env.getPath();

if (pathEnv == null || pathEnv.isBlank()) return;

for (String dir : pathEnv.split(File.pathSeparator)) {
File folder = new File(dir);
if (!folder.isDirectory()) continue;

File[] files = folder.listFiles();
if (files == null) continue;

for (File file : files) {
if (!isExecutable(file)) continue;

String name = stripExtension(file.getName());
if (name.toLowerCase().startsWith(word)) {
candidates.add(new Candidate(name));
}
}
}
}

private boolean isExecutable(File file) {
if (!file.isFile()) return false;
if (!env.isWindows()) return file.canExecute();

String name = file.getName().toLowerCase();
return WINDOWS_EXECUTABLE_EXTENSIONS.stream()
.anyMatch(name::endsWith);
}

private String stripExtension(String filename) {
if (env.isWindows() && filename.contains(".")) {
return filename.substring(0, filename.lastIndexOf('.'));
}
return filename;
}

}
Loading