Skip to content

Commit

Permalink
Introduced the Table and Row classes to simplify the print-out of tab…
Browse files Browse the repository at this point in the history
…les in CLI
  • Loading branch information
spoto committed Feb 27, 2024
1 parent 03143b9 commit c3d81ed
Show file tree
Hide file tree
Showing 8 changed files with 293 additions and 55 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,6 @@
import java.util.ServiceLoader;
import java.util.ServiceLoader.Provider;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import io.hotmoka.closeables.api.OnCloseHandler;
import io.mokamint.application.api.Application;
Expand All @@ -35,81 +32,82 @@
import io.mokamint.node.api.Transaction;
import io.mokamint.nonce.api.Deadline;
import io.mokamint.tools.AbstractCommand;
import io.mokamint.tools.AbstractTable;
import io.mokamint.tools.CommandException;
import io.mokamint.tools.Table;
import picocli.CommandLine.Command;
import picocli.CommandLine.Help.Ansi;
import picocli.CommandLine.Option;

@Command(name = "ls",
description = "List the available applications.",
showDefaultValues = true)
public class List extends AbstractCommand {

@Option(names = "--json", description = "print the output in JSON", defaultValue = "false")
private boolean json;

@Override
protected void execute() throws CommandException {
new ListApplications();
new MyTable().print();
}

private class ListApplications {
private final java.util.List<Provider<Application>> providers;
private final String[] names;
private final int slotsForNames;
private final String[] classNames;
private final int slotsForClassNames;
private final String[] descriptions;
private final int slotsForDescriptions;
/**
* Lists the available applications.
*/
private ListApplications() {
ServiceLoader<Application> serviceLoader = ServiceLoader.load(Application.class);
this.providers = serviceLoader.stream().collect(Collectors.toList());
this.names = new String[1 + providers.size()];
this.classNames = new String[names.length];
this.descriptions = new String[names.length];
fillColumns();
this.slotsForNames = Stream.of(names).mapToInt(String::length).max().getAsInt();
this.slotsForClassNames = Stream.of(classNames).mapToInt(String::length).max().getAsInt();
this.slotsForDescriptions = Stream.of(descriptions).mapToInt(String::length).max().getAsInt();
printRows();
private static class Row implements io.mokamint.tools.Row {
private final String name;
private final String className;
private final String description;

private Row(String name, String className, String description) {
this.name = name;
this.className = className;
this.description = description;
}

private void fillColumns() {
names[0] = "name";
classNames[0] = "class";
descriptions[0] = "description";

for (int pos = 1; pos < names.length; pos++) {
var type = providers.get(pos - 1).type();
classNames[pos] = type.getName();
Name annName = type.getAnnotation(Name.class);
names[pos] = annName != null ? annName.value() : "---";
Description annDescription = type.getAnnotation(Description.class);
descriptions[pos] = annDescription != null ? annDescription.value() : "---";

@Override
public String getColumn(int index) {
switch (index) {
case 0: return name;
case 1: return className;
case 2: return description;
default: throw new IndexOutOfBoundsException(index);
}
}

private void printRows() {
IntStream.iterate(0, i -> i + 1).limit(names.length).mapToObj(this::format).forEach(System.out::println);
}

private String format(int pos) {

@Override
public String toString(int pos, Table table) {
String result;

if (pos == 0)
result = String.format("%s %s %s",
center(names[pos], slotsForNames),
center(classNames[pos], slotsForClassNames),
center(descriptions[pos], slotsForDescriptions));
center(name, table.getSlotsForColumn(0)),
center(className, table.getSlotsForColumn(1)),
center(description, table.getSlotsForColumn(2)));
else
result = String.format("%s %s %s",
leftAlign(names[pos], slotsForNames),
leftAlign(classNames[pos], slotsForClassNames),
leftAlign(descriptions[pos], slotsForDescriptions));

leftAlign(name, table.getSlotsForColumn(0)),
leftAlign(className, table.getSlotsForColumn(1)),
leftAlign(description, table.getSlotsForColumn(2)));
return pos == 0 ? Ansi.AUTO.string("@|green " + result + "|@") : result;
}
}

private class MyTable extends AbstractTable {
private MyTable() {
super(new Row("name", "class", "description"), 3, json);
ServiceLoader.load(Application.class).stream().forEach(this::add);
}

private void add(Provider<Application> provider) {
var type = provider.type();
Name annName = type.getAnnotation(Name.class);
String name = annName != null ? annName.value() : "---";
Description annDescription = type.getAnnotation(Description.class);
String description = annDescription != null ? annDescription.value() : "---";
add(new Row(name, type.getName(), description));
}
}

@Name("App1")
@Description("a first simple application")
public static class App1 implements Application {
Expand Down
4 changes: 2 additions & 2 deletions io-mokamint-application-tools/src/main/java/module-info.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
*/
module io.mokamint.application.tools {
exports io.mokamint.application.tools;
opens io.mokamint.application.tools.internal to info.picocli; // for injecting CLI options
opens io.mokamint.application.tools.internal to info.picocli, com.google.gson; // for injecting CLI options and JSON print-out

// TODO: remove at the end
provides io.mokamint.application.api.Application with io.mokamint.application.tools.internal.List.App1, io.mokamint.application.tools.internal.List.App42;
uses io.mokamint.application.api.Application;
Expand Down
5 changes: 5 additions & 0 deletions io-mokamint-tools/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@
<artifactId>picocli</artifactId>
<version>4.7.2</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
Copyright 2024 Fausto Spoto
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package io.mokamint.tools;

import io.mokamint.tools.internal.TableImpl;

/**
* Partial implementation of a table of rows.
*/
public abstract class AbstractTable extends TableImpl {

/**
* Creates an empty table, without rows, with just its header.
*
* @param header the first row of this table, that gets added to it
* @param columns the number of elements in the rows of this table
* @param json true if and only if the print-out of the table must occur in JSON
*/
protected AbstractTable(Row header, int columns, boolean json) {
super(header, columns, json);
}
}
42 changes: 42 additions & 0 deletions io-mokamint-tools/src/main/java/io/mokamint/tools/Row.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
Copyright 2024 Fausto Spoto
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package io.mokamint.tools;

/**
* A row in a table, that can be printed by a tool command.
*/
public interface Row {

/**
* Yields the given column element of this row.
*
* @param index the index of the column, from 0 upwards
* @return the element
*/
String getColumn(int index);

/**
* Yields a string representation of this row, as it must
* be reported to the user. The position is relative to the head of the table:
* 0 is the first row (typically, the titles), 1 is the second row and so on.
*
* @param pos the position, relative to the head of the table
* @param table the table this row belongs to
* @return the string representation
*/
String toString(int pos, Table table);
}
55 changes: 55 additions & 0 deletions io-mokamint-tools/src/main/java/io/mokamint/tools/Table.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
Copyright 2024 Fausto Spoto
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package io.mokamint.tools;

/**
* A table of rows.
*/
public interface Table {

/**
* Adds the given row at the end of this table.
*
* @param row the row to add; it is assumed to have
* the same number of columns as this table
*/
void add(Row row);

/**
* Yields the number of characters that are used at most for the given column
* of this table.
*
* @param column the column index, starting at 0
* @return the number of characters
*/
int getSlotsForColumn(int column);

/**
* Calls {@link Row#toString(int, Table)} on each row of this table
* and concatenates the result with newlines as separators. If the table is empty
* (that is, if it only contains its heading), then the empty string is returned.
*
* @return the resulting concatenation
*/
@Override
String toString();

/**
* Prints this object on the screen.
*/
void print();
}

0 comments on commit c3d81ed

Please sign in to comment.