head	1.2;
access;
symbols
	netbsd-11-0-RC6:1.2
	netbsd-11-0-RC5:1.2
	netbsd-11-0-RC4:1.2
	netbsd-11-0-RC3:1.2
	netbsd-11-0-RC2:1.2
	netbsd-11-0-RC1:1.2
	perseant-exfatfs-base-20250801:1.2
	netbsd-11:1.2.0.10
	netbsd-11-base:1.2
	netbsd-10-1-RELEASE:1.2
	perseant-exfatfs-base-20240630:1.2
	perseant-exfatfs:1.2.0.8
	perseant-exfatfs-base:1.2
	netbsd-8-3-RELEASE:1.1.1.1
	netbsd-9-4-RELEASE:1.1.1.1
	netbsd-10-0-RELEASE:1.2
	netbsd-10-0-RC6:1.2
	netbsd-10-0-RC5:1.2
	netbsd-10-0-RC4:1.2
	netbsd-10-0-RC3:1.2
	netbsd-10-0-RC2:1.2
	netbsd-10-0-RC1:1.2
	netbsd-10:1.2.0.6
	netbsd-10-base:1.2
	netbsd-9-3-RELEASE:1.1.1.1
	cjep_sun2x-base1:1.2
	cjep_sun2x:1.2.0.4
	cjep_sun2x-base:1.2
	cjep_staticlib_x-base1:1.2
	netbsd-9-2-RELEASE:1.1.1.1
	cjep_staticlib_x:1.2.0.2
	cjep_staticlib_x-base:1.2
	netbsd-9-1-RELEASE:1.1.1.1
	phil-wifi-20200421:1.1.1.1
	phil-wifi-20200411:1.1.1.1
	is-mlppp:1.1.1.1.0.40
	is-mlppp-base:1.1.1.1
	phil-wifi-20200406:1.1.1.1
	netbsd-8-2-RELEASE:1.1.1.1
	netbsd-9-0-RELEASE:1.1.1.1
	netbsd-9-0-RC2:1.1.1.1
	netbsd-9-0-RC1:1.1.1.1
	phil-wifi-20191119:1.1.1.1
	netbsd-9:1.1.1.1.0.38
	netbsd-9-base:1.1.1.1
	phil-wifi-20190609:1.1.1.1
	netbsd-8-1-RELEASE:1.1.1.1
	netbsd-8-1-RC1:1.1.1.1
	pgoyette-compat-merge-20190127:1.1.1.1
	pgoyette-compat-20190127:1.1.1.1
	pgoyette-compat-20190118:1.1.1.1
	pgoyette-compat-1226:1.1.1.1
	pgoyette-compat-1126:1.1.1.1
	pgoyette-compat-1020:1.1.1.1
	pgoyette-compat-0930:1.1.1.1
	pgoyette-compat-0906:1.1.1.1
	netbsd-7-2-RELEASE:1.1.1.1
	pgoyette-compat-0728:1.1.1.1
	netbsd-8-0-RELEASE:1.1.1.1
	phil-wifi:1.1.1.1.0.36
	phil-wifi-base:1.1.1.1
	pgoyette-compat-0625:1.1.1.1
	netbsd-8-0-RC2:1.1.1.1
	pgoyette-compat-0521:1.1.1.1
	pgoyette-compat-0502:1.1.1.1
	pgoyette-compat-0422:1.1.1.1
	netbsd-8-0-RC1:1.1.1.1
	pgoyette-compat-0415:1.1.1.1
	pgoyette-compat-0407:1.1.1.1
	pgoyette-compat-0330:1.1.1.1
	pgoyette-compat-0322:1.1.1.1
	pgoyette-compat-0315:1.1.1.1
	netbsd-7-1-2-RELEASE:1.1.1.1
	pgoyette-compat:1.1.1.1.0.34
	pgoyette-compat-base:1.1.1.1
	netbsd-7-1-1-RELEASE:1.1.1.1
	matt-nb8-mediatek:1.1.1.1.0.32
	matt-nb8-mediatek-base:1.1.1.1
	perseant-stdc-iso10646:1.1.1.1.0.30
	perseant-stdc-iso10646-base:1.1.1.1
	netbsd-8:1.1.1.1.0.28
	netbsd-8-base:1.1.1.1
	prg-localcount2-base3:1.1.1.1
	prg-localcount2-base2:1.1.1.1
	prg-localcount2-base1:1.1.1.1
	prg-localcount2:1.1.1.1.0.26
	prg-localcount2-base:1.1.1.1
	pgoyette-localcount-20170426:1.1.1.1
	bouyer-socketcan-base1:1.1.1.1
	pgoyette-localcount-20170320:1.1.1.1
	netbsd-7-1:1.1.1.1.0.24
	netbsd-7-1-RELEASE:1.1.1.1
	netbsd-7-1-RC2:1.1.1.1
	netbsd-7-nhusb-base-20170116:1.1.1.1
	bouyer-socketcan:1.1.1.1.0.22
	bouyer-socketcan-base:1.1.1.1
	pgoyette-localcount-20170107:1.1.1.1
	netbsd-7-1-RC1:1.1.1.1
	pgoyette-localcount-20161104:1.1.1.1
	netbsd-7-0-2-RELEASE:1.1.1.1
	localcount-20160914:1.1.1.1
	netbsd-7-nhusb:1.1.1.1.0.20
	netbsd-7-nhusb-base:1.1.1.1
	pgoyette-localcount-20160806:1.1.1.1
	pgoyette-localcount-20160726:1.1.1.1
	pgoyette-localcount:1.1.1.1.0.18
	pgoyette-localcount-base:1.1.1.1
	netbsd-7-0-1-RELEASE:1.1.1.1
	netbsd-7-0:1.1.1.1.0.16
	netbsd-7-0-RELEASE:1.1.1.1
	netbsd-7-0-RC3:1.1.1.1
	netbsd-7-0-RC2:1.1.1.1
	netbsd-7-0-RC1:1.1.1.1
	netbsd-7:1.1.1.1.0.14
	netbsd-7-base:1.1.1.1
	yamt-pagecache:1.1.1.1.0.12
	yamt-pagecache-base9:1.1.1.1
	tls-earlyentropy:1.1.1.1.0.10
	tls-earlyentropy-base:1.1.1.1
	riastradh-xf86-video-intel-2-7-1-pre-2-21-15:1.1.1.1
	riastradh-drm2-base3:1.1.1.1
	kyua-cli-0-7:1.1.1.1
	riastradh-drm2-base2:1.1.1.1
	riastradh-drm2-base1:1.1.1.1
	riastradh-drm2:1.1.1.1.0.2
	riastradh-drm2-base:1.1.1.1
	khorben-n900:1.1.1.1.0.8
	agc-symver:1.1.1.1.0.6
	agc-symver-base:1.1.1.1
	tls-maxphys-base:1.1.1.1
	tls-maxphys:1.1.1.1.0.4
	kyua-cli-0-6:1.1.1.1
	GOOGLE-CODE:1.1.1;
locks; strict;
comment	@// @;


1.2
date	2020.07.02.14.04.00;	author lukem;	state Exp;
branches;
next	1.1;
commitid	YUoDcZ95aoStLveC;

1.1
date	2013.02.23.12.34.04;	author jmmv;	state Exp;
branches
	1.1.1.1;
next	;

1.1.1.1
date	2013.02.23.12.34.04;	author jmmv;	state Exp;
branches
	1.1.1.1.4.1
	1.1.1.1.12.1;
next	;

1.1.1.1.4.1
date	2013.02.23.12.34.04;	author tls;	state dead;
branches;
next	1.1.1.1.4.2;

1.1.1.1.4.2
date	2013.02.25.00.26.09;	author tls;	state Exp;
branches;
next	;

1.1.1.1.12.1
date	2013.02.23.12.34.04;	author yamt;	state dead;
branches;
next	1.1.1.1.12.2;
commitid	h3iiOYJJCkPr7yBx;

1.1.1.1.12.2
date	2014.05.22.15.45.28;	author yamt;	state Exp;
branches;
next	;
commitid	h3iiOYJJCkPr7yBx;


desc
@@


1.2
log
@kyua-cli: convert auto_ptr to unique_ptr

Update kyua-cli to C++11 and use unique_ptr instead of auto_ptr,
(with std::move() where appropriate), to avoid deprecated warning by g++ 8.

(I didn't change some of the code that could arguably be refactored
to use unique_ptr or shared_ptr instead of raw pointers
and therefore remove the special case destructor handling).
@
text
@// Copyright 2010 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors
//   may be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "cli/main.hpp"

#if defined(HAVE_CONFIG_H)
#   include "config.h"
#endif

extern "C" {
#include <signal.h>
#include <unistd.h>
}

#include <cstdlib>
#include <iostream>
#include <string>
#include <utility>

#include "cli/cmd_about.hpp"
#include "cli/cmd_config.hpp"
#include "cli/cmd_db_exec.hpp"
#include "cli/cmd_db_migrate.hpp"
#include "cli/cmd_debug.hpp"
#include "cli/cmd_help.hpp"
#include "cli/cmd_list.hpp"
#include "cli/cmd_report.hpp"
#include "cli/cmd_report_html.hpp"
#include "cli/cmd_test.hpp"
#include "cli/common.ipp"
#include "cli/config.hpp"
#include "store/exceptions.hpp"
#include "utils/cmdline/commands_map.ipp"
#include "utils/cmdline/exceptions.hpp"
#include "utils/cmdline/globals.hpp"
#include "utils/cmdline/options.hpp"
#include "utils/cmdline/parser.ipp"
#include "utils/cmdline/ui.hpp"
#include "utils/config/tree.ipp"
#include "utils/env.hpp"
#include "utils/format/macros.hpp"
#include "utils/fs/operations.hpp"
#include "utils/fs/path.hpp"
#include "utils/logging/macros.hpp"
#include "utils/logging/operations.hpp"
#include "utils/optional.ipp"
#include "utils/sanity.hpp"
#include "utils/signals/exceptions.hpp"

namespace cmdline = utils::cmdline;
namespace config = utils::config;
namespace fs = utils::fs;
namespace logging = utils::logging;
namespace signals = utils::signals;

using utils::none;
using utils::optional;


namespace {


/// Executes the given subcommand with proper usage_error reporting.
///
/// \param ui Object to interact with the I/O of the program.
/// \param command The subcommand to execute.
/// \param args The part of the command line passed to the subcommand.  The
///     first item of this collection must match the command name.
/// \param user_config The runtime configuration to pass to the subcommand.
///
/// \return The exit code of the command.  Typically 0 on success, some other
/// integer otherwise.
///
/// \throw cmdline::usage_error If the user input to the subcommand is invalid.
///     This error does not encode the command name within it, so this function
///     extends the message in the error to specify which subcommand was
///     affected.
/// \throw std::exception This propagates any uncaught exception.  Such
///     exceptions are bugs, but we let them propagate so that the runtime will
///     abort and dump core.
static int
run_subcommand(cmdline::ui* ui, cli::cli_command* command,
               const cmdline::args_vector& args,
               const config::tree& user_config)
{
    try {
        PRE(command->name() == args[0]);
        return command->main(ui, args, user_config);
    } catch (const cmdline::usage_error& e) {
        throw std::pair< std::string, cmdline::usage_error >(
            command->name(), e);
    }
}


/// Exception-safe version of main.
///
/// This function provides the real meat of the entry point of the program.  It
/// is allowed to throw some known exceptions which are parsed by the caller.
/// Doing so keeps this function simpler and allow tests to actually validate
/// that the errors reported are accurate.
///
/// \return The exit code of the program.  Should be EXIT_SUCCESS on success and
/// EXIT_FAILURE on failure.  The caller extends this to additional integers for
/// errors reported through exceptions.
///
/// \param ui Object to interact with the I/O of the program.
/// \param argc The number of arguments passed on the command line.
/// \param argv NULL-terminated array containing the command line arguments.
/// \param mock_command An extra command provided for testing purposes; should
///     just be NULL other than for tests.
///
/// \throw cmdline::usage_error If the user ran the program with invalid
///     arguments.
/// \throw std::exception This propagates any uncaught exception.  Such
///     exceptions are bugs, but we let them propagate so that the runtime will
///     abort and dump core.
static int
safe_main(cmdline::ui* ui, int argc, const char* const argv[],
          cli::cli_command_ptr mock_command)
{
    cmdline::options_vector options;
    options.push_back(&cli::config_option);
    options.push_back(&cli::variable_option);
    const cmdline::string_option loglevel_option(
        "loglevel", "Level of the messages to log", "level", "info");
    options.push_back(&loglevel_option);
    const cmdline::path_option logfile_option(
        "logfile", "Path to the log file", "file",
        cli::detail::default_log_name().c_str());
    options.push_back(&logfile_option);

    cmdline::commands_map< cli::cli_command > commands;

    commands.insert(new cli::cmd_about());
    commands.insert(new cli::cmd_config());
    commands.insert(new cli::cmd_db_exec());
    commands.insert(new cli::cmd_db_migrate());
    commands.insert(new cli::cmd_help(&options, &commands));

    commands.insert(new cli::cmd_debug(), "Workspace");
    commands.insert(new cli::cmd_list(), "Workspace");
    commands.insert(new cli::cmd_test(), "Workspace");

    commands.insert(new cli::cmd_report(), "Reporting");
    commands.insert(new cli::cmd_report_html(), "Reporting");

    if (mock_command.get() != NULL)
        commands.insert(std::move(mock_command));

    const cmdline::parsed_cmdline cmdline = cmdline::parse(argc, argv, options);

    const fs::path logfile(cmdline.get_option< cmdline::path_option >(
        "logfile"));
    fs::mkdir_p(logfile.branch_path(), 0755);
    LD(F("Log file is %s") % logfile);
    utils::install_crash_handlers(logfile.str());
    try {
        logging::set_persistency(cmdline.get_option< cmdline::string_option >(
            "loglevel"), logfile);
    } catch (const std::range_error& e) {
        throw cmdline::usage_error(e.what());
    }

    if (cmdline.arguments().empty())
        throw cmdline::usage_error("No command provided");
    const std::string cmdname = cmdline.arguments()[0];

    const config::tree user_config = cli::load_config(cmdline,
                                                      cmdname != "help");

    cli::cli_command* command = commands.find(cmdname);
    if (command == NULL)
        throw cmdline::usage_error(F("Unknown command '%s'") % cmdname);
    return run_subcommand(ui, command, cmdline.arguments(), user_config);
}


}  // anonymous namespace


/// Gets the name of the default log file.
///
/// \return The path to the log file.
fs::path
cli::detail::default_log_name(void)
{
    // Update doc/troubleshooting.texi if you change this algorithm.
    const optional< std::string > home(utils::getenv("HOME"));
    if (home) {
        return logging::generate_log_name(fs::path(home.get()) / ".kyua" /
                                          "logs", cmdline::progname());
    } else {
        const optional< std::string > tmpdir(utils::getenv("TMPDIR"));
        if (tmpdir) {
            return logging::generate_log_name(fs::path(tmpdir.get()),
                                              cmdline::progname());
        } else {
            return logging::generate_log_name(fs::path("/tmp"),
                                              cmdline::progname());
        }
    }
}


/// Testable entry point, with catch-all exception handlers.
///
/// This entry point does not perform any initialization of global state; it is
/// provided to allow unit-testing of the utility's entry point.
///
/// \param ui Object to interact with the I/O of the program.
/// \param argc The number of arguments passed on the command line.
/// \param argv NULL-terminated array containing the command line arguments.
/// \param mock_command An extra command provided for testing purposes; should
///     just be NULL other than for tests.
///
/// \return 0 on success, some other integer on error.
///
/// \throw std::exception This propagates any uncaught exception.  Such
///     exceptions are bugs, but we let them propagate so that the runtime will
///     abort and dump core.
int
cli::main(cmdline::ui* ui, const int argc, const char* const* const argv,
          cli_command_ptr mock_command)
{
    try {
        const int exit_code = safe_main(ui, argc, argv, std::move(mock_command));

        // Codes above 1 are reserved to report conditions captured as
        // exceptions below.
        INV(exit_code == EXIT_SUCCESS || exit_code == EXIT_FAILURE);

        return exit_code;
    } catch (const signals::interrupted_error& e) {
        cmdline::print_error(ui, e.what());
        // Re-deliver the interruption signal to self so that we terminate with
        // the right status.  At this point we should NOT have any custom signal
        // handlers in place.
        ::kill(getpid(), e.signo());
        LD("Interrupt signal re-delivery did not terminate program");
        // If we reach this, something went wrong because we did not exit as
        // intended.  Return an internal error instead.  (Would be nicer to
        // abort in principle, but it wouldn't be a nice experience if it ever
        // happened.)
        return 2;
    } catch (const std::pair< std::string, cmdline::usage_error >& e) {
        const std::string message = F("Usage error for command %s: %s.") %
            e.first % e.second.what();
        LE(message);
        ui->err(message);
        ui->err(F("Type '%s help %s' for usage information.") %
                cmdline::progname() % e.first);
        return 3;
    } catch (const cmdline::usage_error& e) {
        const std::string message = F("Usage error: %s.") % e.what();
        LE(message);
        ui->err(message);
        ui->err(F("Type '%s help' for usage information.") %
                cmdline::progname());
        return 3;
    } catch (const store::old_schema_error& e) {
        const std::string message = F("The database has schema version %s, "
                                      "which is too old; please use db-migrate "
                                      "to upgrade it") % e.old_version();
        cmdline::print_error(ui, message);
        return 2;
    } catch (const std::runtime_error& e) {
        cmdline::print_error(ui, e.what());
        return 2;
    }
}


/// Delegate for ::main().
///
/// This function is supposed to be called directly from the top-level ::main()
/// function.  It takes care of initializing internal libraries and then calls
/// main(ui, argc, argv).
///
/// \pre This function can only be called once.
///
/// \throw std::exception This propagates any uncaught exception.  Such
///     exceptions are bugs, but we let them propagate so that the runtime will
///     abort and dump core.
int
cli::main(const int argc, const char* const* const argv)
{
    logging::set_inmemory();

    LI(F("%s %s") % PACKAGE % VERSION);

    std::string plain_args;
    for (const char* const* arg = argv; *arg != NULL; arg++)
        plain_args += F(" %s") % *arg;
    LI(F("Command line:%s") % plain_args);

    cmdline::init(argv[0]);
    cmdline::ui ui;

    const int exit_code = main(&ui, argc, argv);
    LI(F("Clean exit with code %s") % exit_code);
    return exit_code;
}
@


1.1
log
@Initial revision
@
text
@d174 1
a174 1
        commands.insert(mock_command);
d252 1
a252 1
        const int exit_code = safe_main(ui, argc, argv, mock_command);
@


1.1.1.1
log
@Initial import of Kyua CLI, version 0.6:

This is the main component of Kyua and its build will be guarded by the
MKKYUA knob.  core@@ has approved this import.

Description:

Kyua (pronounced Q.A.) is a testing framework for both developers and
users.  Kyua is different from most other testing frameworks in that it
puts the end user experience before anything else.  There are multiple
reasons for users to run the tests themselves, and Kyua ensures that
they can do so in the most convenient way.

This module, kyua-cli, provides the command-line interface to the Kyua
runtime system.  The major purpose of this tool is to run test cases and
generate unified reports for their results.
@
text
@@


1.1.1.1.12.1
log
@file main.cpp was added on branch yamt-pagecache on 2014-05-22 15:45:28 +0000
@
text
@d1 328
@


1.1.1.1.12.2
log
@sync with head.

for a reference, the tree before this commit was tagged
as yamt-pagecache-tag8.

this commit was splitted into small chunks to avoid
a limitation of cvs.  ("Protocol error: too many arguments")
@
text
@a0 328
// Copyright 2010 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors
//   may be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "cli/main.hpp"

#if defined(HAVE_CONFIG_H)
#   include "config.h"
#endif

extern "C" {
#include <signal.h>
#include <unistd.h>
}

#include <cstdlib>
#include <iostream>
#include <string>
#include <utility>

#include "cli/cmd_about.hpp"
#include "cli/cmd_config.hpp"
#include "cli/cmd_db_exec.hpp"
#include "cli/cmd_db_migrate.hpp"
#include "cli/cmd_debug.hpp"
#include "cli/cmd_help.hpp"
#include "cli/cmd_list.hpp"
#include "cli/cmd_report.hpp"
#include "cli/cmd_report_html.hpp"
#include "cli/cmd_test.hpp"
#include "cli/common.ipp"
#include "cli/config.hpp"
#include "store/exceptions.hpp"
#include "utils/cmdline/commands_map.ipp"
#include "utils/cmdline/exceptions.hpp"
#include "utils/cmdline/globals.hpp"
#include "utils/cmdline/options.hpp"
#include "utils/cmdline/parser.ipp"
#include "utils/cmdline/ui.hpp"
#include "utils/config/tree.ipp"
#include "utils/env.hpp"
#include "utils/format/macros.hpp"
#include "utils/fs/operations.hpp"
#include "utils/fs/path.hpp"
#include "utils/logging/macros.hpp"
#include "utils/logging/operations.hpp"
#include "utils/optional.ipp"
#include "utils/sanity.hpp"
#include "utils/signals/exceptions.hpp"

namespace cmdline = utils::cmdline;
namespace config = utils::config;
namespace fs = utils::fs;
namespace logging = utils::logging;
namespace signals = utils::signals;

using utils::none;
using utils::optional;


namespace {


/// Executes the given subcommand with proper usage_error reporting.
///
/// \param ui Object to interact with the I/O of the program.
/// \param command The subcommand to execute.
/// \param args The part of the command line passed to the subcommand.  The
///     first item of this collection must match the command name.
/// \param user_config The runtime configuration to pass to the subcommand.
///
/// \return The exit code of the command.  Typically 0 on success, some other
/// integer otherwise.
///
/// \throw cmdline::usage_error If the user input to the subcommand is invalid.
///     This error does not encode the command name within it, so this function
///     extends the message in the error to specify which subcommand was
///     affected.
/// \throw std::exception This propagates any uncaught exception.  Such
///     exceptions are bugs, but we let them propagate so that the runtime will
///     abort and dump core.
static int
run_subcommand(cmdline::ui* ui, cli::cli_command* command,
               const cmdline::args_vector& args,
               const config::tree& user_config)
{
    try {
        PRE(command->name() == args[0]);
        return command->main(ui, args, user_config);
    } catch (const cmdline::usage_error& e) {
        throw std::pair< std::string, cmdline::usage_error >(
            command->name(), e);
    }
}


/// Exception-safe version of main.
///
/// This function provides the real meat of the entry point of the program.  It
/// is allowed to throw some known exceptions which are parsed by the caller.
/// Doing so keeps this function simpler and allow tests to actually validate
/// that the errors reported are accurate.
///
/// \return The exit code of the program.  Should be EXIT_SUCCESS on success and
/// EXIT_FAILURE on failure.  The caller extends this to additional integers for
/// errors reported through exceptions.
///
/// \param ui Object to interact with the I/O of the program.
/// \param argc The number of arguments passed on the command line.
/// \param argv NULL-terminated array containing the command line arguments.
/// \param mock_command An extra command provided for testing purposes; should
///     just be NULL other than for tests.
///
/// \throw cmdline::usage_error If the user ran the program with invalid
///     arguments.
/// \throw std::exception This propagates any uncaught exception.  Such
///     exceptions are bugs, but we let them propagate so that the runtime will
///     abort and dump core.
static int
safe_main(cmdline::ui* ui, int argc, const char* const argv[],
          cli::cli_command_ptr mock_command)
{
    cmdline::options_vector options;
    options.push_back(&cli::config_option);
    options.push_back(&cli::variable_option);
    const cmdline::string_option loglevel_option(
        "loglevel", "Level of the messages to log", "level", "info");
    options.push_back(&loglevel_option);
    const cmdline::path_option logfile_option(
        "logfile", "Path to the log file", "file",
        cli::detail::default_log_name().c_str());
    options.push_back(&logfile_option);

    cmdline::commands_map< cli::cli_command > commands;

    commands.insert(new cli::cmd_about());
    commands.insert(new cli::cmd_config());
    commands.insert(new cli::cmd_db_exec());
    commands.insert(new cli::cmd_db_migrate());
    commands.insert(new cli::cmd_help(&options, &commands));

    commands.insert(new cli::cmd_debug(), "Workspace");
    commands.insert(new cli::cmd_list(), "Workspace");
    commands.insert(new cli::cmd_test(), "Workspace");

    commands.insert(new cli::cmd_report(), "Reporting");
    commands.insert(new cli::cmd_report_html(), "Reporting");

    if (mock_command.get() != NULL)
        commands.insert(mock_command);

    const cmdline::parsed_cmdline cmdline = cmdline::parse(argc, argv, options);

    const fs::path logfile(cmdline.get_option< cmdline::path_option >(
        "logfile"));
    fs::mkdir_p(logfile.branch_path(), 0755);
    LD(F("Log file is %s") % logfile);
    utils::install_crash_handlers(logfile.str());
    try {
        logging::set_persistency(cmdline.get_option< cmdline::string_option >(
            "loglevel"), logfile);
    } catch (const std::range_error& e) {
        throw cmdline::usage_error(e.what());
    }

    if (cmdline.arguments().empty())
        throw cmdline::usage_error("No command provided");
    const std::string cmdname = cmdline.arguments()[0];

    const config::tree user_config = cli::load_config(cmdline,
                                                      cmdname != "help");

    cli::cli_command* command = commands.find(cmdname);
    if (command == NULL)
        throw cmdline::usage_error(F("Unknown command '%s'") % cmdname);
    return run_subcommand(ui, command, cmdline.arguments(), user_config);
}


}  // anonymous namespace


/// Gets the name of the default log file.
///
/// \return The path to the log file.
fs::path
cli::detail::default_log_name(void)
{
    // Update doc/troubleshooting.texi if you change this algorithm.
    const optional< std::string > home(utils::getenv("HOME"));
    if (home) {
        return logging::generate_log_name(fs::path(home.get()) / ".kyua" /
                                          "logs", cmdline::progname());
    } else {
        const optional< std::string > tmpdir(utils::getenv("TMPDIR"));
        if (tmpdir) {
            return logging::generate_log_name(fs::path(tmpdir.get()),
                                              cmdline::progname());
        } else {
            return logging::generate_log_name(fs::path("/tmp"),
                                              cmdline::progname());
        }
    }
}


/// Testable entry point, with catch-all exception handlers.
///
/// This entry point does not perform any initialization of global state; it is
/// provided to allow unit-testing of the utility's entry point.
///
/// \param ui Object to interact with the I/O of the program.
/// \param argc The number of arguments passed on the command line.
/// \param argv NULL-terminated array containing the command line arguments.
/// \param mock_command An extra command provided for testing purposes; should
///     just be NULL other than for tests.
///
/// \return 0 on success, some other integer on error.
///
/// \throw std::exception This propagates any uncaught exception.  Such
///     exceptions are bugs, but we let them propagate so that the runtime will
///     abort and dump core.
int
cli::main(cmdline::ui* ui, const int argc, const char* const* const argv,
          cli_command_ptr mock_command)
{
    try {
        const int exit_code = safe_main(ui, argc, argv, mock_command);

        // Codes above 1 are reserved to report conditions captured as
        // exceptions below.
        INV(exit_code == EXIT_SUCCESS || exit_code == EXIT_FAILURE);

        return exit_code;
    } catch (const signals::interrupted_error& e) {
        cmdline::print_error(ui, e.what());
        // Re-deliver the interruption signal to self so that we terminate with
        // the right status.  At this point we should NOT have any custom signal
        // handlers in place.
        ::kill(getpid(), e.signo());
        LD("Interrupt signal re-delivery did not terminate program");
        // If we reach this, something went wrong because we did not exit as
        // intended.  Return an internal error instead.  (Would be nicer to
        // abort in principle, but it wouldn't be a nice experience if it ever
        // happened.)
        return 2;
    } catch (const std::pair< std::string, cmdline::usage_error >& e) {
        const std::string message = F("Usage error for command %s: %s.") %
            e.first % e.second.what();
        LE(message);
        ui->err(message);
        ui->err(F("Type '%s help %s' for usage information.") %
                cmdline::progname() % e.first);
        return 3;
    } catch (const cmdline::usage_error& e) {
        const std::string message = F("Usage error: %s.") % e.what();
        LE(message);
        ui->err(message);
        ui->err(F("Type '%s help' for usage information.") %
                cmdline::progname());
        return 3;
    } catch (const store::old_schema_error& e) {
        const std::string message = F("The database has schema version %s, "
                                      "which is too old; please use db-migrate "
                                      "to upgrade it") % e.old_version();
        cmdline::print_error(ui, message);
        return 2;
    } catch (const std::runtime_error& e) {
        cmdline::print_error(ui, e.what());
        return 2;
    }
}


/// Delegate for ::main().
///
/// This function is supposed to be called directly from the top-level ::main()
/// function.  It takes care of initializing internal libraries and then calls
/// main(ui, argc, argv).
///
/// \pre This function can only be called once.
///
/// \throw std::exception This propagates any uncaught exception.  Such
///     exceptions are bugs, but we let them propagate so that the runtime will
///     abort and dump core.
int
cli::main(const int argc, const char* const* const argv)
{
    logging::set_inmemory();

    LI(F("%s %s") % PACKAGE % VERSION);

    std::string plain_args;
    for (const char* const* arg = argv; *arg != NULL; arg++)
        plain_args += F(" %s") % *arg;
    LI(F("Command line:%s") % plain_args);

    cmdline::init(argv[0]);
    cmdline::ui ui;

    const int exit_code = main(&ui, argc, argv);
    LI(F("Clean exit with code %s") % exit_code);
    return exit_code;
}
@


1.1.1.1.4.1
log
@file main.cpp was added on branch tls-maxphys on 2013-02-25 00:26:09 +0000
@
text
@d1 328
@


1.1.1.1.4.2
log
@resync with head
@
text
@a0 328
// Copyright 2010 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors
//   may be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "cli/main.hpp"

#if defined(HAVE_CONFIG_H)
#   include "config.h"
#endif

extern "C" {
#include <signal.h>
#include <unistd.h>
}

#include <cstdlib>
#include <iostream>
#include <string>
#include <utility>

#include "cli/cmd_about.hpp"
#include "cli/cmd_config.hpp"
#include "cli/cmd_db_exec.hpp"
#include "cli/cmd_db_migrate.hpp"
#include "cli/cmd_debug.hpp"
#include "cli/cmd_help.hpp"
#include "cli/cmd_list.hpp"
#include "cli/cmd_report.hpp"
#include "cli/cmd_report_html.hpp"
#include "cli/cmd_test.hpp"
#include "cli/common.ipp"
#include "cli/config.hpp"
#include "store/exceptions.hpp"
#include "utils/cmdline/commands_map.ipp"
#include "utils/cmdline/exceptions.hpp"
#include "utils/cmdline/globals.hpp"
#include "utils/cmdline/options.hpp"
#include "utils/cmdline/parser.ipp"
#include "utils/cmdline/ui.hpp"
#include "utils/config/tree.ipp"
#include "utils/env.hpp"
#include "utils/format/macros.hpp"
#include "utils/fs/operations.hpp"
#include "utils/fs/path.hpp"
#include "utils/logging/macros.hpp"
#include "utils/logging/operations.hpp"
#include "utils/optional.ipp"
#include "utils/sanity.hpp"
#include "utils/signals/exceptions.hpp"

namespace cmdline = utils::cmdline;
namespace config = utils::config;
namespace fs = utils::fs;
namespace logging = utils::logging;
namespace signals = utils::signals;

using utils::none;
using utils::optional;


namespace {


/// Executes the given subcommand with proper usage_error reporting.
///
/// \param ui Object to interact with the I/O of the program.
/// \param command The subcommand to execute.
/// \param args The part of the command line passed to the subcommand.  The
///     first item of this collection must match the command name.
/// \param user_config The runtime configuration to pass to the subcommand.
///
/// \return The exit code of the command.  Typically 0 on success, some other
/// integer otherwise.
///
/// \throw cmdline::usage_error If the user input to the subcommand is invalid.
///     This error does not encode the command name within it, so this function
///     extends the message in the error to specify which subcommand was
///     affected.
/// \throw std::exception This propagates any uncaught exception.  Such
///     exceptions are bugs, but we let them propagate so that the runtime will
///     abort and dump core.
static int
run_subcommand(cmdline::ui* ui, cli::cli_command* command,
               const cmdline::args_vector& args,
               const config::tree& user_config)
{
    try {
        PRE(command->name() == args[0]);
        return command->main(ui, args, user_config);
    } catch (const cmdline::usage_error& e) {
        throw std::pair< std::string, cmdline::usage_error >(
            command->name(), e);
    }
}


/// Exception-safe version of main.
///
/// This function provides the real meat of the entry point of the program.  It
/// is allowed to throw some known exceptions which are parsed by the caller.
/// Doing so keeps this function simpler and allow tests to actually validate
/// that the errors reported are accurate.
///
/// \return The exit code of the program.  Should be EXIT_SUCCESS on success and
/// EXIT_FAILURE on failure.  The caller extends this to additional integers for
/// errors reported through exceptions.
///
/// \param ui Object to interact with the I/O of the program.
/// \param argc The number of arguments passed on the command line.
/// \param argv NULL-terminated array containing the command line arguments.
/// \param mock_command An extra command provided for testing purposes; should
///     just be NULL other than for tests.
///
/// \throw cmdline::usage_error If the user ran the program with invalid
///     arguments.
/// \throw std::exception This propagates any uncaught exception.  Such
///     exceptions are bugs, but we let them propagate so that the runtime will
///     abort and dump core.
static int
safe_main(cmdline::ui* ui, int argc, const char* const argv[],
          cli::cli_command_ptr mock_command)
{
    cmdline::options_vector options;
    options.push_back(&cli::config_option);
    options.push_back(&cli::variable_option);
    const cmdline::string_option loglevel_option(
        "loglevel", "Level of the messages to log", "level", "info");
    options.push_back(&loglevel_option);
    const cmdline::path_option logfile_option(
        "logfile", "Path to the log file", "file",
        cli::detail::default_log_name().c_str());
    options.push_back(&logfile_option);

    cmdline::commands_map< cli::cli_command > commands;

    commands.insert(new cli::cmd_about());
    commands.insert(new cli::cmd_config());
    commands.insert(new cli::cmd_db_exec());
    commands.insert(new cli::cmd_db_migrate());
    commands.insert(new cli::cmd_help(&options, &commands));

    commands.insert(new cli::cmd_debug(), "Workspace");
    commands.insert(new cli::cmd_list(), "Workspace");
    commands.insert(new cli::cmd_test(), "Workspace");

    commands.insert(new cli::cmd_report(), "Reporting");
    commands.insert(new cli::cmd_report_html(), "Reporting");

    if (mock_command.get() != NULL)
        commands.insert(mock_command);

    const cmdline::parsed_cmdline cmdline = cmdline::parse(argc, argv, options);

    const fs::path logfile(cmdline.get_option< cmdline::path_option >(
        "logfile"));
    fs::mkdir_p(logfile.branch_path(), 0755);
    LD(F("Log file is %s") % logfile);
    utils::install_crash_handlers(logfile.str());
    try {
        logging::set_persistency(cmdline.get_option< cmdline::string_option >(
            "loglevel"), logfile);
    } catch (const std::range_error& e) {
        throw cmdline::usage_error(e.what());
    }

    if (cmdline.arguments().empty())
        throw cmdline::usage_error("No command provided");
    const std::string cmdname = cmdline.arguments()[0];

    const config::tree user_config = cli::load_config(cmdline,
                                                      cmdname != "help");

    cli::cli_command* command = commands.find(cmdname);
    if (command == NULL)
        throw cmdline::usage_error(F("Unknown command '%s'") % cmdname);
    return run_subcommand(ui, command, cmdline.arguments(), user_config);
}


}  // anonymous namespace


/// Gets the name of the default log file.
///
/// \return The path to the log file.
fs::path
cli::detail::default_log_name(void)
{
    // Update doc/troubleshooting.texi if you change this algorithm.
    const optional< std::string > home(utils::getenv("HOME"));
    if (home) {
        return logging::generate_log_name(fs::path(home.get()) / ".kyua" /
                                          "logs", cmdline::progname());
    } else {
        const optional< std::string > tmpdir(utils::getenv("TMPDIR"));
        if (tmpdir) {
            return logging::generate_log_name(fs::path(tmpdir.get()),
                                              cmdline::progname());
        } else {
            return logging::generate_log_name(fs::path("/tmp"),
                                              cmdline::progname());
        }
    }
}


/// Testable entry point, with catch-all exception handlers.
///
/// This entry point does not perform any initialization of global state; it is
/// provided to allow unit-testing of the utility's entry point.
///
/// \param ui Object to interact with the I/O of the program.
/// \param argc The number of arguments passed on the command line.
/// \param argv NULL-terminated array containing the command line arguments.
/// \param mock_command An extra command provided for testing purposes; should
///     just be NULL other than for tests.
///
/// \return 0 on success, some other integer on error.
///
/// \throw std::exception This propagates any uncaught exception.  Such
///     exceptions are bugs, but we let them propagate so that the runtime will
///     abort and dump core.
int
cli::main(cmdline::ui* ui, const int argc, const char* const* const argv,
          cli_command_ptr mock_command)
{
    try {
        const int exit_code = safe_main(ui, argc, argv, mock_command);

        // Codes above 1 are reserved to report conditions captured as
        // exceptions below.
        INV(exit_code == EXIT_SUCCESS || exit_code == EXIT_FAILURE);

        return exit_code;
    } catch (const signals::interrupted_error& e) {
        cmdline::print_error(ui, e.what());
        // Re-deliver the interruption signal to self so that we terminate with
        // the right status.  At this point we should NOT have any custom signal
        // handlers in place.
        ::kill(getpid(), e.signo());
        LD("Interrupt signal re-delivery did not terminate program");
        // If we reach this, something went wrong because we did not exit as
        // intended.  Return an internal error instead.  (Would be nicer to
        // abort in principle, but it wouldn't be a nice experience if it ever
        // happened.)
        return 2;
    } catch (const std::pair< std::string, cmdline::usage_error >& e) {
        const std::string message = F("Usage error for command %s: %s.") %
            e.first % e.second.what();
        LE(message);
        ui->err(message);
        ui->err(F("Type '%s help %s' for usage information.") %
                cmdline::progname() % e.first);
        return 3;
    } catch (const cmdline::usage_error& e) {
        const std::string message = F("Usage error: %s.") % e.what();
        LE(message);
        ui->err(message);
        ui->err(F("Type '%s help' for usage information.") %
                cmdline::progname());
        return 3;
    } catch (const store::old_schema_error& e) {
        const std::string message = F("The database has schema version %s, "
                                      "which is too old; please use db-migrate "
                                      "to upgrade it") % e.old_version();
        cmdline::print_error(ui, message);
        return 2;
    } catch (const std::runtime_error& e) {
        cmdline::print_error(ui, e.what());
        return 2;
    }
}


/// Delegate for ::main().
///
/// This function is supposed to be called directly from the top-level ::main()
/// function.  It takes care of initializing internal libraries and then calls
/// main(ui, argc, argv).
///
/// \pre This function can only be called once.
///
/// \throw std::exception This propagates any uncaught exception.  Such
///     exceptions are bugs, but we let them propagate so that the runtime will
///     abort and dump core.
int
cli::main(const int argc, const char* const* const argv)
{
    logging::set_inmemory();

    LI(F("%s %s") % PACKAGE % VERSION);

    std::string plain_args;
    for (const char* const* arg = argv; *arg != NULL; arg++)
        plain_args += F(" %s") % *arg;
    LI(F("Command line:%s") % plain_args);

    cmdline::init(argv[0]);
    cmdline::ui ui;

    const int exit_code = main(&ui, argc, argv);
    LI(F("Clean exit with code %s") % exit_code);
    return exit_code;
}
@


