Code Monkey home page Code Monkey logo

Comments (2)

jvalkeal avatar jvalkeal commented on July 19, 2024

It'd be nice to have more info available about origins of an options. All this is currently hidden inside parser and not exposed. We'll see if it's possible to expose these.

There are some special handling about options for short vs. long formats mostly to support posix style short options. Booleans are one of those special cases.

from spring-shell.

yaharga avatar yaharga commented on July 19, 2024

Here's how I went about it, after digging through the code and understanding how it is done. Perhaps it'll help simplify what needs to be exposed. The raw arguments are given through a CommandContext#getRawArgs().

I create the class once the command itself is created, and then when I get the command context, I pass the raw args. Hope this helps others!

package com.example.spring.shell;

import org.springframework.shell.command.CommandRegistration;
import org.springframework.shell.command.parser.*;

import org.apache.commons.lang3.tuple.Pair;

import java.util.stream.Collectors;
import java.util.*;

/**
 * Class that parses a command; distinguishes the option given and its arguments.
 */
public class Parser {
    public static final String LONG_NAME_SYMBOL = "--";
    public static final String SHORT_NAME_SYMBOL = "-";

    private final Lexer.DefaultLexer lexer;

    /**
     * <p>Default constructor, prepares the lexer that parses the command.</p>
     * 
     * <p>
     *  Tokenize arguments and generate syntax tree results from tokens;
     *  result from it is then fed into the loop that visists the nodes.
     * </p>
     * 
     * @param command Command registration where parsing would occur.
     */
    public Parser(CommandRegistration) {
        var configuration = new ParserConfig();
        var registration  = Map.of(command.getCommand(), command);
        var model         = new CommandModel(registration, configuration);

        this.lexer = new Lexer.DefaultLexer(model, configuration);
    }

    /**
     * Generate syntax tree results from tokens; result from it is then fed into node visitor.
     * 
     * @param longs  Component long names to check against command options.
     * @param shorts Component short names to check against command options.
     * @param args   Raw arguments passed into an executing command.
     * @return {@code Pair} where the key is whether the option was selected in the command,
     * and the value is whether there were any argument values given.
     */
    public Pair<Boolean, Boolean> parse(String[] longs, Character[] shorts, String... args) {
        var list   = Arrays.asList(args);
        var ast    = new Ast.DefaultAst();
        var tokens = lexer.tokenize(list).tokens();
        var nodes  = ast.generate(tokens).nonterminalNodes();

        for (NonterminalAstNode ntn : nodes) {          // Loop through all command text nodes.
            if (ntn instanceof CommandNode cn) {        // Only proceed through command instance nodes.
                for (AstNode node : cn.getChildren()) { // Loop through children of the syntax tree nodes.
                    if (node instanceof OptionNode on && selected(longs, shorts, on.getName())) {
                        // Once an option node is found that was selected, return the appropriate result.
                        return Pair.of(true, on.getChildren().isEmpty());
                    }
                }
            }
        }

        // If option was not found within command, it means option was missing, and so were its arguments.
        return Pair.of(false, true);
    }

    /**
     * Validates whether the option was selected within the parser command.
     * 
     * @param longs  Array of long names to search through to see if one was selected.
     * @param shorts Array of short names to search through to see if one was selected.
     * @param name   Name given to match against within the long and short names.
     * @return True if match is found.
     */
    private boolean selected(String[] longs, Character[] shorts, String name) {
        if (name.startsWith(LONG_NAME_SYMBOL)) { // Search through long names if name is a long name.
            return Arrays.stream(longs).map(n -> LONG_NAME_SYMBOL + n).anyMatch(name::equals);
        } else if (name.startsWith(SHORT_NAME_SYMBOL)) { // Search through short names if name is a short name.
            var names  = Arrays.stream(shorts).map(n -> SHORT_NAME_SYMBOL + n).collect(Collectors.toSet());
            var length = name.length();
            if (length == 2) { // If simple singular short name.
                return names.contains(name);
            } else if (length > 2) { // If name is a compound short name (more than a character used -iv).
                for (int i = 1; i < length; i++) {
                    if (names.contains("-" + name.charAt(i))) return true;
                }
            }
        }

        return false; // No match found.
    }
}

from spring-shell.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.