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