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