Skip to content

Commit

Permalink
More CLI refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
mikera committed Jan 14, 2024
1 parent 201e0e5 commit 6214bd3
Show file tree
Hide file tree
Showing 15 changed files with 82 additions and 88 deletions.
7 changes: 3 additions & 4 deletions convex-cli/src/main/java/convex/cli/AccountFund.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package convex.cli;

import convex.api.Convex;
import convex.core.crypto.AKeyPair;
import convex.core.data.Address;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import convex.api.Convex;
import convex.core.data.Address;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
Expand Down
30 changes: 30 additions & 0 deletions convex-cli/src/main/java/convex/cli/Helpers.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import convex.core.crypto.PFXTools;
import convex.core.util.Utils;
Expand Down Expand Up @@ -100,6 +102,34 @@ public static File createTempKeystore(String name, char[] password) {
}

}

public static int[] getPortList(String ports[], int count) throws NumberFormatException {
Pattern rangePattern = Pattern.compile(("([0-9]+)\\s*-\\s*([0-9]*)"));
List<String> portTextList = Helpers.splitArrayParameter(ports);
List<Integer> portList = new ArrayList<Integer>();
int countLeft = count;
for (int index = 0; index < portTextList.size() && countLeft > 0; index ++) {
String item = portTextList.get(index);
Matcher matcher = rangePattern.matcher(item);
if (matcher.matches()) {
int portFrom = Integer.parseInt(matcher.group(1));
int portTo = portFrom + count + 1;
if (!matcher.group(2).isEmpty()) {
portTo = Integer.parseInt(matcher.group(2));
}
for ( int portIndex = portFrom; portIndex <= portTo && countLeft > 0; portIndex ++, --countLeft ) {
portList.add(portIndex);
}
}
else if (item.strip().length() == 0) {
}
else {
portList.add(Integer.parseInt(item));
countLeft --;
}
}
return portList.stream().mapToInt(Integer::intValue).toArray();
}
}


66 changes: 7 additions & 59 deletions convex-cli/src/main/java/convex/cli/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@
import convex.cli.client.Status;
import convex.cli.client.Transaction;
import convex.cli.key.Key;
import convex.cli.local.Local;
import convex.cli.output.RecordOutput;
import convex.cli.peer.Peer;
import convex.core.Result;
import convex.core.crypto.AKeyPair;
import convex.core.crypto.PFXTools;
Expand Down Expand Up @@ -53,7 +55,6 @@
mixinStandardHelpOptions=true,
// headerHeading = "Usage:",
// synopsisHeading = "%n",
descriptionHeading = "%nDescription:%n%n",
parameterListHeading = "%nParameters:%n",
optionListHeading = "%nOptions:%n",
commandListHeading = "%nCommands:%n",
Expand All @@ -64,8 +65,7 @@ public class Main implements Runnable {

private static Logger log = LoggerFactory.getLogger(Main.class);


CommandLine commandLine=new CommandLine(this);
public CommandLine commandLine=new CommandLine(this);

@Option(names={ "-c", "--config"},
scope = ScopeType.INHERIT,
Expand All @@ -92,7 +92,7 @@ public class Main implements Runnable {
@Option(names={"-n", "--noninteractive"},
scope = ScopeType.INHERIT,
//defaultValue="",
description="Specify to disable interactiove prompts")
description="Specify to disable interactive prompts")
private boolean nonInteractive;

@Option(names={ "-v", "--verbose"},
Expand Down Expand Up @@ -136,9 +136,8 @@ public int mainExecute(String[] args) {
// in the defaults before running the full execute
try {
commandLine.parseArgs(args);
loadConfig();
} catch (Throwable t) {
System.err.println("unable to parse arguments " + t);
log.debug("Unable to parse arguments: " + t);
}

ch.qos.logback.classic.Logger parentLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
Expand Down Expand Up @@ -193,31 +192,6 @@ public int handleExecutionException(Exception ex, CommandLine commandLine, Parse
}

}

/**
* Loads the specified config file.
* @return true if config file correctly loaded, false otherwise (e.g. if it does not exist)
*/
protected boolean loadConfig() {
String filename=null;
if (configFilename != null && !configFilename.isEmpty()) {
filename = Helpers.expandTilde(configFilename);
}

if (filename!=null) {
File configFile = new File(filename);
if (configFile.exists()) {
PropertiesDefaultProvider defaultProvider = new PropertiesDefaultProvider(configFile);
commandLine.setDefaultValueProvider(defaultProvider);
return true;
} else {
log.warn("Config file does not exist: "+configFilename);
return false;
}
}
return false;
}


/**
* Get the currently configured password for the keystore. Will emit warning and default to
Expand Down Expand Up @@ -334,7 +308,7 @@ public KeyStore loadKeyStore(boolean isCreate) {
if (keyFile.exists()) {
keyStore = PFXTools.loadStore(keyFile, password);
} else if (isCreate) {
log.warn("No keystore exists, creating at: "+keyFile.getCanonicalPath());
log.debug("No keystore exists, creating at: "+keyFile.getCanonicalPath());
Helpers.createPath(keyFile);
keyStore = PFXTools.createStore(keyFile, password);
}
Expand Down Expand Up @@ -442,33 +416,7 @@ public void saveKeyStore() {
}
}

int[] getPortList(String ports[], int count) throws NumberFormatException {
Pattern rangePattern = Pattern.compile(("([0-9]+)\\s*-\\s*([0-9]*)"));
List<String> portTextList = Helpers.splitArrayParameter(ports);
List<Integer> portList = new ArrayList<Integer>();
int countLeft = count;
for (int index = 0; index < portTextList.size() && countLeft > 0; index ++) {
String item = portTextList.get(index);
Matcher matcher = rangePattern.matcher(item);
if (matcher.matches()) {
int portFrom = Integer.parseInt(matcher.group(1));
int portTo = portFrom + count + 1;
if (!matcher.group(2).isEmpty()) {
portTo = Integer.parseInt(matcher.group(2));
}
for ( int portIndex = portFrom; portIndex <= portTo && countLeft > 0; portIndex ++, --countLeft ) {
portList.add(portIndex);
}
}
else if (item.strip().length() == 0) {
}
else {
portList.add(Integer.parseInt(item));
countLeft --;
}
}
return portList.stream().mapToInt(Integer::intValue).toArray();
}


public void println(String s) {
if (s==null) s="null";
Expand Down
2 changes: 1 addition & 1 deletion convex-cli/src/main/java/convex/cli/client/Status.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
description="Reports on the current status of the network.")
public class Status extends AClientCommand {

private static final Logger log = LoggerFactory.getLogger(Status.class);
protected static final Logger log = LoggerFactory.getLogger(Status.class);

@ParentCommand
protected Main mainParent;
Expand Down
4 changes: 1 addition & 3 deletions convex-cli/src/main/java/convex/cli/client/Transaction.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public class Transaction extends AClientCommand {
@ParentCommand
protected Main mainParent;

private static final Logger log = LoggerFactory.getLogger(Transaction.class);
protected static final Logger log = LoggerFactory.getLogger(Transaction.class);

@Option(names={"--public-key"},
defaultValue="",
Expand Down Expand Up @@ -99,8 +99,6 @@ public void run() {
mainParent.printResult(result);
} catch (Exception e) {
throw new CLIError("Error executing transation",e);
} finally {
if (convex!=null) convex.close();
}
}

Expand Down
3 changes: 3 additions & 0 deletions convex-cli/src/main/java/convex/cli/key/AKeyCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
import convex.cli.Main;
import picocli.CommandLine.ParentCommand;

/**
* Base class for commands working with the configured key store
*/
public abstract class AKeyCommand implements Runnable {

@ParentCommand
Expand Down
2 changes: 1 addition & 1 deletion convex-cli/src/main/java/convex/cli/key/KeyGenerate.java
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public void run() {
mainParent.println(publicKeyHexString); // Output generated public key
PFXTools.setKeyPair(ks, kp, password); // TODO: key password?
}
log.info(count+ " keys successfully generated");
log.debug(count+ " keys successfully generated");
saveKeyStore();
} catch (Throwable e) {
throw Utils.sneakyThrow(e);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package convex.cli;
package convex.cli.local;

import convex.cli.Main;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.ParentCommand;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package convex.cli;
package convex.cli.local;

import convex.api.Applications;
import convex.cli.CLIError;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package convex.cli;
package convex.cli.local;

import java.util.ArrayList;
import java.util.HashSet;
Expand All @@ -8,6 +8,10 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import convex.cli.CLIError;
import convex.cli.Constants;
import convex.cli.Helpers;
import convex.cli.Main;
import convex.core.State;
import convex.core.crypto.AKeyPair;
import convex.core.data.AccountKey;
Expand Down Expand Up @@ -97,14 +101,12 @@ private List<AKeyPair> getPublicKeys(int n) {

@Override
public void run() {
Main mainParent = localParent.mainParent;

List<AKeyPair> keyPairList = getPublicKeys(count);

int peerPorts[] = null;
if (ports != null) {
try {
peerPorts = mainParent.getPortList(ports, count);
peerPorts = Helpers.getPortList(ports, count);
} catch (NumberFormatException e) {
log.warn("cannot convert port number " + e);
return;
Expand Down
5 changes: 5 additions & 0 deletions convex-cli/src/main/java/convex/cli/peer/APeerCommand.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package convex.cli.peer;

public abstract class APeerCommand implements Runnable {

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package convex.cli;
package convex.cli.peer;

import convex.cli.Main;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.ParentCommand;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package convex.cli;
package convex.cli.peer;

import java.io.File;
import java.security.KeyStore;

import convex.api.Convex;
import convex.cli.CLIError;
import convex.cli.Constants;
import convex.cli.Main;
import convex.cli.output.RecordOutput;
import convex.core.crypto.AKeyPair;
import convex.core.crypto.PFXTools;
Expand Down Expand Up @@ -36,7 +39,7 @@
aliases={"cr"},
mixinStandardHelpOptions=true,
description="Creates a keypair, new account and a funding stake: to run a local peer.")
public class PeerCreate implements Runnable {
public class PeerCreate extends APeerCommand {

private static final Logger log = LoggerFactory.getLogger(PeerCreate.class);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package convex.cli;
package convex.cli.peer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import convex.cli.CLIError;
import convex.cli.Main;
import convex.core.crypto.AKeyPair;
import convex.core.data.Address;
import convex.core.exceptions.TODOException;
Expand All @@ -20,7 +22,7 @@
*/

@Command(name = "start", aliases = { "st" }, mixinStandardHelpOptions = true, description = "Starts a local peer.")
public class PeerStart implements Runnable {
public class PeerStart extends APeerCommand {

private static final Logger log = LoggerFactory.getLogger(PeerStart.class);

Expand Down Expand Up @@ -85,6 +87,7 @@ public void run() {
return;
}
Address peerAddress = Address.create(addressNumber);
if (peerAddress==null) throw new CLIError("Invalid peer controller address: "+addressNumber);

if (remotePeerHostname == null) {

Expand Down
18 changes: 9 additions & 9 deletions convex-cli/src/test/java/convex/cli/CLIMainTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,40 +11,40 @@ public class CLIMainTest {
public void testMainGetPortList() {
Main mainApp = new Main();
String basicList[] = {"80", "90", "100", "101", "200"};
int result[] = mainApp.getPortList(basicList, 4);
int result[] = Helpers.getPortList(basicList, 4);
assertArrayEquals(new int[]{80, 90, 100, 101}, result);

String commaList[] = {"80,90,100,101,200"};
result = mainApp.getPortList(commaList, 4);
result = Helpers.getPortList(commaList, 4);
assertArrayEquals(new int[]{80, 90, 100, 101}, result);

String closedRange[] = {"100-200"};
result = mainApp.getPortList(closedRange, 4);
result = Helpers.getPortList(closedRange, 4);
assertArrayEquals(new int[]{100, 101, 102, 103}, result);

String openRange[] = {"100-"};
result = mainApp.getPortList(openRange, 6);
result = Helpers.getPortList(openRange, 6);
assertArrayEquals(new int[]{100, 101, 102, 103, 104, 105}, result);

String combinedClosedRange[] = {"80", "100-103", "200"};
result = mainApp.getPortList(combinedClosedRange, 6);
result = Helpers.getPortList(combinedClosedRange, 6);
assertArrayEquals(new int[]{80, 100, 101, 102, 103, 200}, result);

String combinedOpenRange[] = {"80", "100-", "200", "300"};
result = mainApp.getPortList(combinedOpenRange, 6);
result = Helpers.getPortList(combinedOpenRange, 6);
assertArrayEquals(new int[]{80, 100, 101, 102, 103, 104}, result);

String combinedCommaClosedRange[] = {"80,100-103,200"};
result = mainApp.getPortList(combinedCommaClosedRange, 6);
result = Helpers.getPortList(combinedCommaClosedRange, 6);
assertArrayEquals(new int[]{80, 100, 101, 102, 103, 200}, result);

String combinedCommaOpenRange[] = {"80,100-,200,300"};
result = mainApp.getPortList(combinedCommaOpenRange, 6);
result = Helpers.getPortList(combinedCommaOpenRange, 6);
assertArrayEquals(new int[]{80, 100, 101, 102, 103, 104}, result);

assertThrows(NumberFormatException.class, () -> {
String badNumberValue[] = {"80,100+,200,300"};
mainApp.getPortList(badNumberValue, 6);
Helpers.getPortList(badNumberValue, 6);
});
}

Expand Down

0 comments on commit 6214bd3

Please sign in to comment.