Search in sources :

Example 6 with Options

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

the class Posix method head.

protected void head(CommandSession session, Process process, String[] argv) throws Exception {
    String[] usage = { "head -  displays first lines of file", "Usage: head [-n lines | -c bytes] [file ...]", "  -? --help                    Show help", "  -n --lines=LINES             Print line counts", "  -c --bytes=BYTES             Print byte counts" };
    Options opt = parseOptions(session, usage, argv);
    if (opt.isSet("lines") && opt.isSet("bytes")) {
        throw new IllegalArgumentException("usage: head [-n # | -c #] [file ...]");
    }
    int nbLines = Integer.MAX_VALUE;
    int nbBytes = Integer.MAX_VALUE;
    if (opt.isSet("lines")) {
        nbLines = opt.getNumber("lines");
    } else if (opt.isSet("bytes")) {
        nbBytes = opt.getNumber("bytes");
    } else {
        nbLines = 10;
    }
    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));
        }
    }
    for (Source src : sources) {
        int bytes = nbBytes;
        int lines = nbLines;
        if (sources.size() > 1) {
            if (src != sources.get(0)) {
                process.out().println();
            }
            process.out().println("==> " + src.getName() + " <==");
        }
        try (InputStream is = src.read()) {
            byte[] buf = new byte[1024];
            int nb;
            do {
                nb = is.read(buf);
                if (nb > 0 && lines > 0 && bytes > 0) {
                    nb = Math.min(nb, bytes);
                    for (int i = 0; i < nb; i++) {
                        if (buf[i] == '\n' && --lines <= 0) {
                            nb = i + 1;
                            break;
                        }
                    }
                    bytes -= nb;
                    process.out().write(buf, 0, nb);
                }
            } while (nb > 0 && lines > 0 && bytes > 0);
        }
    }
}
Also used : Options(org.jline.builtins.Options) ByteArrayInputStream(java.io.ByteArrayInputStream) FilterInputStream(java.io.FilterInputStream) InputStream(java.io.InputStream) PathSource(org.jline.builtins.Source.PathSource) ArrayList(java.util.ArrayList) AttributedString(org.jline.utils.AttributedString) PathSource(org.jline.builtins.Source.PathSource) Source(org.jline.builtins.Source)

Example 7 with Options

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

the class Posix method sort.

protected void sort(CommandSession session, Process process, String[] argv) throws Exception {
    final String[] usage = { "sort -  writes sorted standard input to standard output.", "Usage: sort [OPTIONS] [FILES]", "  -? --help                    show help", "  -f --ignore-case             fold lower case to upper case characters", "  -r --reverse                 reverse the result of comparisons", "  -u --unique                  output only the first of an equal run", "  -t --field-separator=SEP     use SEP instead of non-blank to blank transition", "  -b --ignore-leading-blanks   ignore leading blancks", "     --numeric-sort            compare according to string numerical value", "  -k --key=KEY                 fields to use for sorting separated by whitespaces" };
    Options opt = parseOptions(session, usage, argv);
    List<String> args = opt.args();
    List<String> lines = new ArrayList<>();
    if (!args.isEmpty()) {
        for (String filename : args) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(session.currentDir().toUri().resolve(filename).toURL().openStream()))) {
                read(reader, lines);
            }
        }
    } else {
        BufferedReader r = new BufferedReader(new InputStreamReader(process.in()));
        read(r, lines);
    }
    String separator = opt.get("field-separator");
    boolean caseInsensitive = opt.isSet("ignore-case");
    boolean reverse = opt.isSet("reverse");
    boolean ignoreBlanks = opt.isSet("ignore-leading-blanks");
    boolean numeric = opt.isSet("numeric-sort");
    boolean unique = opt.isSet("unique");
    List<String> sortFields = opt.getList("key");
    char sep = (separator == null || separator.length() == 0) ? '\0' : separator.charAt(0);
    Collections.sort(lines, new SortComparator(caseInsensitive, reverse, ignoreBlanks, numeric, sep, sortFields));
    String last = null;
    for (String s : lines) {
        if (!unique || last == null || !s.equals(last)) {
            process.out().println(s);
        }
        last = s;
    }
}
Also used : Options(org.jline.builtins.Options) InputStreamReader(java.io.InputStreamReader) ArrayList(java.util.ArrayList) BufferedReader(java.io.BufferedReader) AttributedString(org.jline.utils.AttributedString)

Example 8 with Options

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

the class Posix method echo.

protected void echo(CommandSession session, Process process, Object[] argv) throws Exception {
    final String[] usage = { "echo - echoes or prints ARGUMENT to standard output", "Usage: echo [OPTIONS] [ARGUMENTS]", "  -? --help                show help", "  -n                       no trailing new line" };
    Options opt = parseOptions(session, usage, argv);
    List<String> args = opt.args();
    StringBuilder buf = new StringBuilder();
    if (args != null) {
        for (String arg : args) {
            if (buf.length() > 0)
                buf.append(' ');
            for (int i = 0; i < arg.length(); i++) {
                int c = arg.charAt(i);
                int ch;
                if (c == '\\') {
                    c = i < arg.length() - 1 ? arg.charAt(++i) : '\\';
                    switch(c) {
                        case 'a':
                            buf.append('\u0007');
                            break;
                        case 'n':
                            buf.append('\n');
                            break;
                        case 't':
                            buf.append('\t');
                            break;
                        case 'r':
                            buf.append('\r');
                            break;
                        case '\\':
                            buf.append('\\');
                            break;
                        case '0':
                        case '1':
                        case '2':
                        case '3':
                        case '4':
                        case '5':
                        case '6':
                        case '7':
                        case '8':
                        case '9':
                            ch = 0;
                            for (int j = 0; j < 3; j++) {
                                c = i < arg.length() - 1 ? arg.charAt(++i) : -1;
                                if (c >= 0) {
                                    ch = ch * 8 + (c - '0');
                                }
                            }
                            buf.append((char) ch);
                            break;
                        case 'u':
                            ch = 0;
                            for (int j = 0; j < 4; j++) {
                                c = i < arg.length() - 1 ? arg.charAt(++i) : -1;
                                if (c >= 0) {
                                    if (c >= 'A' && c <= 'Z') {
                                        ch = ch * 16 + (c - 'A' + 10);
                                    } else if (c >= 'a' && c <= 'z') {
                                        ch = ch * 16 + (c - 'a' + 10);
                                    } else if (c >= '0' && c <= '9') {
                                        ch = ch * 16 + (c - '0');
                                    } else {
                                        break;
                                    }
                                }
                            }
                            buf.append((char) ch);
                            break;
                        default:
                            buf.append((char) c);
                            break;
                    }
                } else {
                    buf.append((char) c);
                }
            }
        }
    }
    if (opt.isSet("n")) {
        process.out().print(buf);
    } else {
        process.out().println(buf);
    }
}
Also used : Options(org.jline.builtins.Options) AttributedStringBuilder(org.jline.utils.AttributedStringBuilder) AttributedString(org.jline.utils.AttributedString)

Example 9 with Options

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

the class Posix method grep.

protected void grep(CommandSession session, Process process, String[] argv) throws Exception {
    final String[] usage = { "grep -  search for PATTERN in each FILE or standard input.", "Usage: grep [OPTIONS] PATTERN [FILES]", "  -? --help                Show help", "  -i --ignore-case         Ignore case distinctions", "  -n --line-number         Prefix each line with line number within its input file", "  -q --quiet, --silent     Suppress all normal output", "  -v --invert-match        Select non-matching lines", "  -w --word-regexp         Select only whole words", "  -x --line-regexp         Select only whole lines", "  -c --count               Only print a count of matching lines per file", "     --color=WHEN          Use markers to distinguish the matching string, may be `always', `never' or `auto'", "  -B --before-context=NUM  Print NUM lines of leading context before matching lines", "  -A --after-context=NUM   Print NUM lines of trailing context after matching lines", "  -C --context=NUM         Print NUM lines of output context", "     --pad-lines           Pad line numbers" };
    Options opt = parseOptions(session, usage, argv);
    List<String> args = opt.args();
    if (args.isEmpty()) {
        throw new IllegalArgumentException("no pattern supplied");
    }
    String regex = args.remove(0);
    String regexp = regex;
    if (opt.isSet("word-regexp")) {
        regexp = "\\b" + regexp + "\\b";
    }
    if (opt.isSet("line-regexp")) {
        regexp = "^" + regexp + "$";
    } else {
        regexp = ".*" + regexp + ".*";
    }
    Pattern p;
    Pattern p2;
    if (opt.isSet("ignore-case")) {
        p = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE);
        p2 = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    } else {
        p = Pattern.compile(regexp);
        p2 = Pattern.compile(regex);
    }
    int after = opt.isSet("after-context") ? opt.getNumber("after-context") : -1;
    int before = opt.isSet("before-context") ? opt.getNumber("before-context") : -1;
    int context = opt.isSet("context") ? opt.getNumber("context") : 0;
    String lineFmt = opt.isSet("pad-lines") ? "%6d" : "%d";
    if (after < 0) {
        after = context;
    }
    if (before < 0) {
        before = context;
    }
    List<String> lines = new ArrayList<>();
    boolean invertMatch = opt.isSet("invert-match");
    boolean lineNumber = opt.isSet("line-number");
    boolean count = opt.isSet("count");
    String color = opt.isSet("color") ? opt.get("color") : "auto";
    boolean colored;
    switch(color) {
        case "always":
        case "yes":
        case "force":
            colored = true;
            break;
        case "never":
        case "no":
        case "none":
            colored = false;
            break;
        case "auto":
        case "tty":
        case "if-tty":
            colored = process.isTty(1);
            break;
        default:
            throw new IllegalArgumentException("invalid argument ‘" + color + "’ for ‘--color’");
    }
    Map<String, String> colors = colored ? getColorMap(session, "GREP", DEFAULT_GREP_COLORS) : Collections.emptyMap();
    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 match = false;
    for (Source source : sources) {
        boolean firstPrint = true;
        int nb = 0;
        int lineno = 1;
        String line;
        int lineMatch = 0;
        try (BufferedReader r = new BufferedReader(new InputStreamReader(source.read()))) {
            while ((line = r.readLine()) != null) {
                if (line.length() == 1 && line.charAt(0) == '\n') {
                    break;
                }
                boolean matches = p.matcher(line).matches();
                AttributedStringBuilder sbl = new AttributedStringBuilder();
                if (!count) {
                    if (sources.size() > 1) {
                        if (colored) {
                            applyStyle(sbl, colors, "fn");
                        }
                        sbl.append(source.getName());
                        if (colored) {
                            applyStyle(sbl, colors, "se");
                        }
                        sbl.append(":");
                    }
                    if (lineNumber) {
                        if (colored) {
                            applyStyle(sbl, colors, "ln");
                        }
                        sbl.append(String.format(lineFmt, lineno));
                        if (colored) {
                            applyStyle(sbl, colors, "se");
                        }
                        sbl.append((matches ^ invertMatch) ? ":" : "-");
                    }
                    String style = matches ^ invertMatch ^ (invertMatch && colors.containsKey("rv")) ? "sl" : "cx";
                    if (colored) {
                        applyStyle(sbl, colors, style);
                    }
                    AttributedString aLine = AttributedString.fromAnsi(line);
                    Matcher matcher2 = p2.matcher(aLine.toString());
                    int cur = 0;
                    while (matcher2.find()) {
                        int index = matcher2.start(0);
                        AttributedString prefix = aLine.subSequence(cur, index);
                        sbl.append(prefix);
                        cur = matcher2.end();
                        if (colored) {
                            applyStyle(sbl, colors, invertMatch ? "mc" : "ms", "mt");
                        }
                        sbl.append(aLine.subSequence(index, cur));
                        if (colored) {
                            applyStyle(sbl, colors, style);
                        }
                        nb++;
                    }
                    sbl.append(aLine.subSequence(cur, aLine.length()));
                }
                if (matches ^ invertMatch) {
                    lines.add(sbl.toAnsi(Shell.getTerminal(session)));
                    lineMatch = lines.size();
                } else {
                    if (lineMatch != 0 & lineMatch + after + before <= lines.size()) {
                        if (!count) {
                            if (!firstPrint && before + after > 0) {
                                AttributedStringBuilder sbl2 = new AttributedStringBuilder();
                                if (colored) {
                                    applyStyle(sbl2, colors, "se");
                                }
                                sbl2.append("--");
                                process.out().println(sbl2.toAnsi(Shell.getTerminal(session)));
                            } else {
                                firstPrint = false;
                            }
                            for (int i = 0; i < lineMatch + after; i++) {
                                process.out().println(lines.get(i));
                            }
                        }
                        while (lines.size() > before) {
                            lines.remove(0);
                        }
                        lineMatch = 0;
                    }
                    lines.add(sbl.toAnsi(Shell.getTerminal(session)));
                    while (lineMatch == 0 && lines.size() > before) {
                        lines.remove(0);
                    }
                }
                lineno++;
            }
            if (!count && lineMatch > 0) {
                if (!firstPrint && before + after > 0) {
                    AttributedStringBuilder sbl2 = new AttributedStringBuilder();
                    if (colored) {
                        applyStyle(sbl2, colors, "se");
                    }
                    sbl2.append("--");
                    process.out().println(sbl2.toAnsi(Shell.getTerminal(session)));
                } else {
                    firstPrint = false;
                }
                for (int i = 0; i < lineMatch + after && i < lines.size(); i++) {
                    process.out().println(lines.get(i));
                }
            }
            if (count) {
                process.out().println(nb);
            }
            match |= nb > 0;
        }
    }
    Process.Utils.current().error(match ? 0 : 1);
}
Also used : Options(org.jline.builtins.Options) Pattern(java.util.regex.Pattern) InputStreamReader(java.io.InputStreamReader) Matcher(java.util.regex.Matcher) PathSource(org.jline.builtins.Source.PathSource) ArrayList(java.util.ArrayList) AttributedStringBuilder(org.jline.utils.AttributedStringBuilder) AttributedString(org.jline.utils.AttributedString) PathSource(org.jline.builtins.Source.PathSource) Source(org.jline.builtins.Source) AttributedString(org.jline.utils.AttributedString) BufferedReader(java.io.BufferedReader)

Example 10 with Options

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

the class Posix method pwd.

protected void pwd(CommandSession session, Process process, String[] argv) throws Exception {
    final String[] usage = { "pwd - get current directory", "Usage: pwd [OPTIONS]", "  -? --help                show help" };
    Options opt = parseOptions(session, usage, argv);
    if (!opt.args().isEmpty()) {
        throw new IllegalArgumentException("usage: pwd");
    }
    process.out().println(session.currentDir());
}
Also used : Options(org.jline.builtins.Options) AttributedString(org.jline.utils.AttributedString)

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