cannam@148: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors cannam@148: // Licensed under the MIT License: cannam@148: // cannam@148: // Permission is hereby granted, free of charge, to any person obtaining a copy cannam@148: // of this software and associated documentation files (the "Software"), to deal cannam@148: // in the Software without restriction, including without limitation the rights cannam@148: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell cannam@148: // copies of the Software, and to permit persons to whom the Software is cannam@148: // furnished to do so, subject to the following conditions: cannam@148: // cannam@148: // The above copyright notice and this permission notice shall be included in cannam@148: // all copies or substantial portions of the Software. cannam@148: // cannam@148: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR cannam@148: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, cannam@148: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE cannam@148: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER cannam@148: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, cannam@148: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN cannam@148: // THE SOFTWARE. cannam@148: cannam@148: #ifndef KJ_MAIN_H_ cannam@148: #define KJ_MAIN_H_ cannam@148: cannam@148: #if defined(__GNUC__) && !KJ_HEADER_WARNINGS cannam@148: #pragma GCC system_header cannam@148: #endif cannam@148: cannam@148: #include "array.h" cannam@148: #include "string.h" cannam@148: #include "vector.h" cannam@148: #include "function.h" cannam@148: cannam@148: namespace kj { cannam@148: cannam@148: class ProcessContext { cannam@148: // Context for command-line programs. cannam@148: cannam@148: public: cannam@148: virtual StringPtr getProgramName() = 0; cannam@148: // Get argv[0] as passed to main(). cannam@148: cannam@148: KJ_NORETURN(virtual void exit()) = 0; cannam@148: // Indicates program completion. The program is considered successful unless `error()` was cannam@148: // called. Typically this exits with _Exit(), meaning that the stack is not unwound, buffers cannam@148: // are not flushed, etc. -- it is the responsibility of the caller to flush any buffers that cannam@148: // matter. However, an alternate context implementation e.g. for unit testing purposes could cannam@148: // choose to throw an exception instead. cannam@148: // cannam@148: // At first this approach may sound crazy. Isn't it much better to shut down cleanly? What if cannam@148: // you lose data? However, it turns out that if you look at each common class of program, _Exit() cannam@148: // is almost always preferable. Let's break it down: cannam@148: // cannam@148: // * Commands: A typical program you might run from the command line is single-threaded and cannam@148: // exits quickly and deterministically. Commands often use buffered I/O and need to flush cannam@148: // those buffers before exit. However, most of the work performed by destructors is not cannam@148: // flushing buffers, but rather freeing up memory, placing objects into freelists, and closing cannam@148: // file descriptors. All of this is irrelevant if the process is about to exit anyway, and cannam@148: // for a command that runs quickly, time wasted freeing heap space may make a real difference cannam@148: // in the overall runtime of a script. Meanwhile, it is usually easy to determine exactly what cannam@148: // resources need to be flushed before exit, and easy to tell if they are not being flushed cannam@148: // (because the command fails to produce the expected output). Therefore, it is reasonably cannam@148: // easy for commands to explicitly ensure all output is flushed before exiting, and it is cannam@148: // probably a good idea for them to do so anyway, because write failures should be detected cannam@148: // and handled. For commands, a good strategy is to allocate any objects that require clean cannam@148: // destruction on the stack, and allow them to go out of scope before the command exits. cannam@148: // Meanwhile, any resources which do not need to be cleaned up should be allocated as members cannam@148: // of the command's main class, whose destructor normally will not be called. cannam@148: // cannam@148: // * Interactive apps: Programs that interact with the user (whether they be graphical apps cannam@148: // with windows or console-based apps like emacs) generally exit only when the user asks them cannam@148: // to. Such applications may store large data structures in memory which need to be synced cannam@148: // to disk, such as documents or user preferences. However, relying on stack unwind or global cannam@148: // destructors as the mechanism for ensuring such syncing occurs is probably wrong. First of cannam@148: // all, it's 2013, and applications ought to be actively syncing changes to non-volatile cannam@148: // storage the moment those changes are made. Applications can crash at any time and a crash cannam@148: // should never lose data that is more than half a second old. Meanwhile, if a user actually cannam@148: // does try to close an application while unsaved changes exist, the application UI should cannam@148: // prompt the user to decide what to do. Such a UI mechanism is obviously too high level to cannam@148: // be implemented via destructors, so KJ's use of _Exit() shouldn't make a difference here. cannam@148: // cannam@148: // * Servers: A good server is fault-tolerant, prepared for the possibility that at any time cannam@148: // it could crash, the OS could decide to kill it off, or the machine it is running on could cannam@148: // just die. So, using _Exit() should be no problem. In fact, servers generally never even cannam@148: // call exit anyway; they are killed externally. cannam@148: // cannam@148: // * Batch jobs: A long-running batch job is something between a command and a server. It cannam@148: // probably knows exactly what needs to be flushed before exiting, and it probably should be cannam@148: // fault-tolerant. cannam@148: // cannam@148: // Meanwhile, regardless of program type, if you are adhering to KJ style, then the use of cannam@148: // _Exit() shouldn't be a problem anyway: cannam@148: // cannam@148: // * KJ style forbids global mutable state (singletons) in general and global constructors and cannam@148: // destructors in particular. Therefore, everything that could possibly need cleanup either cannam@148: // lives on the stack or is transitively owned by something living on the stack. cannam@148: // cannam@148: // * Calling exit() simply means "Don't clean up anything older than this stack frame.". If you cannam@148: // have resources that require cleanup before exit, make sure they are owned by stack frames cannam@148: // beyond the one that eventually calls exit(). To be as safe as possible, don't place any cannam@148: // state in your program's main class, and don't call exit() yourself. Then, runMainAndExit() cannam@148: // will do it, and the only thing on the stack at that time will be your main class, which cannam@148: // has no state anyway. cannam@148: // cannam@148: // TODO(someday): Perhaps we should use the new std::quick_exit(), so that at_quick_exit() is cannam@148: // available for those who really think they need it. Unfortunately, it is not yet available cannam@148: // on many platforms. cannam@148: cannam@148: virtual void warning(StringPtr message) = 0; cannam@148: // Print the given message to standard error. A newline is printed after the message if it cannam@148: // doesn't already have one. cannam@148: cannam@148: virtual void error(StringPtr message) = 0; cannam@148: // Like `warning()`, but also sets a flag indicating that the process has failed, and that when cannam@148: // it eventually exits it should indicate an error status. cannam@148: cannam@148: KJ_NORETURN(virtual void exitError(StringPtr message)) = 0; cannam@148: // Equivalent to `error(message)` followed by `exit()`. cannam@148: cannam@148: KJ_NORETURN(virtual void exitInfo(StringPtr message)) = 0; cannam@148: // Displays the given non-error message to the user and then calls `exit()`. This is used to cannam@148: // implement things like --help. cannam@148: cannam@148: virtual void increaseLoggingVerbosity() = 0; cannam@148: // Increase the level of detail produced by the debug logging system. `MainBuilder` invokes cannam@148: // this if the caller uses the -v flag. cannam@148: cannam@148: // TODO(someday): Add interfaces representing standard OS resources like the filesystem, so that cannam@148: // these things can be mocked out. cannam@148: }; cannam@148: cannam@148: class TopLevelProcessContext final: public ProcessContext { cannam@148: // A ProcessContext implementation appropriate for use at the actual entry point of a process cannam@148: // (as opposed to when you are trying to call a program's main function from within some other cannam@148: // program). This implementation writes errors to stderr, and its `exit()` method actually cannam@148: // calls the C `quick_exit()` function. cannam@148: cannam@148: public: cannam@148: explicit TopLevelProcessContext(StringPtr programName); cannam@148: cannam@148: struct CleanShutdownException { int exitCode; }; cannam@148: // If the environment variable KJ_CLEAN_SHUTDOWN is set, then exit() will actually throw this cannam@148: // exception rather than exiting. `kj::runMain()` catches this exception and returns normally. cannam@148: // This is useful primarily for testing purposes, to assist tools like memory leak checkers that cannam@148: // are easily confused by quick_exit(). cannam@148: cannam@148: StringPtr getProgramName() override; cannam@148: KJ_NORETURN(void exit() override); cannam@148: void warning(StringPtr message) override; cannam@148: void error(StringPtr message) override; cannam@148: KJ_NORETURN(void exitError(StringPtr message) override); cannam@148: KJ_NORETURN(void exitInfo(StringPtr message) override); cannam@148: void increaseLoggingVerbosity() override; cannam@148: cannam@148: private: cannam@148: StringPtr programName; cannam@148: bool cleanShutdown; cannam@148: bool hadErrors = false; cannam@148: }; cannam@148: cannam@148: typedef Function params)> MainFunc; cannam@148: cannam@148: int runMainAndExit(ProcessContext& context, MainFunc&& func, int argc, char* argv[]); cannam@148: // Runs the given main function and then exits using the given context. If an exception is thrown, cannam@148: // this will catch it, report it via the context and exit with an error code. cannam@148: // cannam@148: // Normally this function does not return, because returning would probably lead to wasting time cannam@148: // on cleanup when the process is just going to exit anyway. However, to facilitate memory leak cannam@148: // checkers and other tools that require a clean shutdown to do their job, if the environment cannam@148: // variable KJ_CLEAN_SHUTDOWN is set, the function will in fact return an exit code, which should cannam@148: // then be returned from main(). cannam@148: // cannam@148: // Most users will use the KJ_MAIN() macro rather than call this function directly. cannam@148: cannam@148: #define KJ_MAIN(MainClass) \ cannam@148: int main(int argc, char* argv[]) { \ cannam@148: ::kj::TopLevelProcessContext context(argv[0]); \ cannam@148: MainClass mainObject(context); \ cannam@148: return ::kj::runMainAndExit(context, mainObject.getMain(), argc, argv); \ cannam@148: } cannam@148: // Convenience macro for declaring a main function based on the given class. The class must have cannam@148: // a constructor that accepts a ProcessContext& and a method getMain() which returns cannam@148: // kj::MainFunc (probably building it using a MainBuilder). cannam@148: cannam@148: class MainBuilder { cannam@148: // Builds a main() function with nice argument parsing. As options and arguments are parsed, cannam@148: // corresponding callbacks are called, so that you never have to write a massive switch() cannam@148: // statement to interpret arguments. Additionally, this approach encourages you to write cannam@148: // main classes that have a reasonable API that can be used as an alternative to their cannam@148: // command-line interface. cannam@148: // cannam@148: // All StringPtrs passed to MainBuilder must remain valid until option parsing completes. The cannam@148: // assumption is that these strings will all be literals, making this an easy requirement. If cannam@148: // not, consider allocating them in an Arena. cannam@148: // cannam@148: // Some flags are automatically recognized by the main functions built by this class: cannam@148: // --help: Prints help text and exits. The help text is constructed based on the cannam@148: // information you provide to the builder as you define each flag. cannam@148: // --verbose: Increase logging verbosity. cannam@148: // --version: Print version information and exit. cannam@148: // cannam@148: // Example usage: cannam@148: // cannam@148: // class FooMain { cannam@148: // public: cannam@148: // FooMain(kj::ProcessContext& context): context(context) {} cannam@148: // cannam@148: // bool setAll() { all = true; return true; } cannam@148: // // Enable the --all flag. cannam@148: // cannam@148: // kj::MainBuilder::Validity setOutput(kj::StringPtr name) { cannam@148: // // Set the output file. cannam@148: // cannam@148: // if (name.endsWith(".foo")) { cannam@148: // outputFile = name; cannam@148: // return true; cannam@148: // } else { cannam@148: // return "Output file must have extension .foo."; cannam@148: // } cannam@148: // } cannam@148: // cannam@148: // kj::MainBuilder::Validity processInput(kj::StringPtr name) { cannam@148: // // Process an input file. cannam@148: // cannam@148: // if (!exists(name)) { cannam@148: // return kj::str(name, ": file not found"); cannam@148: // } cannam@148: // // ... process the input file ... cannam@148: // return true; cannam@148: // } cannam@148: // cannam@148: // kj::MainFunc getMain() { cannam@148: // return MainBuilder(context, "Foo Builder v1.5", "Reads s and builds a Foo.") cannam@148: // .addOption({'a', "all"}, KJ_BIND_METHOD(*this, setAll), cannam@148: // "Frob all the widgets. Otherwise, only some widgets are frobbed.") cannam@148: // .addOptionWithArg({'o', "output"}, KJ_BIND_METHOD(*this, setOutput), cannam@148: // "", "Output to . Must be a .foo file.") cannam@148: // .expectOneOrMoreArgs("", KJ_BIND_METHOD(*this, processInput)) cannam@148: // .build(); cannam@148: // } cannam@148: // cannam@148: // private: cannam@148: // bool all = false; cannam@148: // kj::StringPtr outputFile; cannam@148: // kj::ProcessContext& context; cannam@148: // }; cannam@148: cannam@148: public: cannam@148: MainBuilder(ProcessContext& context, StringPtr version, cannam@148: StringPtr briefDescription, StringPtr extendedDescription = nullptr); cannam@148: ~MainBuilder() noexcept(false); cannam@148: cannam@148: class OptionName { cannam@148: public: cannam@148: OptionName() = default; cannam@148: inline OptionName(char shortName): isLong(false), shortName(shortName) {} cannam@148: inline OptionName(const char* longName): isLong(true), longName(longName) {} cannam@148: cannam@148: private: cannam@148: bool isLong; cannam@148: union { cannam@148: char shortName; cannam@148: const char* longName; cannam@148: }; cannam@148: friend class MainBuilder; cannam@148: }; cannam@148: cannam@148: class Validity { cannam@148: public: cannam@148: inline Validity(bool valid) { cannam@148: if (!valid) errorMessage = heapString("invalid argument"); cannam@148: } cannam@148: inline Validity(const char* errorMessage) cannam@148: : errorMessage(heapString(errorMessage)) {} cannam@148: inline Validity(String&& errorMessage) cannam@148: : errorMessage(kj::mv(errorMessage)) {} cannam@148: cannam@148: inline const Maybe& getError() const { return errorMessage; } cannam@148: inline Maybe releaseError() { return kj::mv(errorMessage); } cannam@148: cannam@148: private: cannam@148: Maybe errorMessage; cannam@148: friend class MainBuilder; cannam@148: }; cannam@148: cannam@148: MainBuilder& addOption(std::initializer_list names, Function callback, cannam@148: StringPtr helpText); cannam@148: // Defines a new option (flag). `names` is a list of characters and strings that can be used to cannam@148: // specify the option on the command line. Single-character names are used with "-" while string cannam@148: // names are used with "--". `helpText` is a natural-language description of the flag. cannam@148: // cannam@148: // `callback` is called when the option is seen. Its return value indicates whether the option cannam@148: // was accepted. If not, further option processing stops, and error is written, and the process cannam@148: // exits. cannam@148: // cannam@148: // Example: cannam@148: // cannam@148: // builder.addOption({'a', "all"}, KJ_BIND_METHOD(*this, showAll), "Show all files."); cannam@148: // cannam@148: // This option could be specified in the following ways: cannam@148: // cannam@148: // -a cannam@148: // --all cannam@148: // cannam@148: // Note that single-character option names can be combined into a single argument. For example, cannam@148: // `-abcd` is equivalent to `-a -b -c -d`. cannam@148: // cannam@148: // The help text for this option would look like: cannam@148: // cannam@148: // -a, --all cannam@148: // Show all files. cannam@148: // cannam@148: // Note that help text is automatically word-wrapped. cannam@148: cannam@148: MainBuilder& addOptionWithArg(std::initializer_list names, cannam@148: Function callback, cannam@148: StringPtr argumentTitle, StringPtr helpText); cannam@148: // Like `addOption()`, but adds an option which accepts an argument. `argumentTitle` is used in cannam@148: // the help text. The argument text is passed to the callback. cannam@148: // cannam@148: // Example: cannam@148: // cannam@148: // builder.addOptionWithArg({'o', "output"}, KJ_BIND_METHOD(*this, setOutput), cannam@148: // "", "Output to ."); cannam@148: // cannam@148: // This option could be specified with an argument of "foo" in the following ways: cannam@148: // cannam@148: // -ofoo cannam@148: // -o foo cannam@148: // --output=foo cannam@148: // --output foo cannam@148: // cannam@148: // Note that single-character option names can be combined, but only the last option can have an cannam@148: // argument, since the characters after the option letter are interpreted as the argument. E.g. cannam@148: // `-abofoo` would be equivalent to `-a -b -o foo`. cannam@148: // cannam@148: // The help text for this option would look like: cannam@148: // cannam@148: // -o FILENAME, --output=FILENAME cannam@148: // Output to FILENAME. cannam@148: cannam@148: MainBuilder& addSubCommand(StringPtr name, Function getSubParser, cannam@148: StringPtr briefHelpText); cannam@148: // If exactly the given name is seen as an argument, invoke getSubParser() and then pass all cannam@148: // remaining arguments to the parser it returns. This is useful for implementing commands which cannam@148: // have lots of sub-commands, like "git" (which has sub-commands "checkout", "branch", "pull", cannam@148: // etc.). cannam@148: // cannam@148: // `getSubParser` is only called if the command is seen. This avoids building main functions cannam@148: // for commands that aren't used. cannam@148: // cannam@148: // `briefHelpText` should be brief enough to show immediately after the command name on a single cannam@148: // line. It will not be wrapped. Users can use the built-in "help" command to get extended cannam@148: // help on a particular command. cannam@148: cannam@148: MainBuilder& expectArg(StringPtr title, Function callback); cannam@148: MainBuilder& expectOptionalArg(StringPtr title, Function callback); cannam@148: MainBuilder& expectZeroOrMoreArgs(StringPtr title, Function callback); cannam@148: MainBuilder& expectOneOrMoreArgs(StringPtr title, Function callback); cannam@148: // Set callbacks to handle arguments. `expectArg()` and `expectOptionalArg()` specify positional cannam@148: // arguments with special handling, while `expect{Zero,One}OrMoreArgs()` specifies a handler for cannam@148: // an argument list (the handler is called once for each argument in the list). `title` cannam@148: // specifies how the argument should be represented in the usage text. cannam@148: // cannam@148: // All options callbacks are called before argument callbacks, regardless of their ordering on cannam@148: // the command line. This matches GNU getopt's behavior of permuting non-flag arguments to the cannam@148: // end of the argument list. Also matching getopt, the special option "--" indicates that the cannam@148: // rest of the command line is all arguments, not options, even if they start with '-'. cannam@148: // cannam@148: // The interpretation of positional arguments is fairly flexible. The non-optional arguments can cannam@148: // be expected at the beginning, end, or in the middle. If more arguments are specified than cannam@148: // the number of non-optional args, they are assigned to the optional argument handlers in the cannam@148: // order of registration. cannam@148: // cannam@148: // For example, say you called: cannam@148: // builder.expectArg("", ...); cannam@148: // builder.expectOptionalArg("", ...); cannam@148: // builder.expectArg("", ...); cannam@148: // builder.expectZeroOrMoreArgs("", ...); cannam@148: // builder.expectArg("", ...); cannam@148: // cannam@148: // This command requires at least three arguments: foo, baz, and corge. If four arguments are cannam@148: // given, the second is assigned to bar. If five or more arguments are specified, then the cannam@148: // arguments between the third and last are assigned to qux. Note that it never makes sense cannam@148: // to call `expect*OrMoreArgs()` more than once since only the first call would ever be used. cannam@148: // cannam@148: // In practice, you probably shouldn't create such complicated commands as in the above example. cannam@148: // But, this flexibility seems necessary to support commands where the first argument is special cannam@148: // as well as commands (like `cp`) where the last argument is special. cannam@148: cannam@148: MainBuilder& callAfterParsing(Function callback); cannam@148: // Call the given function after all arguments have been parsed. cannam@148: cannam@148: MainFunc build(); cannam@148: // Build the "main" function, which simply parses the arguments. Once this returns, the cannam@148: // `MainBuilder` is no longer valid. cannam@148: cannam@148: private: cannam@148: struct Impl; cannam@148: Own impl; cannam@148: cannam@148: class MainImpl; cannam@148: }; cannam@148: cannam@148: } // namespace kj cannam@148: cannam@148: #endif // KJ_MAIN_H_