Java源码示例:picocli.CommandLine.Mixin

示例1
@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;
}
 
示例2
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;
}
 
示例3
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());
}
 
示例4
@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);
}
 
示例5
@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);
      });
}
 
示例6
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;
  }
}
 
示例7
@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)));
  }
}
 
示例8
@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);
  }
}
 
示例9
@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());
  }
}
 
示例10
@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);
}
 
示例11
@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);
}
 
示例12
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);
    }
}
 
示例13
@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);
}
 
示例14
@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);
}
 
示例15
@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);
}
 
示例16
@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");
}
 
示例17
@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");
}
 
示例18
@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");
}
 
示例19
private OutputStream selectOutputStream(@Mixin final InAndOutParams params) throws IOException {
  return params.post != null ? Files.newOutputStream(Path.of(params.post)) : System.out;
}
 
示例20
private void setConstants(@Mixin final NetworkOptions networkOptions) {
  Constants.setConstants(
      NetworkDefinition.fromCliArg(networkOptions.getNetwork()).getConstants());
}
 
示例21
@Command
public void doit(@Mixin CommonOption commonOptionParam,
                 @Option(names = "-z") int z,
                 @Parameters String arg0,
                 String arg1) {}
 
示例22
@Command
public int commandMethod(@Option(names = "-x") int x, @Mixin ProviderMixin pm) {
    return 0;
}
 
示例23
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);
                }
            }
        }
    }
}
 
示例24
@Command(mixinStandardHelpOptions = true)
void withMixin(@Mixin SomeMixin mixin, @ArgGroup(multiplicity = "0..1") Composite composite) {
    this.myMixin = mixin;
    this.myComposite = composite;
    invoked.add(withMixin);
}
 
示例25
@Command
int methodSub(@Mixin MyMixin myMixin) {
    return ++methodSubInvocationCount * 100 + myMixin.x;
}
 
示例26
@Command
void sub1(@Mixin MyMixin mymixin) {
    verbose("Hello from sub1%n");
}
 
示例27
@Command
public void doit(@Mixin CommonOption commonOptionParam,
                 @Option(names = "-z") int z,
                 @Parameters String arg0,
                 String arg1) {}