Skip to content

Commit

Permalink
Started refactoring CLI commands to use more shared code.
Browse files Browse the repository at this point in the history
  • Loading branch information
david-waltermire committed Nov 1, 2024
1 parent 3d5216c commit 970258c
Show file tree
Hide file tree
Showing 17 changed files with 346 additions and 214 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import gov.nist.secauto.metaschema.cli.processor.command.ExtraArgument;
import gov.nist.secauto.metaschema.cli.processor.command.ICommand;
import gov.nist.secauto.metaschema.cli.processor.command.ICommandExecutor;
import gov.nist.secauto.metaschema.core.util.CollectionUtil;
import gov.nist.secauto.metaschema.core.util.IVersionInfo;
import gov.nist.secauto.metaschema.core.util.ObjectUtils;

Expand All @@ -35,11 +36,10 @@
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -164,6 +164,13 @@ private ExitStatus parseCommand(String... args) {
assert commandArgs != null;
CallingContext callingContext = new CallingContext(commandArgs);

if (LOGGER.isDebugEnabled()) {
String commandChain = callingContext.getCalledCommands().stream()
.map(ICommand::getName)
.collect(Collectors.joining(" -> "));
LOGGER.debug("Processing command chain: {}", commandChain);
}

ExitStatus status;
// the first two arguments should be the <command> and <operation>, where <type>
// is the object type
Expand All @@ -177,10 +184,16 @@ private ExitStatus parseCommand(String... args) {
return status;
}

@NonNull
protected final List<ICommand> getTopLevelCommands() {
List<ICommand> retval = Collections.unmodifiableList(commands);
assert retval != null;
return retval;
return CollectionUtil.unmodifiableList(commands);
}

@NonNull
protected final Map<String, ICommand> getTopLevelCommandsByName() {
return ObjectUtils.notNull(getTopLevelCommands()
.stream()
.collect(Collectors.toUnmodifiableMap(ICommand::getName, Function.identity())));
}

private static void handleNoColor() {
Expand Down Expand Up @@ -230,63 +243,43 @@ public class CallingContext {
@NonNull
private final List<Option> options;
@NonNull
private final Deque<ICommand> calledCommands;
private final List<ICommand> calledCommands;
@Nullable
private final ICommand targetCommand;
@NonNull
private final List<String> extraArgs;

@SuppressFBWarnings(value = "CT_CONSTRUCTOR_THROW", justification = "Use of final fields")
public CallingContext(@NonNull List<String> args) {
Map<String, ICommand> topLevelCommandMap = getTopLevelCommands().stream()
.collect(Collectors.toUnmodifiableMap(ICommand::getName, Function.identity()));

@SuppressWarnings("PMD.LooseCoupling") LinkedList<ICommand> calledCommands = new LinkedList<>();
List<Option> options = new LinkedList<>(OPTIONS);
Deque<ICommand> calledCommands = new LinkedList<>();
List<String> extraArgs = new LinkedList<>();

boolean endArgs = false;
for (String arg : args) {
if (endArgs || arg.startsWith("-")) {
AtomicBoolean endArgs = new AtomicBoolean();
args.forEach(arg -> {
if (endArgs.get() || arg.startsWith("-")) {
extraArgs.add(arg);
} else if ("--".equals(arg)) {
endArgs = true;
endArgs.set(true);
} else {
ICommand command;
if (calledCommands.isEmpty()) {
command = topLevelCommandMap.get(arg);
} else {
command = calledCommands.getLast();
command = command.getSubCommandByName(arg);
}
ICommand command = calledCommands.isEmpty()
? getTopLevelCommandsByName().get(arg)
: calledCommands.getLast().getSubCommandByName(arg);

if (command == null) {
extraArgs.add(arg);
endArgs = true;
endArgs.set(true);
} else {
calledCommands.add(command);
options.addAll(command.gatherOptions());
}
}
}

if (LOGGER.isDebugEnabled()) {
String commandChain = calledCommands.stream()
.map(ICommand::getName)
.collect(Collectors.joining(" -> "));
LOGGER.debug("Processing command chain: {}", commandChain);
}

for (ICommand cmd : calledCommands) {
options.addAll(cmd.gatherOptions());
}

options = Collections.unmodifiableList(options);
extraArgs = Collections.unmodifiableList(extraArgs);

assert options != null;
assert extraArgs != null;
});

this.options = options;
this.calledCommands = calledCommands;
this.extraArgs = extraArgs;
this.calledCommands = CollectionUtil.unmodifiableList(calledCommands);
this.targetCommand = calledCommands.peekLast();
this.options = CollectionUtil.unmodifiableList(options);
this.extraArgs = CollectionUtil.unmodifiableList(extraArgs);
}

@NonNull
Expand All @@ -296,7 +289,7 @@ public CLIProcessor getCLIProcessor() {

@Nullable
public ICommand getTargetCommand() {
return calledCommands.peekLast();
return targetCommand;
}

@NonNull
Expand All @@ -305,7 +298,7 @@ protected List<Option> getOptionsList() {
}

@NonNull
private Deque<ICommand> getCalledCommands() {
private List<ICommand> getCalledCommands() {
return calledCommands;
}

Expand Down Expand Up @@ -499,7 +492,7 @@ protected String buildHelpCliSyntax() {
StringBuilder builder = new StringBuilder(64);
builder.append(getExec());

Deque<ICommand> calledCommands = getCalledCommands();
List<ICommand> calledCommands = getCalledCommands();
if (!calledCommands.isEmpty()) {
builder.append(calledCommands.stream()
.map(ICommand::getName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,21 @@

package gov.nist.secauto.metaschema.cli.processor.command;

import gov.nist.secauto.metaschema.core.util.ObjectUtils;
import gov.nist.secauto.metaschema.core.util.UriUtils;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Collections;

import edu.umd.cs.findbugs.annotations.NonNull;
import nl.talsmasoftware.lazy4j.Lazy;

public abstract class AbstractTerminalCommand implements ICommand {
private static Lazy<Path> currentWorkingDirectory = Lazy.lazy(() -> Paths.get("").toAbsolutePath());

@SuppressWarnings("null")
@Override
Expand All @@ -25,7 +32,20 @@ public boolean isSubCommandRequired() {
return false;
}

protected static Path resolvePathAgainstCWD(@NonNull Path path) {
return Paths.get("").toAbsolutePath().resolve(path).normalize();
@NonNull
protected static Path getCurrentWorkingDirectory() {
return ObjectUtils.notNull(currentWorkingDirectory.get());
}

protected static Path resolveAgainstCWD(@NonNull Path path) {
return getCurrentWorkingDirectory().resolve(path).normalize();
}

protected static URI resolveAgainstCWD(@NonNull URI uri) {
return getCurrentWorkingDirectory().toUri().resolve(uri.normalize());
}

protected static URI resolveAgainstCWD(@NonNull String uri) throws URISyntaxException {
return UriUtils.toUri(uri, getCurrentWorkingDirectory().toUri());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import gov.nist.secauto.metaschema.core.model.constraint.IConstraint.Level;
import gov.nist.secauto.metaschema.core.util.ObjectUtils;

import org.eclipse.jdt.annotation.Owning;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
Expand Down Expand Up @@ -60,7 +61,7 @@ private static Schema toSchema(@NonNull List<? extends Source> schemaSources) th
* @throws SAXException
* if an error occurred while parsing the provided XML schemas
*/
public XmlSchemaContentValidator(@NonNull List<? extends Source> schemaSources) throws SAXException {
public XmlSchemaContentValidator(@Owning @NonNull List<? extends Source> schemaSources) throws SAXException {
this(toSchema(ObjectUtils.requireNonNull(schemaSources, "schemaSources")));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ private UriUtils() {
* the base URI to use for URI normalization
* @return a new URI
* @throws URISyntaxException
* an error if the location string is not convertible to URI
* if the location string is not convertible to URI
*/
@SuppressWarnings("PMD.PreserveStackTrace")
@NonNull
Expand Down Expand Up @@ -91,12 +91,11 @@ public static URI relativize(URI base, URI other, boolean prepend) throws URISyn

private static boolean hasSameSchemeAndAuthority(URI base, URI other) {
String baseScheme = base.getScheme();
boolean retval = (baseScheme == null && other.getScheme() == null)
|| (baseScheme != null && baseScheme.equals(other.getScheme()));
boolean retval = baseScheme == null && other.getScheme() == null
|| baseScheme != null && baseScheme.equals(other.getScheme());
String baseAuthority = base.getAuthority();
retval = retval && ((baseAuthority == null && other.getAuthority() == null)
|| (baseAuthority != null && baseAuthority.equals(other.getAuthority())));
return retval;
return retval && (baseAuthority == null && other.getAuthority() == null
|| baseAuthority != null && baseAuthority.equals(other.getAuthority()));
}

/**
Expand Down Expand Up @@ -132,7 +131,7 @@ public static String prependRelativePath(String base, String target) {

// Construct the relative path
StringBuilder retval = new StringBuilder();
for (int j = 0; j < (baseSegments.length - segmentIndex); j++) {
for (int j = 0; j < baseSegments.length - segmentIndex; j++) {
retval.append("..");
if (retval.length() != 0) {
retval.append(URI_SEPERATOR);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

import gov.nist.secauto.metaschema.core.model.IAssemblyDefinition;
import gov.nist.secauto.metaschema.core.model.IAssemblyInstanceAbsolute;
import gov.nist.secauto.metaschema.core.model.IChoiceGroupInstance;
import gov.nist.secauto.metaschema.core.model.IChoiceInstance;
import gov.nist.secauto.metaschema.core.model.IContainerModelAbsolute;
import gov.nist.secauto.metaschema.core.model.IContainerModelSupport;
import gov.nist.secauto.metaschema.core.model.IFieldDefinition;
Expand Down Expand Up @@ -55,6 +57,22 @@ protected static void addInstance(
fieldInstances.put(effectiveName, field);
}

protected static void addInstance(
@NonNull IChoiceInstance choice,
@NonNull List<IModelInstanceAbsolute> modelInstances,
@NonNull List<IChoiceInstance> choiceInstances) {
modelInstances.add(choice);
choiceInstances.add(choice);
}

protected static void addInstance(
@NonNull IChoiceGroupInstance choiceGroup,
@NonNull List<IModelInstanceAbsolute> modelInstances,
@NonNull Map<String, IChoiceGroupInstance> choiceGroupInstances) {
modelInstances.add(choiceGroup);
choiceGroupInstances.put(choiceGroup.getGroupAsName(), choiceGroup);
}

@NonNull
protected static IAssemblyInstanceAbsolute newInstance(
@NonNull AssemblyReference obj,
Expand Down
Loading

0 comments on commit 970258c

Please sign in to comment.