Search in sources :

Example 26 with Options

use of org.jline.builtins.Options in project felix by apache.

the class Posix method wc.

protected void wc(CommandSession session, Process process, String[] argv) throws Exception {
    String[] usage = { "wc -  word, line, character, and byte count", "Usage: wc [OPTIONS] [FILES]", "  -? --help                    Show help", "  -l --lines                   Print line counts", "  -c --bytes                   Print byte counts", "  -m --chars                   Print character counts", "  -w --words                   Print word counts" };
    Options opt = parseOptions(session, usage, argv);
    List<Source> sources = new ArrayList<>();
    if (opt.args().isEmpty()) {
        opt.args().add("-");
    }
    for (String arg : opt.args()) {
        if ("-".equals(arg)) {
            sources.add(new StdInSource(process));
        } else {
            sources.add(new PathSource(session.currentDir().resolve(arg), arg));
        }
    }
    boolean displayLines = opt.isSet("lines");
    boolean displayWords = opt.isSet("words");
    boolean displayChars = opt.isSet("chars");
    boolean displayBytes = opt.isSet("bytes");
    if (displayChars) {
        displayBytes = false;
    }
    if (!displayLines && !displayWords && !displayChars && !displayBytes) {
        displayLines = true;
        displayWords = true;
        displayBytes = true;
    }
    String format = "";
    if (displayLines) {
        format += "%1$8d";
    }
    if (displayWords) {
        format += "%2$8d";
    }
    if (displayChars) {
        format += "%3$8d";
    }
    if (displayBytes) {
        format += "%4$8d";
    }
    format += "  %5s";
    int totalLines = 0;
    int totalBytes = 0;
    int totalChars = 0;
    int totalWords = 0;
    for (Source src : sources) {
        try (InputStream is = src.read()) {
            AtomicInteger lines = new AtomicInteger();
            AtomicInteger bytes = new AtomicInteger();
            AtomicInteger chars = new AtomicInteger();
            AtomicInteger words = new AtomicInteger();
            AtomicBoolean inWord = new AtomicBoolean();
            AtomicBoolean lastNl = new AtomicBoolean(true);
            InputStream isc = new FilterInputStream(is) {

                @Override
                public int read() throws IOException {
                    int b = super.read();
                    if (b >= 0) {
                        bytes.incrementAndGet();
                    }
                    return b;
                }

                @Override
                public int read(byte[] b, int off, int len) throws IOException {
                    int nb = super.read(b, off, len);
                    if (nb > 0) {
                        bytes.addAndGet(nb);
                    }
                    return nb;
                }
            };
            IntConsumer consumer = cp -> {
                chars.incrementAndGet();
                boolean ws = Character.isWhitespace(cp);
                if (inWord.getAndSet(!ws) && ws) {
                    words.incrementAndGet();
                }
                if (cp == '\n') {
                    lines.incrementAndGet();
                    lastNl.set(true);
                } else {
                    lastNl.set(false);
                }
            };
            Reader reader = new InputStreamReader(isc);
            while (true) {
                int h = reader.read();
                if (Character.isHighSurrogate((char) h)) {
                    int l = reader.read();
                    if (Character.isLowSurrogate((char) l)) {
                        int cp = Character.toCodePoint((char) h, (char) l);
                        consumer.accept(cp);
                    } else {
                        consumer.accept(h);
                        if (l >= 0) {
                            consumer.accept(l);
                        } else {
                            break;
                        }
                    }
                } else if (h >= 0) {
                    consumer.accept(h);
                } else {
                    break;
                }
            }
            if (inWord.get()) {
                words.incrementAndGet();
            }
            if (!lastNl.get()) {
                lines.incrementAndGet();
            }
            process.out().println(String.format(format, lines.get(), words.get(), chars.get(), bytes.get(), src.getName()));
            totalBytes += bytes.get();
            totalChars += chars.get();
            totalWords += words.get();
            totalLines += lines.get();
        }
    }
    if (sources.size() > 1) {
        process.out().println(String.format(format, totalLines, totalWords, totalChars, totalBytes, "total"));
    }
}
Also used : Arrays(java.util.Arrays) PathSource(org.jline.builtins.Source.PathSource) Date(java.util.Date) ZonedDateTime(java.time.ZonedDateTime) IntConsumer(java.util.function.IntConsumer) FileTime(java.nio.file.attribute.FileTime) IntBinaryOperator(java.util.function.IntBinaryOperator) CommandSession(org.apache.felix.service.command.CommandSession) AttributedString(org.jline.utils.AttributedString) WatchKey(java.nio.file.WatchKey) Matcher(java.util.regex.Matcher) ByteArrayInputStream(java.io.ByteArrayInputStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) Context(org.apache.felix.gogo.jline.Shell.Context) Path(java.nio.file.Path) EnumSet(java.util.EnumSet) Options(org.jline.builtins.Options) TTop(org.jline.builtins.TTop) PosixFilePermission(java.nio.file.attribute.PosixFilePermission) Predicate(java.util.function.Predicate) Set(java.util.Set) Source(org.jline.builtins.Source) Reader(java.io.Reader) Instant(java.time.Instant) OSUtils(org.jline.utils.OSUtils) Collectors(java.util.stream.Collectors) ZoneId(java.time.ZoneId) Executors(java.util.concurrent.Executors) Objects(java.util.Objects) List(java.util.List) Stream(java.util.stream.Stream) Pattern(java.util.regex.Pattern) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Capability(org.jline.utils.InfoCmp.Capability) Commands(org.jline.builtins.Commands) SimpleDateFormat(java.text.SimpleDateFormat) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Attributes(org.jline.terminal.Attributes) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Process(org.apache.felix.service.command.Process) LinkOption(java.nio.file.LinkOption) FilterInputStream(java.io.FilterInputStream) StandardWatchEventKinds(java.nio.file.StandardWatchEventKinds) PosixFilePermissions(java.nio.file.attribute.PosixFilePermissions) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Nano(org.jline.builtins.Nano) Terminal(org.jline.terminal.Terminal) OutputStream(java.io.OutputStream) PrintStream(java.io.PrintStream) CommandProcessor(org.apache.felix.service.command.CommandProcessor) AttributedStyle(org.jline.utils.AttributedStyle) Files(java.nio.file.Files) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) WatchService(java.nio.file.WatchService) TreeMap(java.util.TreeMap) AttributedStringBuilder(org.jline.utils.AttributedStringBuilder) Closeable(java.io.Closeable) DateTimeFormatter(java.time.format.DateTimeFormatter) BufferedReader(java.io.BufferedReader) Comparator(java.util.Comparator) Less(org.jline.builtins.Less) Collections(java.util.Collections) InputStream(java.io.InputStream) Options(org.jline.builtins.Options) FilterInputStream(java.io.FilterInputStream) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) FilterInputStream(java.io.FilterInputStream) InputStream(java.io.InputStream) PathSource(org.jline.builtins.Source.PathSource) ArrayList(java.util.ArrayList) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) AttributedString(org.jline.utils.AttributedString) PathSource(org.jline.builtins.Source.PathSource) Source(org.jline.builtins.Source) IntConsumer(java.util.function.IntConsumer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 27 with Options

use of org.jline.builtins.Options in project felix by apache.

the class Posix method clear.

protected void clear(CommandSession session, Process process, String[] argv) throws Exception {
    final String[] usage = { "clear -  clear screen", "Usage: clear [OPTIONS]", "  -? --help                    Show help" };
    Options opt = parseOptions(session, usage, argv);
    if (process.isTty(1)) {
        Shell.getTerminal(session).puts(Capability.clear_screen);
        Shell.getTerminal(session).flush();
    }
}
Also used : Options(org.jline.builtins.Options) AttributedString(org.jline.utils.AttributedString)

Example 28 with Options

use of org.jline.builtins.Options in project felix by apache.

the class Posix method watch.

protected void watch(final CommandSession session, Process process, String[] argv) throws Exception {
    final String[] usage = { "watch - watches & refreshes the output of a command", "Usage: watch [OPTIONS] COMMAND", "  -? --help                    Show help", "  -n --interval                Interval between executions of the command in seconds", "  -a --append                  The output should be appended but not clear the console" };
    Options opt = parseOptions(session, usage, argv);
    List<String> args = opt.args();
    if (args.isEmpty()) {
        throw new IllegalArgumentException("usage: watch COMMAND");
    }
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    final Terminal terminal = Shell.getTerminal(session);
    final CommandProcessor processor = Shell.getProcessor(session);
    try {
        int interval = 1;
        if (opt.isSet("interval")) {
            interval = opt.getNumber("interval");
            if (interval < 1) {
                interval = 1;
            }
        }
        final String cmd = String.join(" ", args);
        Runnable task = () -> {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream os = new PrintStream(baos);
            InputStream is = new ByteArrayInputStream(new byte[0]);
            if (opt.isSet("append") || !terminal.puts(Capability.clear_screen)) {
                terminal.writer().println();
            }
            try {
                CommandSession ns = processor.createSession(is, os, os);
                Set<String> vars = Shell.getCommands(session);
                for (String n : vars) {
                    ns.put(n, session.get(n));
                }
                ns.execute(cmd);
            } catch (Throwable t) {
                t.printStackTrace(os);
            }
            os.flush();
            terminal.writer().print(baos.toString());
            terminal.writer().flush();
        };
        executorService.scheduleAtFixedRate(task, 0, interval, TimeUnit.SECONDS);
        Attributes attr = terminal.enterRawMode();
        terminal.reader().read();
        terminal.setAttributes(attr);
    } finally {
        executorService.shutdownNow();
    }
}
Also used : Options(org.jline.builtins.Options) PrintStream(java.io.PrintStream) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) EnumSet(java.util.EnumSet) Set(java.util.Set) HashSet(java.util.HashSet) ByteArrayInputStream(java.io.ByteArrayInputStream) FilterInputStream(java.io.FilterInputStream) InputStream(java.io.InputStream) Attributes(org.jline.terminal.Attributes) AttributedString(org.jline.utils.AttributedString) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Terminal(org.jline.terminal.Terminal) CommandSession(org.apache.felix.service.command.CommandSession) ByteArrayInputStream(java.io.ByteArrayInputStream) CommandProcessor(org.apache.felix.service.command.CommandProcessor)

Example 29 with Options

use of org.jline.builtins.Options in project felix by apache.

the class Procedural method doThrow.

protected Object doThrow(CommandSession session, Process process, Object[] argv) throws ThrownException, HelpException, OptionException {
    String[] usage = { "throw -  throw an exception", "Usage: throw [ message [ cause ] ]", "       throw exception", "       throw", "  -? --help                    Show help" };
    Options opt = parseOptions(session, usage, argv);
    if (opt.argObjects().size() == 0) {
        Object exception = session.get("exception");
        if (exception instanceof Throwable)
            throw new ThrownException((Throwable) exception);
        else
            throw new ThrownException(new Exception());
    } else if (opt.argObjects().size() == 1 && opt.argObjects().get(0) instanceof Throwable) {
        throw new ThrownException((Throwable) opt.argObjects().get(0));
    } else {
        String message = opt.argObjects().get(0).toString();
        Throwable cause = null;
        if (opt.argObjects().size() > 1) {
            if (opt.argObjects().get(1) instanceof Throwable) {
                cause = (Throwable) opt.argObjects().get(1);
            }
        }
        throw new ThrownException(new Exception(message).initCause(cause));
    }
}
Also used : Options(org.jline.builtins.Options)

Example 30 with Options

use of org.jline.builtins.Options in project felix by apache.

the class Procedural method doWhile.

protected Object doWhile(CommandSession session, Process process, Object[] argv) throws Exception {
    String[] usage = { "while -  while loop", "Usage: while { condition } { action }", "  -? --help                    Show help" };
    Options opt = parseOptions(session, usage, argv);
    List<Function> functions = getFunctions(opt);
    if (functions == null || functions.size() != 2) {
        process.err().println("usage: while { condition } { action }");
        process.error(2);
        return null;
    }
    while (isTrue(session, functions.get(0))) {
        try {
            functions.get(1).execute(session, null);
        } catch (BreakException b) {
            break;
        } catch (ContinueException c) {
            continue;
        }
    }
    return null;
}
Also used : Options(org.jline.builtins.Options) Function(org.apache.felix.service.command.Function)

Aggregations

Options (org.jline.builtins.Options)41 AttributedString (org.jline.utils.AttributedString)16 Function (org.apache.felix.service.command.Function)15 ArrayList (java.util.ArrayList)14 Process (org.apache.felix.service.command.Process)12 InputStreamReader (java.io.InputStreamReader)10 BufferedReader (java.io.BufferedReader)9 InputStream (java.io.InputStream)9 ByteArrayInputStream (java.io.ByteArrayInputStream)8 FilterInputStream (java.io.FilterInputStream)8 PrintStream (java.io.PrintStream)8 Path (java.nio.file.Path)8 CommandSession (org.apache.felix.service.command.CommandSession)8 AttributedStringBuilder (org.jline.utils.AttributedStringBuilder)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 IOException (java.io.IOException)7 HashSet (java.util.HashSet)7 Reader (java.io.Reader)6 TreeMap (java.util.TreeMap)6 Closeable (java.io.Closeable)5