picocli.CommandLine.Mixin Java Examples

The following examples show how to use picocli.CommandLine.Mixin. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RangeTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
// test for https://github.com/remkop/picocli/issues/564
public void testMixinsWithVariableIndex() {
    @Command(name = "testCommand", description = "Example for issue 564")
    class TestCommand {

        @Mixin private CommonMixinOne myCommonMixinOne;

        @Parameters(index = "1", paramLabel = "TEST-COMMAND-PARAM")
        private String testCommandParam;

        @Mixin private CommonMixinTwo myCommonMixinTwo;
    }

    CommandLine cmd = new CommandLine(new TestCommand());

    String expected = String.format("" +
            "Usage: testCommand COMMON-PARAM-ONE TEST-COMMAND-PARAM COMMON-PARAM-TWO%n" +
            "Example for issue 564%n" +
            "      COMMON-PARAM-ONE%n" +
            "      TEST-COMMAND-PARAM%n" +
            "      COMMON-PARAM-TWO%n");
    String actual = cmd.getUsageMessage();
    assertEquals(expected, actual);
}
 
Example #2
Source File: DebugDbCommand.java    From teku with Apache License 2.0 6 votes vote down vote up
@Command(
    name = "get-deposits",
    description = "List the ETH1 deposit information stored in the database",
    mixinStandardHelpOptions = true,
    showDefaultValues = true,
    abbreviateSynopsis = true,
    versionProvider = PicoCliVersionProvider.class,
    synopsisHeading = "%n",
    descriptionHeading = "%nDescription:%n%n",
    optionListHeading = "%nOptions:%n",
    footerHeading = "%n",
    footer = "Teku is licensed under the Apache License 2.0")
public int getDeposits(@Mixin final DataOptions dataOptions) throws Exception {
  try (final YamlEth1EventsChannel eth1EventsChannel = new YamlEth1EventsChannel(System.out);
      final Database database = createDatabase(dataOptions)) {
    final DepositStorage depositStorage =
        DepositStorage.create(eth1EventsChannel, database, true);
    depositStorage.replayDepositEvents().join();
  }
  return 0;
}
 
Example #3
Source File: ReflectionConfigGenerator.java    From picocli with Apache License 2.0 6 votes vote down vote up
private void visitAnnotatedFields(Class<?> cls) {
    if (cls == null) {
        return;
    }
    ReflectedClass reflectedClass = getOrCreateClass(cls);
    Field[] declaredFields = cls.getDeclaredFields();
    for (Field f : declaredFields) {
        if (f.isAnnotationPresent(CommandLine.Spec.class)) {
            reflectedClass.addField(f);
        }
        if (f.isAnnotationPresent(CommandLine.ParentCommand.class)) {
            reflectedClass.addField(f);
        }
        if (f.isAnnotationPresent(Mixin.class)) {
            reflectedClass.addField(f);
        }
        if (f.isAnnotationPresent(CommandLine.Unmatched.class)) {
            reflectedClass.addField(f);
        }
    }
    visitAnnotatedFields(cls.getSuperclass());
}
 
Example #4
Source File: AbstractCommandSpecProcessor.java    From picocli with Apache License 2.0 6 votes vote down vote up
private boolean isSubcommand(ExecutableElement method, RoundEnvironment roundEnv) {
    Element typeElement = method.getEnclosingElement();
    if (typeElement.getAnnotation(Command.class) != null && typeElement.getAnnotation(Command.class).addMethodSubcommands()) {
        return true;
    }
    if (typeElement.getAnnotation(Command.class) == null) {
        Set<Element> elements = new HashSet<Element>(typeElement.getEnclosedElements());

        // The class is a Command if it has any fields or methods annotated with the below:
        return roundEnv.getElementsAnnotatedWith(Option.class).removeAll(elements)
                || roundEnv.getElementsAnnotatedWith(Parameters.class).removeAll(elements)
                || roundEnv.getElementsAnnotatedWith(Mixin.class).removeAll(elements)
                || roundEnv.getElementsAnnotatedWith(ArgGroup.class).removeAll(elements)
                || roundEnv.getElementsAnnotatedWith(Unmatched.class).removeAll(elements)
                || roundEnv.getElementsAnnotatedWith(Spec.class).removeAll(elements);
    }
    return false;
}
 
Example #5
Source File: LoggingSubSub.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Command
void subsubsubmethod(@Mixin LoggingMixin loggingMixin) {
    logger.trace("Hi (tracing)   from app subsub subsubsubmethod");
    logger.debug("Hi (debugging) from app subsub subsubsubmethod");
    logger.info ("Hi (info)      from app subsub subsubsubmethod");
    logger.warn ("Hi (warning)   from app subsub subsubsubmethod");
}
 
Example #6
Source File: ArgGroupTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Command(mixinStandardHelpOptions = true)
void groupFirst(@ArgGroup(multiplicity = "0..1") Composite composite, @Mixin SomeMixin mixin, int[] posInt, @Option(names = "-s") String[] strings) {
    this.myMixin = mixin;
    this.myComposite = composite;
    this.myPositionalInt = posInt;
    this.myStrings = strings;
    invoked.add(InvokedSub.groupFirst);
}
 
Example #7
Source File: ArgGroupTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Command(mixinStandardHelpOptions = true)
void posAndOptAndMixin(int[] posInt, @Option(names = "-s") String[] strings, @Mixin SomeMixin mixin, @ArgGroup(multiplicity = "0..1") Composite composite) {
    this.myMixin = mixin;
    this.myComposite = composite;
    this.myPositionalInt = posInt;
    this.myStrings = strings;
    invoked.add(InvokedSub.posAndOptAndMixin);
}
 
Example #8
Source File: ArgGroupTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Command(mixinStandardHelpOptions = true)
void posAndMixin(int[] posInt, @ArgGroup(multiplicity = "0..1") Composite composite, @Mixin SomeMixin mixin) {
    this.myMixin = mixin;
    this.myComposite = composite;
    this.myPositionalInt = posInt;
    invoked.add(InvokedSub.posAndMixin);
}
 
Example #9
Source File: Sub.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Command
void subsubmethod(@Mixin LoggingMixin loggingMixin) {
    logger.trace("Hi (tracing)   from app sub subsubmethod");
    logger.debug("Hi (debugging) from app sub subsubmethod");
    logger.info ("Hi (info)      from app sub subsubmethod");
    logger.warn ("Hi (warning)   from app sub subsubmethod");
}
 
Example #10
Source File: AbstractCommandSpecProcessor.java    From picocli with Apache License 2.0 5 votes vote down vote up
private void buildMixins(RoundEnvironment roundEnv, Context context) {
    logger.fine("Building mixins...");
    Set<? extends Element> explicitMixins = roundEnv.getElementsAnnotatedWith(Mixin.class);
    for (Element element : explicitMixins) {
        buildMixin(element, roundEnv, context);
    }
}
 
Example #11
Source File: TransitionCommand.java    From teku with Apache License 2.0 5 votes vote down vote up
@Command(
    name = "slots",
    description = "Process empty slots on the pre-state to get a post-state",
    mixinStandardHelpOptions = true,
    showDefaultValues = true,
    abbreviateSynopsis = true,
    versionProvider = PicoCliVersionProvider.class,
    synopsisHeading = "%n",
    descriptionHeading = "%nDescription:%n%n",
    optionListHeading = "%nOptions:%n",
    footerHeading = "%n",
    footer = "Teku is licensed under the Apache License 2.0")
public int slots(
    @Mixin InAndOutParams params,
    @Option(
            names = {"--delta", "-d"},
            description = "to interpret the slot number as a delta from the pre-state")
        boolean delta,
    @Parameters(paramLabel = "<number>", description = "Number of slots to process")
        long number) {
  return processStateTransition(
      params,
      (state, stateTransition) -> {
        UnsignedLong targetSlot = UnsignedLong.valueOf(number);
        if (delta) {
          targetSlot = state.getSlot().plus(targetSlot);
        }
        return stateTransition.process_slots(state, targetSlot);
      });
}
 
Example #12
Source File: LoggingSub.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Command(name = "subsubmethod")
void commandMethodSub(@Mixin LoggingMixin loggingMixin) {
    logger.trace("Hi (tracing)   from app sub subsubmethod");
    logger.debug("Hi (debugging) from app sub subsubmethod");
    logger.info ("Hi (info)      from app sub subsubmethod");
    logger.warn ("Hi (warning)   from app sub subsubmethod");
}
 
Example #13
Source File: LoggingSubSub.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Command
void commandMethodSub(@Mixin LoggingMixin loggingMixin) {
    String synopsis = spec.subcommands().get("commandMethodSub").getHelp().synopsis(0).trim();

    logger.trace("Hi (tracing)   from {}", synopsis);
    logger.debug("Hi (debugging) from {}", synopsis);
    logger.info("Hi (info)      from {}", synopsis);
    logger.warn("Hi (warning)   from {}", synopsis);
}
 
Example #14
Source File: LoggingSub.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Command
void commandMethodSub(@Mixin LoggingMixin loggingMixin) {
    String synopsis = spec.subcommands().get("commandMethodSub").getHelp().synopsis(0).trim();

    logger.trace("Hi (tracing)   from {}", synopsis);
    logger.debug("Hi (debugging) from {}", synopsis);
    logger.info("Hi (info)      from {}", synopsis);
    logger.warn("Hi (warning)   from {}", synopsis);
}
 
Example #15
Source File: PeerCommand.java    From teku with Apache License 2.0 5 votes vote down vote up
@Command(
    name = "generate",
    description = "Generate a list of peer ids",
    mixinStandardHelpOptions = true,
    showDefaultValues = true,
    abbreviateSynopsis = true,
    versionProvider = PicoCliVersionProvider.class,
    synopsisHeading = "%n",
    descriptionHeading = "%nDescription:%n%n",
    optionListHeading = "%nOptions:%n",
    footerHeading = "%n",
    footer = "Teku is licensed under the Apache License 2.0")
public void generate(
    @Mixin PeerGenerationParams params,
    @Option(
            names = {"-n", "--number"},
            arity = "1",
            required = true,
            description = "number of peerIDs to generate")
        int number)
    throws IOException {
  try {
    validateParamsAndGenerate(params.outputFile, number);
    spec.commandLine().getOut().println("Generated file " + params.outputFile);
  } catch (final Exception ex) {
    throw new ParameterException(spec.commandLine(), ex.getMessage());
  }
}
 
Example #16
Source File: DebugDbCommand.java    From teku with Apache License 2.0 5 votes vote down vote up
@Command(
    name = "get-latest-finalized-state",
    description = "Get the latest finalized state, if available, as SSZ",
    mixinStandardHelpOptions = true,
    showDefaultValues = true,
    abbreviateSynopsis = true,
    versionProvider = PicoCliVersionProvider.class,
    synopsisHeading = "%n",
    descriptionHeading = "%nDescription:%n%n",
    optionListHeading = "%nOptions:%n",
    footerHeading = "%n",
    footer = "Teku is licensed under the Apache License 2.0")
public int getLatestFinalizedState(
    @Mixin final DataOptions dataOptions,
    @Mixin final NetworkOptions networkOptions,
    @Option(
            required = true,
            names = {"--output", "-o"},
            description = "File to write state to")
        final Path outputFile)
    throws Exception {
  setConstants(networkOptions);
  try (final Database database = createDatabase(dataOptions)) {
    final Optional<BeaconState> state =
        database
            .createMemoryStore()
            .map(store -> store.getLatestFinalizedBlockAndState().getState());
    return writeState(outputFile, state);
  }
}
 
Example #17
Source File: DebugDbCommand.java    From teku with Apache License 2.0 5 votes vote down vote up
@Command(
    name = "get-finalized-state",
    description = "Get the finalized state, if available, as SSZ",
    mixinStandardHelpOptions = true,
    showDefaultValues = true,
    abbreviateSynopsis = true,
    versionProvider = PicoCliVersionProvider.class,
    synopsisHeading = "%n",
    descriptionHeading = "%nDescription:%n%n",
    optionListHeading = "%nOptions:%n",
    footerHeading = "%n",
    footer = "Teku is licensed under the Apache License 2.0")
public int getFinalizedState(
    @Mixin final DataOptions dataOptions,
    @Mixin final NetworkOptions networkOptions,
    @Option(
            required = true,
            names = {"--output", "-o"},
            description = "File to write state to")
        final Path outputFile,
    @Option(
            required = true,
            names = {"--slot", "-s"},
            description =
                "The slot to retrive the state for. If unavailable the closest available state will be returned")
        final long slot)
    throws Exception {
  setConstants(networkOptions);
  try (final Database database = createDatabase(dataOptions)) {
    return writeState(
        outputFile, database.getLatestAvailableFinalizedState(UnsignedLong.valueOf(slot)));
  }
}
 
Example #18
Source File: TransitionCommand.java    From teku with Apache License 2.0 5 votes vote down vote up
private InputStream selectInputStream(@Mixin final InAndOutParams params) throws IOException {
  if (params.pre != null) {
    final Path inputPath = Path.of(params.pre);
    return Files.newInputStream(inputPath);
  } else {
    return System.in;
  }
}
 
Example #19
Source File: AbstractCommandSpecProcessor.java    From picocli with Apache License 2.0 4 votes vote down vote up
private void registerSubcommands(List<AnnotationValue> typeMirrors,
                                 List<CommandSpec> result,
                                 Context context,
                                 RoundEnvironment roundEnv) {

    for (AnnotationValue typeMirror : typeMirrors) {
        Element subcommandElement = processingEnv.getElementUtils().getTypeElement(
                typeMirror.getValue().toString().replace('$', '.'));
        logger.fine("Processing subcommand: " + subcommandElement);

        if (isValidSubcommandHasNameAttribute(subcommandElement)) {
            CommandSpec commandSpec = buildCommand(subcommandElement, context, roundEnv);
            result.add(commandSpec);

            List<? extends Element> enclosedElements = subcommandElement.getEnclosedElements();
            for (Element enclosed : enclosedElements) {
                if (enclosed.getAnnotation(Command.class) != null) {
                    buildCommand(enclosed, context, roundEnv);
                }
                if (enclosed.getAnnotation(ArgGroup.class) != null) {
                    buildArgGroup(enclosed, context);
                }
                if (enclosed.getAnnotation(Mixin.class) != null) {
                    buildMixin(enclosed, roundEnv, context);
                }
                if (enclosed.getAnnotation(Option.class) != null) {
                    buildOption(enclosed, context);
                }
                if (enclosed.getAnnotation(Parameters.class) != null) {
                    buildParameter(enclosed, context);
                }
                if (enclosed.getAnnotation(Unmatched.class) != null) {
                    buildUnmatched(enclosed, context);
                }
                if (enclosed.getAnnotation(Spec.class) != null) {
                    buildSpec(enclosed, context);
                }
                if (enclosed.getAnnotation(ParentCommand.class) != null) {
                    buildParentCommand(enclosed, context);
                }
            }
        }
    }
}
 
Example #20
Source File: Top.java    From picocli with Apache License 2.0 4 votes vote down vote up
@Command
void sub1(@Mixin MyMixin mymixin) {
    verbose("Hello from sub1%n");
}
 
Example #21
Source File: CommandWithMixin.java    From picocli with Apache License 2.0 4 votes vote down vote up
@Command
public void doit(@Mixin CommonOption commonOptionParam,
                 @Option(names = "-z") int z,
                 @Parameters String arg0,
                 String arg1) {}
 
Example #22
Source File: RepeatableSubcommandsTest.java    From picocli with Apache License 2.0 4 votes vote down vote up
@Command
int methodSub(@Mixin MyMixin myMixin) {
    return ++methodSubInvocationCount * 100 + myMixin.x;
}
 
Example #23
Source File: ArgGroupTest.java    From picocli with Apache License 2.0 4 votes vote down vote up
@Command(mixinStandardHelpOptions = true)
void withMixin(@Mixin SomeMixin mixin, @ArgGroup(multiplicity = "0..1") Composite composite) {
    this.myMixin = mixin;
    this.myComposite = composite;
    invoked.add(withMixin);
}
 
Example #24
Source File: App.java    From picocli with Apache License 2.0 4 votes vote down vote up
@Command
public int commandMethod(@Option(names = "-x") int x, @Mixin ProviderMixin pm) {
    return 0;
}
 
Example #25
Source File: CommandWithMixin.java    From picocli with Apache License 2.0 4 votes vote down vote up
@Command
public void doit(@Mixin CommonOption commonOptionParam,
                 @Option(names = "-z") int z,
                 @Parameters String arg0,
                 String arg1) {}
 
Example #26
Source File: DebugDbCommand.java    From teku with Apache License 2.0 4 votes vote down vote up
private void setConstants(@Mixin final NetworkOptions networkOptions) {
  Constants.setConstants(
      NetworkDefinition.fromCliArg(networkOptions.getNetwork()).getConstants());
}
 
Example #27
Source File: TransitionCommand.java    From teku with Apache License 2.0 4 votes vote down vote up
private OutputStream selectOutputStream(@Mixin final InAndOutParams params) throws IOException {
  return params.post != null ? Files.newOutputStream(Path.of(params.post)) : System.out;
}