Skip to content

Commit

Permalink
prnt command: added option toString and custom highlight map values
Browse files Browse the repository at this point in the history
  • Loading branch information
mattirn committed Mar 13, 2020
1 parent f30e34b commit 4523408
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 44 deletions.
79 changes: 48 additions & 31 deletions builtins/src/main/java/org/jline/builtins/ConsoleEngineImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -1035,57 +1035,68 @@ private Map<String,Object> objectToMap(Map<String, Object> options, Object obj)
@SuppressWarnings("unchecked")
private String objectToString(Map<String, Object> options, Object obj) {
Map<Class<?>, Object> toString = options.containsKey("objectToString") ? (Map<Class<?>, Object>)options.get("objectToString")
: new HashMap<>();;
if (toString.containsKey(obj.getClass())) {
: new HashMap<>();
if (obj == null) {
return "null";
} else if (toString.containsKey(obj.getClass())) {
return (String)engine.execute(toString.get(obj.getClass()), obj);
} else if (objectToString.containsKey(obj.getClass())) {
return objectToString.get(obj.getClass()).apply(obj);
}
return engine.toString(obj);
}

private AttributedString highlightValue(Map<String, Object> options
, String column
, Object obj, AttributedStyle defaultStyle) {
AttributedString out = highlightValue(options, column, obj);
boolean doDefault = true;
for (int i = 0; i < out.columnLength(); i++) {
if (out.styleAt(i).getStyle() != AttributedStyle.DEFAULT.getStyle()) {
doDefault = false;
break;
}
}
return doDefault ? new AttributedString(out, defaultStyle) : out;
}

@SuppressWarnings("unchecked")
private AttributedString highlightValue(Map<String, Object> options, String column, Object obj) {
AttributedString out = new AttributedString("");
Object raw = stringDemanded(options, obj) ? objectToString(options, obj) : obj;
boolean done = false;
AttributedString out = null;
Object raw = options.containsKey("toString") ? objectToString(options, obj) : obj;
Map<String, Object> hv = options.containsKey("highlightValue") ? (Map<String, Object>)options.get("highlightValue")
: new HashMap<>();
if (column != null) {
Map<String, Object> hv = options.containsKey("highlightValue") ? (Map<String, Object>)options.get("highlightValue")
: new HashMap<>();;
for (Map.Entry<String,Object> entry : hv.entrySet()) {
if (column.matches(entry.getKey())) {
if (!entry.getKey().equals("*") && column.matches(entry.getKey())) {
out = (AttributedString)engine.execute(hv.get(entry.getKey()), raw);
done = true;
break;
}
}
if (!done) {
if (out == null) {
for (Map.Entry<String,Function<Object,AttributedString>> entry : highlightValue.entrySet()) {
if (column.matches(entry.getKey())) {
if (!entry.getKey().equals("*") && column.matches(entry.getKey())) {
out = highlightValue.get(entry.getKey()).apply(raw);
done = true;
break;
}
}
}
}
if (!done) {
if (out == null) {
if (raw instanceof String) {
out = new AttributedString(columnValue((String)raw));
} else {
out = new AttributedString(columnValue(objectToString(options, raw)));
}
}
if (hv.containsKey("*")) {
out = (AttributedString)engine.execute(hv.get("*"), out);
} else if (highlightValue.containsKey("*")) {
out = highlightValue.get("*").apply(out);
}
return out;
}

@SuppressWarnings("unchecked")
private boolean stringDemanded(Map<String, Object> options, Object obj) {
Map<Class<?>, Object> toString = options.containsKey("objectToString") ? (Map<Class<?>, Object>)options.get("objectToString")
: new HashMap<>();;
return toString.containsKey(obj.getClass()) || objectToString.containsKey(obj.getClass());
}

@SuppressWarnings("unchecked")
private List<AttributedString> highlight(Map<String, Object> options, Object obj) {
List<AttributedString> out = new ArrayList<>();
Expand All @@ -1094,17 +1105,17 @@ private List<AttributedString> highlight(Map<String, Object> options, Object obj
if (obj == null) {
// do nothing
} else if (obj instanceof Map) {
out = highlightMap(keysToString((Map<Object, Object>)obj), width);
out = highlightMap(options, keysToString((Map<Object, Object>)obj), width);
} else if (obj instanceof Collection<?> || obj instanceof Object[]) {
Collection<?> collection = obj instanceof Collection<?> ? (Collection<?>)obj
: Arrays.asList((Object[])obj);
if (!collection.isEmpty()) {
if (collection.size() == 1 && !options.containsKey("oneRowTable")) {
Object elem = collection.iterator().next();
if (elem instanceof Map) {
out = highlightMap(keysToString((Map<Object, Object>)elem), width);
} else if (canConvert(elem) && !stringDemanded(options, obj)){
out = highlightMap(objectToMap(options, elem), width);
out = highlightMap(options, keysToString((Map<Object, Object>)elem), width);
} else if (canConvert(elem) && !options.containsKey("toString")){
out = highlightMap(options, objectToMap(options, elem), width);
} else {
out.add(new AttributedString(objectToString(options, obj)));
}
Expand Down Expand Up @@ -1239,8 +1250,8 @@ private List<AttributedString> highlight(Map<String, Object> options, Object obj
}
}
}
} else if (canConvert(obj) && !stringDemanded(options, obj)) {
out = highlightMap(objectToMap(options, obj), width);
} else if (canConvert(obj) && !options.containsKey("toString")) {
out = highlightMap(options, objectToMap(options, obj), width);
} else {
out.add(new AttributedString(objectToString(options, obj)));
}
Expand Down Expand Up @@ -1276,7 +1287,7 @@ private void toTabStops(List<Integer> columns, boolean rownum) {
}
}

private List<AttributedString> highlightMap(Map<String, Object> map, int width) {
private List<AttributedString> highlightMap(Map<String, Object> options, Map<String, Object> map, int width) {
List<AttributedString> out = new ArrayList<>();
int max = map.keySet().stream().map(String::length).max(Integer::compareTo).get();
for (Map.Entry<String, Object> entry : map.entrySet()) {
Expand All @@ -1290,12 +1301,13 @@ private List<AttributedString> highlightMap(Map<String, Object> map, int width)
asb = new AttributedStringBuilder().tabs(Arrays.asList(0, max + 1));
}
} else {
String v = engine.toString(entry.getValue());
if (v.contains("\n")) {
v = Arrays.asList(v.split("\\r?\\n")).toString();
AttributedStyle defaultStyle = AttributedStyle.DEFAULT.foreground(AttributedStyle.YELLOW);
AttributedString v = highlightValue(options, entry.getKey(), entry.getValue(), defaultStyle);
if (v.contains('\n')) {
v = new AttributedString(Arrays.asList(v.toString().split("\\r?\\n")).toString(), defaultStyle);
}
asb.append("\t");
asb.append(v, AttributedStyle.DEFAULT.foreground(AttributedStyle.YELLOW));
asb.append(v);
out.add(truncate(asb, width));
}
}
Expand Down Expand Up @@ -1342,6 +1354,8 @@ private Object prnt(Builtins.CommandInput input) {
" -r --rownum Display table row numbers",
" --structsOnTable Display structs and lists on table",
" -s --style=STYLE Use nanorc STYLE",
" --toString use object's toString() method to get print value",
" DEFAULT: object's fields are put to property map before printing",
" -w --width=WIDTH Display width (default terminal width)"
};
Options opt = Options.compile(usage).parse(input.xargs());
Expand All @@ -1353,6 +1367,9 @@ private Object prnt(Builtins.CommandInput input) {
if (opt.isSet("style")) {
options.put("style", opt.get("style"));
}
if (opt.isSet("toString")) {
options.put("toString", true);
}
if (opt.isSet("width")) {
options.put("width", opt.getNumber("width"));
}
Expand Down
4 changes: 4 additions & 0 deletions demo/src/main/scripts/hello2.jline
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ array.each {
:prnt $resp
}.identity{}

_reader = org.jline.builtins.SystemRegistry.get().consoleEngine().reader
prnt $_reader
prnt --toString $_reader

params = $@
prnt -s JSON $params

Expand Down
43 changes: 30 additions & 13 deletions demo/src/main/scripts/init.jline
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
#
# All imports added here are imported also to your groovy shell
#
import java.nio.file.*;
import java.nio.file.*
import java.util.regex.*
import org.jline.utils.*

PATH = [ROOT + 'scripts']

Expand All @@ -19,18 +21,8 @@ CONSOLE_OPTIONS.splitOutput = true
#
# customize prnt command
#
def _number2date(number){
def out = null
try {
out = number instanceof Long ? new Date(number) : number
} catch (Exception e) {
out = number
}
new org.jline.utils.AttributedString(out.toString())
}

def _reader2map(reader){
out = [:]
def out = [:]
out['othersGroupName'] = reader.othersGroupName
out['keyMap'] = reader.keyMap
out['autosuggestion'] = reader.autosuggestion
Expand All @@ -39,7 +31,7 @@ def _reader2map(reader){
}

def _reader2string(reader){
out = "["
def out = "["
out += 'othersGroupName:' + reader.othersGroupName + ', '
out += 'keyMap:' + reader.keyMap + ', '
out += 'autosuggestion:' + reader.autosuggestion + ', '
Expand All @@ -48,13 +40,38 @@ def _reader2string(reader){
out
}

def _number2date(number){
def out = null
try {
out = number instanceof Long ? new Date(number) : number
} catch (Exception e) {
out = number
}
new AttributedString(out.toString())
}

def _orgJline(p) {
def out = p
if (p.toString().matches('org.jline.*')) {
def m = Pattern.compile('(org.jline)(.*)').matcher(p.toString())
if (m.find()) {
def asb = new AttributedStringBuilder()
asb.append(m.group(1),AttributedStyle.DEFAULT.foreground(AttributedStyle.YELLOW + AttributedStyle.BRIGHT))
asb.append(m.group(2))
out = asb.toAttributedString()
}
}
out
}

PRNT_OPTIONS = [:]
PRNT_OPTIONS['objectToMap'] = [:]
PRNT_OPTIONS['objectToString'] = [:]
PRNT_OPTIONS['highlightValue'] = [:]
PRNT_OPTIONS['objectToMap'].put(org.jline.reader.impl.LineReaderImpl, _reader2map)
PRNT_OPTIONS['objectToString'].put(org.jline.reader.impl.LineReaderImpl, _reader2string)
PRNT_OPTIONS['highlightValue'].put('time.*', _number2date)
PRNT_OPTIONS['highlightValue'].put('*', _orgJline)
#
# custom Groovy pipes
#
Expand Down

0 comments on commit 4523408

Please sign in to comment.