2017
[folly.git] / folly / experimental / NestedCommandLineApp.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #pragma once
18
19 #include <functional>
20 #include <stdexcept>
21
22 #include <folly/experimental/ProgramOptions.h>
23
24 namespace folly {
25
26 /**
27  * Exception that commands may throw to force the program to exit cleanly
28  * with a given exit code. NestedCommandLineApp::run() catches this and
29  * makes run() print the given message on stderr (followed by a newline, unless
30  * empty; the message is only allowed when exiting with a non-zero status), and
31  * return the exit code. (Other exceptions will propagate out of run())
32  */
33 class ProgramExit : public std::runtime_error {
34  public:
35   explicit ProgramExit(int status, const std::string& msg = std::string());
36   int status() const { return status_; }
37  private:
38   int status_;
39 };
40
41 /**
42  * App that uses a nested command line, of the form:
43  *
44  * program [--global_options...] command [--command_options...] command_args...
45  */
46 class NestedCommandLineApp {
47  public:
48   typedef std::function<void(
49       const std::string& command,
50       const boost::program_options::variables_map& options,
51       const std::vector<std::string>& args)> InitFunction;
52
53   typedef std::function<void(
54       const boost::program_options::variables_map& options,
55       const std::vector<std::string>&)> Command;
56
57   /**
58    * Initialize the app.
59    *
60    * If programName is not set, we try to guess (readlink("/proc/self/exe")).
61    *
62    * version is the version string printed when given the --version flag.
63    *
64    * initFunction, if specified, is called after parsing the command line,
65    * right before executing the command.
66    */
67   explicit NestedCommandLineApp(
68       std::string programName = std::string(),
69       std::string version = std::string(),
70       InitFunction initFunction = InitFunction());
71
72   /**
73    * Add GFlags to the list of supported options with the given style.
74    */
75   void addGFlags(ProgramOptionsStyle style = ProgramOptionsStyle::GNU) {
76     globalOptions_.add(getGFlags(style));
77   }
78
79   /**
80    * Return the global options object, so you can add options.
81    */
82   boost::program_options::options_description& globalOptions() {
83     return globalOptions_;
84   }
85
86   /**
87    * Add a command.
88    *
89    * name:  command name
90    * argStr: description of arguments in help strings
91    *   (<filename> <N>)
92    * shortHelp: one-line summary help string
93    * fullHelp: full help string
94    * command: function to run
95    *
96    * Returns a reference to the options_description object that you can
97    * use to add options for this command.
98    */
99   boost::program_options::options_description& addCommand(
100       std::string name,
101       std::string argStr,
102       std::string shortHelp,
103       std::string fullHelp,
104       Command command);
105
106   /**
107    * Add an alias; running the command newName will have the same effect
108    * as running oldName.
109    */
110   void addAlias(std::string newName, std::string oldName);
111
112   /**
113    * Run the command and return; the return code is 0 on success or
114    * non-zero on error, so it is idiomatic to call this at the end of main():
115    * return app.run(argc, argv);
116    *
117    * On successful exit, run() will check for errors on stdout (and flush
118    * it) to help command-line applications that need to write to stdout
119    * (failing to write to stdout is an error). If there is an error on stdout,
120    * we'll print a helpful message on stderr and return an error status (1).
121    */
122   int run(int argc, const char* const argv[]);
123   int run(const std::vector<std::string>& args);
124
125  private:
126   void doRun(const std::vector<std::string>& args);
127   const std::string& resolveAlias(const std::string& name) const;
128
129   struct CommandInfo {
130     std::string argStr;
131     std::string shortHelp;
132     std::string fullHelp;
133     Command command;
134     boost::program_options::options_description options;
135   };
136
137   const std::pair<const std::string, CommandInfo>&
138   findCommand(const std::string& name) const;
139
140   void displayHelp(
141       const boost::program_options::variables_map& options,
142       const std::vector<std::string>& args);
143
144   std::string programName_;
145   std::string version_;
146   InitFunction initFunction_;
147   boost::program_options::options_description globalOptions_;
148   std::map<std::string, CommandInfo> commands_;
149   std::map<std::string, std::string> aliases_;
150 };
151
152 }  // namespaces