tools: nfdc help command

refs #3780

Change-Id: Ibd0e37bad127a38e582864fadd81afadc74baf48
diff --git a/tools/nfdc/available-commands.cpp b/tools/nfdc/available-commands.cpp
index b0a118a..3cd540a 100644
--- a/tools/nfdc/available-commands.cpp
+++ b/tools/nfdc/available-commands.cpp
@@ -24,6 +24,7 @@
  */
 
 #include "available-commands.hpp"
+#include "help.hpp"
 #include "status-report.hpp"
 #include "status-main.hpp"
 #include "legacy-nfdc.hpp"
@@ -62,8 +63,11 @@
 void
 registerCommands(CommandParser& parser)
 {
+  registerHelpCommand(parser);
+
   CommandDefinition defStatusReport("status", "report");
   defStatusReport
+    .setTitle("print NFD status report")
     .addArg("format", ArgValueType::REPORT_FORMAT, Required::NO, Positional::YES);
   parser.addCommand(defStatusReport, &statusReport);
 
@@ -72,17 +76,19 @@
     std::string noun;
     std::string verb;
     std::string legacyOption;
+    std::string title;
   };
   const std::vector<StatusCommandDefinition> statusCommands{
-    {"status", "show", "-v"},
-    {"face", "list", "-f"},
-    {"channel", "list", "-c"},
-    {"strategy", "list", "-s"},
-    {"fib", "list", "-b"},
-    {"route", "list", "-r"}
+    {"status", "show", "-v", "print general status"},
+    {"face", "list", "-f", "print face list"},
+    {"channel", "list", "-c", "print channel list"},
+    {"strategy", "list", "-s", "print strategy choices"},
+    {"fib", "list", "-b", "print FIB entries"},
+    {"route", "list", "-r", "print RIB routes"}
   };
   for (const StatusCommandDefinition& scd : statusCommands) {
     CommandDefinition def(scd.noun, scd.verb);
+    def.setTitle(scd.title);
     parser.addCommand(def, bind(&statusList, _1, scd.legacyOption));
   }
   parser.addAlias("status", "show", "list");
@@ -90,20 +96,26 @@
   CommandDefinition defLegacyNfdStatus("legacy-nfd-status", "");
   defLegacyNfdStatus
     .addArg("args", ArgValueType::ANY, Required::NO, Positional::YES);
-  parser.addCommand(defLegacyNfdStatus, &legacyNfdStatus);
+  parser.addCommand(defLegacyNfdStatus, &legacyNfdStatus, AVAILABLE_IN_ALL & ~AVAILABLE_IN_HELP);
 
-  const std::vector<std::string> legacyNfdcSubcommands{
-    "register",
-    "unregister",
-    "create",
-    "destroy",
-    "set-strategy",
-    "unset-strategy",
-    "add-nexthop",
-    "remove-nexthop"
+  struct LegacyNfdcCommandDefinition
+  {
+    std::string subcommand;
+    std::string title;
   };
-  for (const std::string& subcommand : legacyNfdcSubcommands) {
-    CommandDefinition def(subcommand, "");
+  const std::vector<LegacyNfdcCommandDefinition> legacyNfdcSubcommands{
+    {"register", "register a prefix"},
+    {"unregister", "unregister a prefix"},
+    {"create", "create a face"},
+    {"destroy", "destroy a face"},
+    {"set-strategy", "set strategy choice on namespace"},
+    {"unset-strategy", "unset strategy choice on namespace"},
+    {"add-nexthop", "add FIB nexthop"},
+    {"remove-nexthop", "remove FIB nexthop"}
+  };
+  for (const LegacyNfdcCommandDefinition& lncd : legacyNfdcSubcommands) {
+    CommandDefinition def(lncd.subcommand, "");
+    def.setTitle(lncd.title);
     def.addArg("args", ArgValueType::ANY, Required::NO, Positional::YES);
     parser.addCommand(def, &legacyNfdcMain);
   }
diff --git a/tools/nfdc/command-definition.hpp b/tools/nfdc/command-definition.hpp
index 136f5c4..47c6af3 100644
--- a/tools/nfdc/command-definition.hpp
+++ b/tools/nfdc/command-definition.hpp
@@ -142,20 +142,21 @@
   }
 
 public: // help
-  /** \return one-line synopsis
+  /** \return one-line description
    */
   const std::string&
-  getSynopsis() const
+  getTitle() const
   {
-    return m_synopsis;
+    return m_title;
   }
 
-  /** \brief set one-line synopsis
+  /** \brief set one-line description
+   *  \param title one-line description, written in lower case
    */
   CommandDefinition&
-  setSynopsis(const std::string& synopsis)
+  setTitle(const std::string& title)
   {
-    m_synopsis = synopsis;
+    m_title = title;
     return *this;
   }
 
@@ -189,7 +190,7 @@
   std::string m_noun;
   std::string m_verb;
 
-  std::string m_synopsis;
+  std::string m_title;
 
   struct Arg
   {
diff --git a/tools/nfdc/command-parser.cpp b/tools/nfdc/command-parser.cpp
index 6b21d8b..b4c4558 100644
--- a/tools/nfdc/command-parser.cpp
+++ b/tools/nfdc/command-parser.cpp
@@ -47,6 +47,9 @@
   if ((modes & AVAILABLE_IN_BATCH) != 0) {
     os << sep << "batch";
   }
+  if ((modes & AVAILABLE_IN_HELP) == 0) {
+    os << sep << "hidden";
+  }
 
   if (sep.getCount() == 0) {
     os << "none";
@@ -73,6 +76,11 @@
   BOOST_ASSERT(modes != AVAILABLE_IN_NONE);
   m_commands[{def.getNoun(), def.getVerb()}].reset(
     new Command{def, execute, static_cast<AvailableIn>(modes)});
+
+  if ((modes & AVAILABLE_IN_HELP) != 0) {
+    m_commandOrder.push_back(m_commands.find({def.getNoun(), def.getVerb()}));
+  }
+
   return *this;
 }
 
@@ -83,6 +91,20 @@
   return *this;
 }
 
+std::vector<const CommandDefinition*>
+CommandParser::listCommands(const std::string& noun, ParseMode mode) const
+{
+  std::vector<const CommandDefinition*> results;
+  for (CommandContainer::const_iterator i : m_commandOrder) {
+    const Command& command = *i->second;
+    if ((command.modes & static_cast<AvailableIn>(mode)) != 0 &&
+        (noun.empty() || noun == command.def.getNoun())) {
+      results.push_back(&command.def);
+    }
+  }
+  return results;
+}
+
 std::tuple<std::string, std::string, CommandArguments, ExecuteCommand>
 CommandParser::parse(const std::vector<std::string>& tokens, ParseMode mode) const
 {
diff --git a/tools/nfdc/command-parser.hpp b/tools/nfdc/command-parser.hpp
index a46530d..551f5e3 100644
--- a/tools/nfdc/command-parser.hpp
+++ b/tools/nfdc/command-parser.hpp
@@ -40,6 +40,7 @@
   AVAILABLE_IN_NONE     = 0,
   AVAILABLE_IN_ONE_SHOT = 1 << 0, ///< one-shot mode
   AVAILABLE_IN_BATCH    = 1 << 1, ///< batch mode
+  AVAILABLE_IN_HELP     = 1 << 7, ///< visible in help listing
   AVAILABLE_IN_ALL      = 0xff
 };
 
@@ -86,6 +87,14 @@
   CommandParser&
   addAlias(const std::string& noun, const std::string& verb, const std::string& verb2);
 
+  /** \brief list known commands for help
+   *  \param noun if not empty, filter results by this noun
+   *  \param mode include commands for the specified parse mode
+   *  \return commands in insertion order
+   */
+  std::vector<const CommandDefinition*>
+  listCommands(const std::string& noun, ParseMode mode) const;
+
   /** \brief parse a command line
    *  \param tokens command line
    *  \param mode parser mode, must be ParseMode::ONE_SHOT, other modes are not implemented
@@ -110,6 +119,10 @@
    */
   typedef std::map<CommandName, shared_ptr<Command>> CommandContainer;
   CommandContainer m_commands;
+
+  /** \brief commands in insertion order
+   */
+  std::vector<CommandContainer::const_iterator> m_commandOrder;
 };
 
 } // namespace nfdc
diff --git a/tools/nfdc/format-helpers.cpp b/tools/nfdc/format-helpers.cpp
index 3496104..942a9f1 100644
--- a/tools/nfdc/format-helpers.cpp
+++ b/tools/nfdc/format-helpers.cpp
@@ -88,6 +88,15 @@
 
 namespace text {
 
+std::ostream&
+operator<<(std::ostream& os, const Spaces& spaces)
+{
+  for (int i = 0; i < spaces.nSpaces; ++i) {
+    os << ' ';
+  }
+  return os;
+}
+
 Separator::Separator(const std::string& first, const std::string& subsequent)
   : m_first(first)
   , m_subsequent(subsequent)
diff --git a/tools/nfdc/format-helpers.hpp b/tools/nfdc/format-helpers.hpp
index 6629409..4c7badd 100644
--- a/tools/nfdc/format-helpers.hpp
+++ b/tools/nfdc/format-helpers.hpp
@@ -67,6 +67,16 @@
 
 namespace text {
 
+/** \brief print a number of whitespaces
+ */
+struct Spaces
+{
+  int nSpaces; ///< number of spaces; print nothing if negative
+};
+
+std::ostream&
+operator<<(std::ostream& os, const Spaces& spaces);
+
 /** \brief print different string on first and subsequent usage
  *
  *  \code
diff --git a/tools/nfdc/help.cpp b/tools/nfdc/help.cpp
new file mode 100644
index 0000000..6088607
--- /dev/null
+++ b/tools/nfdc/help.cpp
@@ -0,0 +1,104 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014-2016,  Regents of the University of California,
+ *                           Arizona Board of Regents,
+ *                           Colorado State University,
+ *                           University Pierre & Marie Curie, Sorbonne University,
+ *                           Washington University in St. Louis,
+ *                           Beijing Institute of Technology,
+ *                           The University of Memphis.
+ *
+ * This file is part of NFD (Named Data Networking Forwarding Daemon).
+ * See AUTHORS.md for complete list of NFD authors and contributors.
+ *
+ * NFD is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE.  See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * NFD, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "help.hpp"
+#include "format-helpers.hpp"
+#include <ndn-cxx/util/logger.hpp>
+#include <unistd.h>
+
+namespace nfd {
+namespace tools {
+namespace nfdc {
+
+NDN_LOG_INIT(nfdc.Help);
+
+const int LIST_COMMAND_NAME_COLUMN_WIDTH = 16;
+
+void
+helpList(std::ostream& os, const CommandParser& parser, ParseMode mode, const std::string& noun)
+{
+  os << "nfdc [-h] [-V] <command> [<args>]\n\n";
+  if (noun.empty()) {
+    os << "All subcommands:\n";
+  }
+  else {
+    os << "Subcommands starting with " << noun << ":\n";
+  }
+
+  std::vector<const CommandDefinition*> commands = parser.listCommands(noun, mode);
+  if (commands.empty()) {
+    os << "  (none)\n";
+    return;
+  }
+
+  for (auto def : commands) {
+    os << "  " << def->getNoun() << ' ' << def->getVerb() << ' '
+       << text::Spaces{static_cast<int>(LIST_COMMAND_NAME_COLUMN_WIDTH -
+                       def->getNoun().size() - def->getVerb().size() - 2)}
+       << def->getTitle() << '\n';
+  }
+
+  os << "\nSee 'nfdc help <command>' to read about a specific subcommand.\n";
+}
+
+static int
+helpSingle(const std::string& noun, const std::string& verb)
+{
+  std::string manpage = "nfdc-" + noun;
+
+  execlp("man", "man", manpage.data(), nullptr);
+  NDN_LOG_FATAL("Error opening man page for " << manpage);
+  return 1;
+}
+
+int
+help(ExecuteContext& ctx, const CommandParser& parser, std::ostream& os)
+{
+  std::string noun = ctx.args.get<std::string>("noun", "");
+  std::string verb = ctx.args.get<std::string>("verb", "");
+
+  if (noun.empty()) {
+    helpList(os, parser, ParseMode::ONE_SHOT, noun);
+    return 0;
+  }
+  else {
+    return helpSingle(noun, verb);
+  }
+}
+
+void
+registerHelpCommand(CommandParser& parser)
+{
+  CommandDefinition defHelp("help", "");
+  defHelp
+    .setTitle("display help information")
+    .addArg("noun", ArgValueType::STRING, Required::NO, Positional::YES)
+    .addArg("verb", ArgValueType::STRING, Required::NO, Positional::YES);
+  parser.addCommand(defHelp, bind(&help, _1, cref(parser), ref(std::cout)));
+}
+
+} // namespace nfdc
+} // namespace tools
+} // namespace nfd
diff --git a/tools/nfdc/help.hpp b/tools/nfdc/help.hpp
new file mode 100644
index 0000000..4fd2dc5
--- /dev/null
+++ b/tools/nfdc/help.hpp
@@ -0,0 +1,53 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014-2016,  Regents of the University of California,
+ *                           Arizona Board of Regents,
+ *                           Colorado State University,
+ *                           University Pierre & Marie Curie, Sorbonne University,
+ *                           Washington University in St. Louis,
+ *                           Beijing Institute of Technology,
+ *                           The University of Memphis.
+ *
+ * This file is part of NFD (Named Data Networking Forwarding Daemon).
+ * See AUTHORS.md for complete list of NFD authors and contributors.
+ *
+ * NFD is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE.  See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * NFD, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef NFD_TOOLS_NFDC_HELP_HPP
+#define NFD_TOOLS_NFDC_HELP_HPP
+
+#include "command-parser.hpp"
+
+namespace nfd {
+namespace tools {
+namespace nfdc {
+
+void
+helpList(std::ostream& os, const CommandParser& parser,
+         ParseMode mode = ParseMode::ONE_SHOT, const std::string& noun = "");
+
+/** \brief the 'help' command
+ */
+int
+help(ExecuteContext& ctx, const CommandParser& parser, std::ostream& os);
+
+/** \brief registers 'help' command
+ */
+void
+registerHelpCommand(CommandParser& parser);
+
+} // namespace nfdc
+} // namespace tools
+} // namespace nfd
+
+#endif // NFD_TOOLS_NFDC_HELP_HPP
diff --git a/tools/nfdc/main.cpp b/tools/nfdc/main.cpp
index bcd9da3..da403c8 100644
--- a/tools/nfdc/main.cpp
+++ b/tools/nfdc/main.cpp
@@ -24,7 +24,7 @@
  */
 
 #include "available-commands.hpp"
-#include "legacy-nfdc.hpp"
+#include "help.hpp"
 #include "core/version.hpp"
 
 namespace nfd {
@@ -36,8 +36,11 @@
 {
   std::vector<std::string> args(argv + 1, argv + argc);
 
+  CommandParser parser;
+  registerCommands(parser);
+
   if (args.empty() || args[0] == "-h") {
-    legacyNfdcUsage();
+    helpList(std::cout, parser);
     return 0;
   }
 
@@ -46,8 +49,6 @@
     return 0;
   }
 
-  CommandParser parser;
-  registerCommands(parser);
   std::string noun, verb;
   CommandArguments ca;
   ExecuteCommand execute;