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