The CommandContext can be retrieved thatnks to the ExecutableBuilder.
189875
void execute(ExecutableBuilder builder,
            int timeout,
            TimeUnit unit) throws
            CommandLineException,
            InterruptedException, ExecutionException, TimeoutException {
        Future<Void> task = executorService.submit(() -> {
            builder.build().execute();
            return null;
        });
        try {
            if (timeout <= 0) { //Synchronous
                task.get();
            } else { // Guarded execution
                try {
                    task.get(timeout, unit);
                } catch (TimeoutException ex) {
                    // First make the context unusable
                    CommandContext c = builder.getCommandContext();
                    if (c instanceof TimeoutCommandContext) {
                        ((TimeoutCommandContext) c).timeout();
                    }
                    // Then cancel the task.
                    task.cancel(true);
                    throw ex;
                }
            }
        } catch (InterruptedException ex) {
            // Could have been interrupted by user (Ctrl-C)
            Thread.currentThread().interrupt();
            cancelTask(task, builder.getCommandContext(), null);
            // Interrupt running operation.
            CommandContext c = builder.getCommandContext();
            if (c instanceof TimeoutCommandContext) {
                ((TimeoutCommandContext) c).interrupted();
            }
            throw ex;
        }
    }
129263
protected void ensureExecutionInitialized() {
    if (execution == null && executionId != null) {
      execution = Context
          .getCommandContext()
          .getExecutionManager()
          .findExecutionById(executionId);
    }
  }
547742
function compile(context, commands) {
    let ii, cmd, limitOptions;

    // log.debug('limit: in-compile cmds:', commands);

    // look for the limit commands within the commands
    for (ii = commands.length - 1; ii >= 0; ii--) {
        cmd = commands[ii];
        if (cmd[0] === LIMIT) {
            // cmdLimit = cmd;
            limitOptions = {
                offset: context.valueOf(cmd[2]),
                limit: context.valueOf(cmd[1])
            };
            commands.splice(ii, 1);
        } else if (limitOptions && cmd[0] === ENTITY_FILTER) {
            // set the options object of the entityFilter command
            if (limitOptions) {
                cmd[3] = { ...cmd[3], ...limitOptions };
            }
            limitOptions = null;
        }
    }

    // if we still have an open limit and no entity filter was found, add one
    if (limitOptions) {
        commands.unshift([ENTITY_FILTER, null, null, limitOptions]);
    }

    return commands;
}
390316
def cmdline(executable):
    

    args = [executable.executable]
    indexed_args = []

    for parameter in executable:

        optional = (parameter.type == 'boolean') or parameter.default
        has_value = parameter.type != 'boolean'


        if parameter.longflag:  # use longflag where possible
            flag = "--%s" % parameter.longflag
        elif parameter.flag:
            flag = "-%s VALUE" % parameter.flag
        elif parameter.index:
            flag = parameter.name
            optional = False


        if has_value:
            flag += " VALUE"

        if optional:
            flag = "[" + flag + "]"

        if parameter.index:
            indexed_args.insert(int(parameter.index), flag)
        else:
            args.append(flag)

    return args + indexed_args
1189025
private static ContextRuntime getRootContext(final Injector injector,
                                               final Configuration rootContextConfiguration,
                                               final Optional<Configuration> rootServiceConfiguration)
      throws ContextClientCodeException {
    final ContextRuntime result;
    if (rootServiceConfiguration.isPresent()) {
      final Injector rootServiceInjector;
      try {
        rootServiceInjector = injector.forkInjector(rootServiceConfiguration.get());
      } catch (final BindException e) {
        throw new ContextClientCodeException(ContextClientCodeException.getIdentifier(rootContextConfiguration),
            Optional.<String>empty(), "Unable to instatiate the root context", e);
      }
      result = new ContextRuntime(rootServiceInjector, rootContextConfiguration);
    } else {
      result = new ContextRuntime(injector.forkInjector(), rootContextConfiguration);
    }
    return result;
  }
1111967
private InstanceContext findAgentContext( Application application, Instance instance ) {

		Instance scopedInstance = InstanceHelpers.findScopedInstance( instance );
		return new InstanceContext( application, scopedInstance );
	}
613954
public static void update( CommandExecutionContext executionContext, Instance createdInstance ) {

		if( executionContext != null ) {
			createdInstance.data.put( executionContext.getNewVmMarkerKey(), executionContext.getNewVmMarkerValue());
			executionContext.getGlobalVmNumber().incrementAndGet();
			executionContext.getAppVmNumber().incrementAndGet();
		}
	}
71824
function getSubCommands(context, command) {
  var commands = cli.getMapping(context).requisition.system.commands;
  var subcommands = commands.getAll().filter(function(subcommand) {
    return subcommand.name.indexOf(command.name) === 0 &&
           subcommand.name !== command.name &&
           !subcommand.hidden;
  });

  subcommands.sort(function(c1, c2) {
    return c1.name.localeCompare(c2.name);
  });

  subcommands = subcommands.map(function(subcommand) {
    return subcommand.toJson();
  });

  return subcommands;
}
96686
@Override
    protected WeldCreationalContext<T> getCreationalContext(ManagedObjectInvocationContext<T> invocationContext) throws ManagedObjectException {

        ManagedObjectContext managedObjectContext = invocationContext.getManagedObjectContext();

        @SuppressWarnings("unchecked")
        WeldCreationalContext<T> creationalContext = managedObjectContext.getContextData(WeldCreationalContext.class);
        creationalContext = CreationalContextResolver.resolve(creationalContext, getBean());

        return creationalContext;
    }
480548
private static Properties getWindowsShellVariables()
        throws EnvironmentException
    {
        Properties properties = new Properties();
        // build the command based on the shell used: cmd.exe or command.com
        StringBuffer buffer = new StringBuffer( getWindowsUserShell() );
        buffer.append( " /C SET" );
        String cmdExec = buffer.toString();

        int exitValue = readEnvironment( cmdExec, properties );
        if( 0 != exitValue )
        {
            String message = "Environment process failed with non-zero exit code of " + exitValue;
            throw new EnvironmentException( message );
        }

        return properties;
    }
1083401
@Override
    protected void doHandle(CommandContext ctx) throws CommandLineException {

        final boolean v = verbose.isPresent(ctx.getParsedCommandLine());

        final OperationResponse response;
        boolean failed = false;
        boolean hasFile = file.getValue(ctx.getParsedCommandLine()) != null;
        try {
            final ModelNode request = buildRequest(ctx);
            OperationBuilder builder = new OperationBuilder(request, true);
            for (String path : getAttachments(ctx).getAttachedFiles()) {
                builder.addFileAsAttachment(new File(path));
            }
            final ModelControllerClient client = ctx.getModelControllerClient();
            try {
                response = client.executeOperation(builder.build(), OperationMessageHandler.DISCARD);
            } catch(Exception e) {
                throw new CommandFormatException("Failed to perform operation: " + e.getLocalizedMessage());
            }
            if (!Util.isSuccess(response.getResponseNode())) {
                String msg = formatBatchError(ctx, response.getResponseNode());
                if (msg == null) {
                    msg = Util.getFailureDescription(response.getResponseNode());
                }
                throw new CommandFormatException(msg);
            }

            ModelNode steps = response.getResponseNode().get(Util.RESULT);
            if (steps.isDefined()) {
                // Dispatch to non null response handlers.
                final Batch batch = ctx.getBatchManager().getActiveBatch();
                int i = 1;
                for (BatchedCommand cmd : batch.getCommands()) {
                    ModelNode step = steps.get("step-" + i);
                    if (step.isDefined()) {
                        if (cmd.getResponseHandler() != null) {
                            cmd.getResponseHandler().handleResponse(step, response);
                        }
                        i += 1;
                    }
                }
            }

        } catch(CommandLineException e) {
            failed = true;
            if (hasFile) {
                throw new CommandLineException("The batch failed with the following error: ", e);
            } else {
                throw new CommandLineException("The batch failed with the following error "
                        + "(you are remaining in the batch editing mode to have a chance to correct the error)", e);
            }
        } finally {
            // There is a change in behavior between the file and the added command
            // With a file, the batch is discarded, whatever the result.
            if (hasFile) {
                ctx.getBatchManager().discardActiveBatch();
            } else if (!failed) {
                if (ctx.getBatchManager().isBatchActive()) {
                    ctx.getBatchManager().discardActiveBatch();
                }
            }
        }

        if(v) {
            ctx.printDMR(response.getResponseNode());
        } else {
            ctx.printLine("The batch executed successfully");
            super.handleResponse(ctx, response.getResponseNode(), true);
        }
    }
1351567
private Object exec(StatementContext statement) {
    if (statement == null)
      return null;
    return statement.accept(visitor);
  }
940368
private void registerCommandExecutors(PageComponentContext context){
    	context.register(GlobalCommandIds.SAVE, new SaveCommandExecutor());
    	context.register(GlobalCommandIds.SAVE_AS, new SaveAsCommandExecutor());
    }
183137
private void processCommand(List<String> command) throws Exception {
        processBuilder.command(command);
        Process p = processBuilder.start();
        checkReturnCode(p, processBuilder.command().toString(), ReturnCode.OK.getValue(), ReturnCode.ALREADY_EXISTS.getValue());
        if (!acceptLicense) {
            throw new BuildException("To install a feature, you must accept the feature's license terms and conditions.");
        }
    }
547530
def help(context, command):
    ''''''
    if command:
        cmd = cli.commands.get(command, None)
        if cmd:
            context.info_name = command
            click.echo(cmd.get_help(context))
        else:
            raise click.ClickException('no command: %s' % command)
    else:
        click.echo(cli.get_help(context))
957563
protected ApplicationContext getApplicationContext(JobExecutionContext context)
            throws SchedulerException {

        final SchedulerContext schedulerContext = context.getScheduler().getContext();
        ApplicationContext applicationContext =  (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY);

        // show keys in context
        if(applicationContext==null) {
            logger.error(APPLICATION_CONTEXT_KEY+" is empty in "+ schedulerContext+":");
            if(schedulerContext.getKeys()!=null) {
                for (String key : schedulerContext.getKeys()) {
                    Object value = schedulerContext.get(key);
                    String valueText = value!=null ? value.toString() : "<NULL>";
                    logger.info("    {} = {}", key, valueText);
                }
            }
        }

        return applicationContext;
    }
1088856
public boolean execute(Context context)
     throws Exception {
        if(context == null)
            throw new IllegalArgumentException();

        if(!_frozen)
            _frozen = true;

        boolean result = false;
        Exception saveException = null;
        for(int i = 0; i < _commands.length; i++) {
            try {
                result = _commands[i].execute(context);
                if(result)
                    break;
            }
            catch(Exception e) {
                saveException = e;
            }
        }

        if(saveException != null)
            throw saveException;
        else return result;
    }