use of org.jline.builtins.Source 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);
}
}
}
use of org.jline.builtins.Source 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);
}
use of org.jline.builtins.Source in project felix by apache.
the class Posix method less.
protected void less(CommandSession session, Process process, String[] argv) throws Exception {
String[] usage = { "less - file pager", "Usage: less [OPTIONS] [FILES]", " -? --help Show help", " -e --quit-at-eof Exit on second EOF", " -E --QUIT-AT-EOF Exit on EOF", " -F --quit-if-one-screen Exit if entire file fits on first screen", " -q --quiet --silent Silent mode", " -Q --QUIET --SILENT Completely silent", " -S --chop-long-lines Do not fold long lines", " -i --ignore-case Search ignores lowercase case", " -I --IGNORE-CASE Search ignores all case", " -x --tabs Set tab stops", " -N --LINE-NUMBERS Display line number for each line", " --no-init Disable terminal initialization", " --no-keypad Disable keypad handling" };
boolean hasExtendedOptions = false;
try {
Less.class.getField("quitIfOneScreen");
hasExtendedOptions = true;
} catch (NoSuchFieldException e) {
List<String> ustrs = new ArrayList<>(Arrays.asList(usage));
ustrs.removeIf(s -> s.contains("--quit-if-one-screen") || s.contains("--no-init") || s.contains("--no-keypad"));
usage = ustrs.toArray(new String[ustrs.size()]);
}
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));
}
}
if (!process.isTty(1)) {
for (Source source : sources) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(source.read()))) {
cat(process, reader, opt.isSet("LINE-NUMBERS"));
}
}
return;
}
Less less = new Less(Shell.getTerminal(session));
less.quitAtFirstEof = opt.isSet("QUIT-AT-EOF");
less.quitAtSecondEof = opt.isSet("quit-at-eof");
less.quiet = opt.isSet("quiet");
less.veryQuiet = opt.isSet("QUIET");
less.chopLongLines = opt.isSet("chop-long-lines");
less.ignoreCaseAlways = opt.isSet("IGNORE-CASE");
less.ignoreCaseCond = opt.isSet("ignore-case");
if (opt.isSet("tabs")) {
less.tabs = opt.getNumber("tabs");
}
less.printLineNumbers = opt.isSet("LINE-NUMBERS");
if (hasExtendedOptions) {
Less.class.getField("quitIfOneScreen").set(less, opt.isSet("quit-if-one-screen"));
Less.class.getField("noInit").set(less, opt.isSet("no-init"));
Less.class.getField("noKeypad").set(less, opt.isSet("no-keypad"));
}
less.run(sources);
}
use of org.jline.builtins.Source 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"));
}
}
Aggregations