Skip to content

Commit

Permalink
Merge pull request #115 from fonimus/feature/background-script
Browse files Browse the repository at this point in the history
Add possibility to put script in background
  • Loading branch information
fonimus authored Oct 24, 2020
2 parents de009c0 + 03c39d9 commit 7bfa6d8
Show file tree
Hide file tree
Showing 17 changed files with 688 additions and 48 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,11 @@ public class ApplicationTest {}

## Release notes

### 1.5.3

* Rewrite script command to be usable in background with result file (options added to default command)
* Add ``StoppableInteractiveInput`` to be able to stop the interactive mode with specific condition

### 1.5.2

* Add option to create group commands ``ssh.shell.commands.<command>.create``, which is true by default.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
import org.springframework.shell.standard.ShellMethod;
Expand All @@ -37,6 +38,7 @@
/**
* Demo command for example
*/
@Slf4j
@SshShellComponent
public class DemoCommand {

Expand All @@ -62,6 +64,22 @@ public String echo(String message, @ShellOption(defaultValue = ShellOption.NULL)
return message;
}

/**
* Wait for some time
*
* @param waitInMillis wait time
* @return message
*/
@ShellMethod(key = "wait", value = "Wait command")
public String waitCmd(long waitInMillis) {
try {
Thread.sleep(waitInMillis);
} catch (InterruptedException e) {
LOGGER.warn("Got interrupted");
}
return "Waited " + waitInMillis + " milliseconds";
}

/**
* Pojo command
* <p>Try the post processors like pretty, grep with it</p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@
import lombok.extern.slf4j.Slf4j;
import org.springframework.shell.CompletionContext;
import org.springframework.shell.CompletionProposal;
import org.springframework.shell.ExitRequest;
import org.springframework.shell.Input;
import org.springframework.shell.InputProvider;
import org.springframework.shell.ResultHandler;
import org.springframework.shell.Shell;

Expand All @@ -44,6 +46,8 @@
public class ExtendedShell
extends Shell {

private final ResultHandler resultHandler;

private final List<String> postProcessorNames = new ArrayList<>();

/**
Expand All @@ -54,22 +58,57 @@ public class ExtendedShell
*/
public ExtendedShell(ResultHandler resultHandler, List<PostProcessor> postProcessors) {
super(resultHandler);
this.resultHandler = resultHandler;
if (postProcessors != null) {
postProcessorNames.addAll(postProcessors.stream().map(PostProcessor::getName).collect(Collectors.toList()));
}
}


@Override
public void run(InputProvider inputProvider) {
run(inputProvider, () -> false);
}

@SuppressWarnings("unchecked")
public void run(InputProvider inputProvider, ShellNotifier shellNotifier) {
Object result = null;
// Handles ExitRequest thrown from Quit command
while (!(result instanceof ExitRequest) && !shellNotifier.shouldStop()) {
Input input;
try {
input = inputProvider.readInput();
} catch (ExitRequest e) {
// Handles ExitRequest thrown from hitting CTRL-C
break;
} catch (Exception e) {
resultHandler.handleResult(e);
continue;
}
if (input == null) {
break;
}

result = evaluate(input);
if (result != NO_INPUT && !(result instanceof ExitRequest)) {
resultHandler.handleResult(result);
}
}
}

@Override
public Object evaluate(Input input) {
List<String> words = input.words();
Object toReturn = super.evaluate(new ExtendedInput(input));
SshContext ctx = SSH_THREAD_CONTEXT.get();
if (ctx != null) {
ctx.setPostProcessorsList(null);
if (!ctx.isBackground()) {
// clear potential post processors from previous commands
ctx.getPostProcessorsList().clear();
}
if (isKeyCharInList(words)) {
List<Integer> indexes =
IntStream.range(0, words.size()).filter(i -> KEY_CHARS.contains(words.get(i))).boxed().collect(Collectors.toList());
List<PostProcessorObject> postProcessors = new ArrayList<>();
for (Integer index : indexes) {
if (words.size() > index + 1) {
String keyChar = words.get(index);
Expand All @@ -83,15 +122,14 @@ public Object evaluate(Input input) {
currentIndex++;
word = words.size() > index + currentIndex ? words.get(index + currentIndex) : null;
}
postProcessors.add(new PostProcessorObject(postProcessorName, params));
ctx.getPostProcessorsList().add(new PostProcessorObject(postProcessorName, params));
} else if (keyChar.equals(ARROW)) {
postProcessors.add(new PostProcessorObject(SavePostProcessor.SAVE,
ctx.getPostProcessorsList().add(new PostProcessorObject(SavePostProcessor.SAVE,
Collections.singletonList(words.get(index + 1))));
}
}
}
LOGGER.debug("Found {} post processors", postProcessors.size());
ctx.setPostProcessorsList(postProcessors);
LOGGER.debug("Found {} post processors", ctx.getPostProcessorsList().size());
}
}
return toReturn;
Expand All @@ -113,4 +151,10 @@ private static boolean isKeyCharInList(List<String> strList) {
}
return false;
}

@FunctionalInterface
public interface ShellNotifier {

boolean shouldStop();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import org.jline.reader.LineReader;
import org.jline.terminal.Terminal;

import java.util.ArrayList;
import java.util.List;

/**
Expand All @@ -41,8 +42,12 @@ public class SshContext {

private SshAuthentication authentication;

private final List<PostProcessorObject> postProcessorsList = new ArrayList<>();

@Setter
private List<PostProcessorObject> postProcessorsList;
private boolean background;

private long backgroundCount = 0;

public SshContext() {
}
Expand Down Expand Up @@ -89,4 +94,8 @@ public ServerSession getSshSession() {
public Environment getSshEnv() {
return isLocalPrompt() ? null : sshShellRunnable.getSshEnv();
}

public void incrementBackgroundCount() {
this.backgroundCount++;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,11 @@
import com.github.fonimus.ssh.shell.auth.SshAuthentication;
import com.github.fonimus.ssh.shell.interactive.Interactive;
import com.github.fonimus.ssh.shell.interactive.InteractiveInput;
import com.github.fonimus.ssh.shell.interactive.InteractiveInputIO;
import com.github.fonimus.ssh.shell.interactive.KeyBinding;
import com.github.fonimus.ssh.shell.interactive.KeyBindingInput;
import com.github.fonimus.ssh.shell.interactive.StoppableInteractiveInput;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.sshd.server.Environment;
import org.apache.sshd.server.session.ServerSession;
Expand Down Expand Up @@ -570,7 +573,7 @@ public void interactive(Interactive interactive) {
if (size.getColumns() < previous) {
display.clear();
}
maxLines[0] = display(interactive.getInput(), display, size, refreshDelay[0]);
maxLines[0] = display(interactive.getInput(), display, size, refreshDelay[0]).getLines();
});
Attributes attr = terminal.enterRawMode();
try {
Expand Down Expand Up @@ -641,7 +644,8 @@ public void interactive(Interactive interactive) {

String op;
do {
maxLines[0] = display(interactive.getInput(), display, size, refreshDelay[0]);
DisplayResult result = display(interactive.getInput(), display, size, refreshDelay[0]);
maxLines[0] = result.getLines();
checkInterrupted();

long delta = ((System.currentTimeMillis() - t0) / refreshDelay[0] + 1)
Expand All @@ -654,6 +658,8 @@ public void interactive(Interactive interactive) {
op = EXIT;
} else if (ch != NonBlockingReader.READ_EXPIRED) {
op = bindingReader.readBinding(keys, null, false);
} else if (result.isStop()) {
op = EXIT;
}
if (op == null) {
continue;
Expand Down Expand Up @@ -712,11 +718,20 @@ public void interactive(InteractiveInput input, long delay, boolean fullScreen,
interactive(Interactive.builder().input(input).refreshDelay(delay).fullScreen(fullScreen).size(size).build());
}

private int display(InteractiveInput input, Display display, Size size, long currentDelay) {
private DisplayResult display(InteractiveInput input, Display display, Size size, long currentDelay) {
display.resize(size.getRows(), size.getColumns());
List<AttributedString> lines = input.getLines(size, currentDelay);
DisplayResult result = new DisplayResult();
List<AttributedString> lines;
if (input instanceof StoppableInteractiveInput) {
InteractiveInputIO io = ((StoppableInteractiveInput) input).getIO(size, currentDelay);
result.setStop(io.isStop());
lines = io.getLines();
} else {
lines = input.getLines(size, currentDelay);
}
display.update(lines, 0);
return lines.size();
result.setLines(lines.size());
return result;
}

private void checkInterrupted() throws InterruptedException {
Expand All @@ -741,4 +756,12 @@ private LineReader reader() {
}
return sshContext.getLineReader();
}

@Data
public static class DisplayResult {

private int lines;

private boolean stop;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ public SshShellInputProvider(LineReader lineReader, PromptProvider promptProvide
public Input readInput() {
SshContext ctx = SSH_THREAD_CONTEXT.get();
if (ctx != null) {
ctx.setPostProcessorsList(null);
ctx.getPostProcessorsList().clear();
}
try {
return super.readInput();
Expand Down
Loading

0 comments on commit 7bfa6d8

Please sign in to comment.