001/* 002 * (C) Copyright 2017 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * bdelbosc 018 */ 019package org.nuxeo.lib.stream.tools.command; 020 021import java.util.List; 022 023import org.apache.commons.cli.CommandLine; 024import org.apache.commons.cli.HelpFormatter; 025import org.apache.commons.cli.Options; 026import org.nuxeo.lib.stream.log.LogManager; 027import org.nuxeo.lib.stream.tools.CommandRegistry; 028 029/** 030 * @since 9.3 031 */ 032public class HelpCommand extends Command { 033 034 protected static final String NAME = "help"; 035 036 protected Options options; 037 038 @Override 039 public String name() { 040 return NAME; 041 } 042 043 @Override 044 public void updateOptions(Options options) { 045 this.options = options; 046 } 047 048 @Override 049 public boolean run(LogManager manager, CommandLine cmd) { 050 List<Command> commands = new CommandRegistry().commands(); 051 displayCommonOptions(); 052 if (cmd.getArgList().isEmpty()) { 053 commands.stream().filter(command -> !(command instanceof HelpCommand)).forEach(this::displayHelp); 054 } else { 055 String name = cmd.getArgList().get(0); 056 commands.stream().filter(command -> name.equals(command.name())).forEach(this::displayHelp); 057 } 058 return true; 059 } 060 061 protected void displayCommonOptions() { 062 HelpFormatter formatter = new HelpFormatter(); 063 formatter.setSyntaxPrefix(""); 064 formatter.printHelp("Usage: stream.sh [COMMAND] [Options]\nCommon options:", options); 065 } 066 067 protected void displayHelp(Command command) { 068 Options cmdOptions = new Options(); 069 command.updateOptions(cmdOptions); 070 HelpFormatter formatter = new HelpFormatter(); 071 formatter.setSyntaxPrefix("Command: "); 072 formatter.printHelp(command.name(), cmdOptions); 073 } 074}