<commit_before>/*
* Copyright (c) 2013-2016, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>

#include "Config.h"
#include "version.h"

using namespace boost::program_options;

namespace i2p {
namespace config {
  options_description m_OptionsDesc;
  variables_map       m_Options;

  /* list of renamed options */
  std::map<std::string, std::string> remapped_options = {
    { "tunnelscfg",          "tunconf" },
    { "v6",                  "ipv6" },
    { "httpaddress",         "http.address" },
    { "httpport",            "http.port"    },
    { "httpproxyaddress",    "httpproxy.address"  },
    { "httpproxyport",       "httpproxy.port"     },
    { "socksproxyaddress",   "socksproxy.address" },
    { "socksproxyport",      "socksproxy.port"    },
    { "samaddress",          "sam.address" },
    { "samport",             "sam.port"    },
    { "bobaddress",          "bob.address" },
    { "bobport",             "bob.port"    },
    { "i2pcontroladdress",   "i2pcontrol.address" },
    { "i2pcontroladdress",   "i2pcontrol.port"    },
    { "proxykeys",           "httpproxy.keys" },
  };
  /* list of options, that loose their argument and become simple switch */
  std::set<std::string> boolean_options = {
    "daemon", "floodfill", "notransit", "service", "ipv6"
  };

  /* this function is a solid piece of shit, remove it after 2.6.0 */
  std::pair<std::string, std::string> old_syntax_parser(const std::string& s) {
    std::string name  = "";
    std::string value = "";
    std::size_t pos = 0;
    /* shortcuts -- -h */
    if (s.length() == 2 && s.at(0) == '-' && s.at(1) != '-')
      return make_pair(s.substr(1), "");
    /* old-style -- -log, /log, etc */
    if (s.at(0) == '/' || (s.at(0) == '-' && s.at(1) != '-')) {
      if ((pos = s.find_first_of("= ")) != std::string::npos) {
        name  = s.substr(1, pos - 1);
        value = s.substr(pos + 1);
      } else {
        name  = s.substr(1, pos);
        value = "";
      }
      if (boolean_options.count(name) > 0 && value != "")
        std::cerr << "args: don't give an argument to switch option: " << s << std::endl;
      if (m_OptionsDesc.find_nothrow(name, false)) {
        std::cerr << "args: option " << s << " style is DEPRECATED, use --" << name << " instead" << std::endl;
        return std::make_pair(name, value);
      }
      if (remapped_options.count(name) > 0) {
        name = remapped_options[name];
        std::cerr << "args: option " << s << " is DEPRECATED, use --" << name << " instead" << std::endl;
        return std::make_pair(name, value);
      } /* else */
    }
    /* long options -- --help */
    if (s.substr(0, 2) == "--") {
      if ((pos = s.find_first_of("= ")) != std::string::npos) {
        name  = s.substr(2, pos - 2);
        value = s.substr(pos + 1);
      } else {
        name  = s.substr(2, pos);
        value = "";
      }
      if (boolean_options.count(name) > 0 && value != "") {
        std::cerr << "args: don't give an argument to switch option: " << s << std::endl;
        value = "";
      }
      if (m_OptionsDesc.find_nothrow(name, false))
        return std::make_pair(name, value);
      if (remapped_options.count(name) > 0) {
        name = remapped_options[name];
        std::cerr << "args: option " << s << " is DEPRECATED, use --" << name << " instead" << std::endl;
        return std::make_pair(name, value);
      } /* else */
    }
    std::cerr << "args: unknown option -- " << s << std::endl;
    return std::make_pair("", "");
  }

  void Init() {
    options_description general("General options");
    general.add_options()
      ("help",     "Show this message")
      ("conf",      value<std::string>()->default_value(""),     "Path to main i2pd config file (default: try ~/.i2pd/i2p.conf or /var/lib/i2pd/i2p.conf)")
      ("tunconf",   value<std::string>()->default_value(""),     "Path to config with tunnels list and options (default: try ~/.i2pd/tunnels.cfg or /var/lib/i2pd/tunnels.cfg)")
      ("pidfile",   value<std::string>()->default_value(""),     "Path to pidfile (default: ~/i2pd/i2pd.pid or /var/lib/i2pd/i2pd.pid)")
      ("log",       value<std::string>()->default_value(""),     "Logs destination: stdout, file (stdout if not set, file - otherwise, for compatibility)")
      ("logfile",   value<std::string>()->default_value(""),     "Path to logfile (stdout if not set, autodetect if daemon)")
      ("loglevel",  value<std::string>()->default_value("info"), "Set the minimal level of log messages (debug, info, warn, error)")
      ("host",      value<std::string>()->default_value(""),     "External IP")
      ("port",      value<uint16_t>()->default_value(0),                "Port to listen for incoming connections (default: auto)")
      ("ipv6",      value<bool>()->zero_tokens()->default_value(false), "Enable communication through ipv6")
      ("daemon",    value<bool>()->zero_tokens()->default_value(false), "Router will go to background after start")
      ("service",   value<bool>()->zero_tokens()->default_value(false), "Router will use system folders like '/var/lib/i2pd'")
      ("notransit", value<bool>()->zero_tokens()->default_value(false), "Router will not accept transit tunnels at startup")
      ("floodfill", value<bool>()->zero_tokens()->default_value(false), "Router will be floodfill")
      ("bandwidth", value<char>()->default_value('-'), "Bandwidth limiting: L - 32kbps, O - 256Kbps, P - unlimited")
#ifdef _WIN32
      ("svcctl",    value<std::string>()->default_value(""),     "Windows service management ('install' or 'remove')")
#endif
      ;

    options_description httpserver("HTTP Server options");
    httpserver.add_options()
      ("http.enabled",        value<bool>()->default_value(true),               "Enable or disable webconsole")
      ("http.address",        value<std::string>()->default_value("127.0.0.1"), "Webconsole listen address")
      ("http.port",           value<uint16_t>()->default_value(7070),           "Webconsole listen port")
      ;

    options_description httpproxy("HTTP Proxy options");
    httpproxy.add_options()
      ("httpproxy.enabled",   value<bool>()->default_value(true),                         "Enable or disable HTTP Proxy")
      ("httpproxy.address",   value<std::string>()->default_value("127.0.0.1"),           "HTTP Proxy listen address")
      ("httpproxy.port",      value<uint16_t>()->default_value(4444),                     "HTTP Proxy listen port")
      ("httpproxy.keys",      value<std::string>()->default_value("httpproxy-keys.dat"),  "HTTP Proxy encryption keys")
      ;

    options_description socksproxy("SOCKS Proxy options");
    socksproxy.add_options()
      ("socksproxy.enabled",  value<bool>()->default_value(true),                         "Enable or disable SOCKS Proxy")
      ("socksproxy.address",  value<std::string>()->default_value("127.0.0.1"),           "SOCKS Proxy listen address")
      ("socksproxy.port",     value<uint16_t>()->default_value(4447),                     "SOCKS Proxy listen port")
      ("socksproxy.keys",     value<std::string>()->default_value("socksproxy-keys.dat"), "SOCKS Proxy encryption keys")
      ;

    options_description sam("SAM bridge options");
    sam.add_options()
      ("sam.enabled",         value<bool>()->default_value(false),                        "Enable or disable SAM Application bridge")
      ("sam.address",         value<std::string>()->default_value("127.0.0.1"),           "SAM listen address")
      ("sam.port",            value<uint16_t>()->default_value(7656),                     "SAM listen port")
      ;

    options_description bob("BOB options");
    bob.add_options()
      ("bob.enabled",         value<bool>()->default_value(false),                        "Enable or disable BOB command channel")
      ("bob.address",         value<std::string>()->default_value("127.0.0.1"),           "BOB listen address")
      ("bob.port",            value<uint16_t>()->default_value(2827),                     "BOB listen port")
      ;

    options_description i2pcontrol("I2PControl options");
    i2pcontrol.add_options()
      ("i2pcontrol.enabled",  value<bool>()->default_value(false),                        "Enable or disable I2P Control Protocol")
      ("i2pcontrol.address",  value<std::string>()->default_value("127.0.0.1"),           "I2PCP listen address")
      ("i2pcontrol.port",     value<uint16_t>()->default_value(7650),                     "I2PCP listen port")
      ("i2pcontrol.password", value<std::string>()->default_value("itoopie"),             "I2PCP access password")
      ("i2pcontrol.cert",     value<std::string>()->default_value("i2pcontrol.crt.pem"),  "I2PCP connection cerificate")
      ("i2pcontrol.key",      value<std::string>()->default_value("i2pcontrol.key.pem"),  "I2PCP connection cerificate key")
      ;

    m_OptionsDesc
      .add(general)
      .add(httpserver)
      .add(httpproxy)
      .add(socksproxy)
      .add(sam)
      .add(bob)
      .add(i2pcontrol)
      ;
  }

  void ParseCmdline(int argc, char* argv[]) {
    try {
      auto style = boost::program_options::command_line_style::unix_style
                 | boost::program_options::command_line_style::allow_long_disguise;
      style &=   ~ boost::program_options::command_line_style::allow_guessing;
      store(parse_command_line(argc, argv, m_OptionsDesc, style, old_syntax_parser), m_Options);
    } catch (boost::program_options::error e) {
      std::cerr << "args: " << e.what() << std::endl;
      exit(EXIT_FAILURE);
    }

    if (m_Options.count("help") || m_Options.count("h")) {
      std::cout << "i2pd version " << I2PD_VERSION << " (" << I2P_VERSION << ")" << std::endl;
      std::cout << m_OptionsDesc;
      exit(EXIT_SUCCESS);
    }
  }

  void ParseConfig(const std::string& path) {
    if (path == "")
      return;

    std::ifstream config(path, std::ios::in);

    if (!config.is_open()) {
      std::cerr << "missing/unreadable config file: " << path << std::endl;
      exit(EXIT_FAILURE);
    }

    try {
      store(boost::program_options::parse_config_file(config, m_OptionsDesc), m_Options);
    } catch (boost::program_options::error e) {
      std::cerr << e.what() << std::endl;
      exit(EXIT_FAILURE);
    };
  }

  void Finalize() {
    notify(m_Options);
  };
} // namespace config
} // namespace i2p
<commit_msg>* chg default for --host= option : was broken in 900fc1c<commit_after>/*
* Copyright (c) 2013-2016, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>

#include "Config.h"
#include "version.h"

using namespace boost::program_options;

namespace i2p {
namespace config {
  options_description m_OptionsDesc;
  variables_map       m_Options;

  /* list of renamed options */
  std::map<std::string, std::string> remapped_options = {
    { "tunnelscfg",          "tunconf" },
    { "v6",                  "ipv6" },
    { "httpaddress",         "http.address" },
    { "httpport",            "http.port"    },
    { "httpproxyaddress",    "httpproxy.address"  },
    { "httpproxyport",       "httpproxy.port"     },
    { "socksproxyaddress",   "socksproxy.address" },
    { "socksproxyport",      "socksproxy.port"    },
    { "samaddress",          "sam.address" },
    { "samport",             "sam.port"    },
    { "bobaddress",          "bob.address" },
    { "bobport",             "bob.port"    },
    { "i2pcontroladdress",   "i2pcontrol.address" },
    { "i2pcontroladdress",   "i2pcontrol.port"    },
    { "proxykeys",           "httpproxy.keys" },
  };
  /* list of options, that loose their argument and become simple switch */
  std::set<std::string> boolean_options = {
    "daemon", "floodfill", "notransit", "service", "ipv6"
  };

  /* this function is a solid piece of shit, remove it after 2.6.0 */
  std::pair<std::string, std::string> old_syntax_parser(const std::string& s) {
    std::string name  = "";
    std::string value = "";
    std::size_t pos = 0;
    /* shortcuts -- -h */
    if (s.length() == 2 && s.at(0) == '-' && s.at(1) != '-')
      return make_pair(s.substr(1), "");
    /* old-style -- -log, /log, etc */
    if (s.at(0) == '/' || (s.at(0) == '-' && s.at(1) != '-')) {
      if ((pos = s.find_first_of("= ")) != std::string::npos) {
        name  = s.substr(1, pos - 1);
        value = s.substr(pos + 1);
      } else {
        name  = s.substr(1, pos);
        value = "";
      }
      if (boolean_options.count(name) > 0 && value != "")
        std::cerr << "args: don't give an argument to switch option: " << s << std::endl;
      if (m_OptionsDesc.find_nothrow(name, false)) {
        std::cerr << "args: option " << s << " style is DEPRECATED, use --" << name << " instead" << std::endl;
        return std::make_pair(name, value);
      }
      if (remapped_options.count(name) > 0) {
        name = remapped_options[name];
        std::cerr << "args: option " << s << " is DEPRECATED, use --" << name << " instead" << std::endl;
        return std::make_pair(name, value);
      } /* else */
    }
    /* long options -- --help */
    if (s.substr(0, 2) == "--") {
      if ((pos = s.find_first_of("= ")) != std::string::npos) {
        name  = s.substr(2, pos - 2);
        value = s.substr(pos + 1);
      } else {
        name  = s.substr(2, pos);
        value = "";
      }
      if (boolean_options.count(name) > 0 && value != "") {
        std::cerr << "args: don't give an argument to switch option: " << s << std::endl;
        value = "";
      }
      if (m_OptionsDesc.find_nothrow(name, false))
        return std::make_pair(name, value);
      if (remapped_options.count(name) > 0) {
        name = remapped_options[name];
        std::cerr << "args: option " << s << " is DEPRECATED, use --" << name << " instead" << std::endl;
        return std::make_pair(name, value);
      } /* else */
    }
    std::cerr << "args: unknown option -- " << s << std::endl;
    return std::make_pair("", "");
  }

  void Init() {
    options_description general("General options");
    general.add_options()
      ("help",     "Show this message")
      ("conf",      value<std::string>()->default_value(""),     "Path to main i2pd config file (default: try ~/.i2pd/i2p.conf or /var/lib/i2pd/i2p.conf)")
      ("tunconf",   value<std::string>()->default_value(""),     "Path to config with tunnels list and options (default: try ~/.i2pd/tunnels.cfg or /var/lib/i2pd/tunnels.cfg)")
      ("pidfile",   value<std::string>()->default_value(""),     "Path to pidfile (default: ~/i2pd/i2pd.pid or /var/lib/i2pd/i2pd.pid)")
      ("log",       value<std::string>()->default_value(""),     "Logs destination: stdout, file (stdout if not set, file - otherwise, for compatibility)")
      ("logfile",   value<std::string>()->default_value(""),     "Path to logfile (stdout if not set, autodetect if daemon)")
      ("loglevel",  value<std::string>()->default_value("info"), "Set the minimal level of log messages (debug, info, warn, error)")
      ("host",      value<std::string>()->default_value("0.0.0.0"),     "External IP")
      ("port",      value<uint16_t>()->default_value(0),                "Port to listen for incoming connections (default: auto)")
      ("ipv6",      value<bool>()->zero_tokens()->default_value(false), "Enable communication through ipv6")
      ("daemon",    value<bool>()->zero_tokens()->default_value(false), "Router will go to background after start")
      ("service",   value<bool>()->zero_tokens()->default_value(false), "Router will use system folders like '/var/lib/i2pd'")
      ("notransit", value<bool>()->zero_tokens()->default_value(false), "Router will not accept transit tunnels at startup")
      ("floodfill", value<bool>()->zero_tokens()->default_value(false), "Router will be floodfill")
      ("bandwidth", value<char>()->default_value('-'), "Bandwidth limiting: L - 32kbps, O - 256Kbps, P - unlimited")
#ifdef _WIN32
      ("svcctl",    value<std::string>()->default_value(""),     "Windows service management ('install' or 'remove')")
#endif
      ;

    options_description httpserver("HTTP Server options");
    httpserver.add_options()
      ("http.enabled",        value<bool>()->default_value(true),               "Enable or disable webconsole")
      ("http.address",        value<std::string>()->default_value("127.0.0.1"), "Webconsole listen address")
      ("http.port",           value<uint16_t>()->default_value(7070),           "Webconsole listen port")
      ;

    options_description httpproxy("HTTP Proxy options");
    httpproxy.add_options()
      ("httpproxy.enabled",   value<bool>()->default_value(true),                         "Enable or disable HTTP Proxy")
      ("httpproxy.address",   value<std::string>()->default_value("127.0.0.1"),           "HTTP Proxy listen address")
      ("httpproxy.port",      value<uint16_t>()->default_value(4444),                     "HTTP Proxy listen port")
      ("httpproxy.keys",      value<std::string>()->default_value("httpproxy-keys.dat"),  "HTTP Proxy encryption keys")
      ;

    options_description socksproxy("SOCKS Proxy options");
    socksproxy.add_options()
      ("socksproxy.enabled",  value<bool>()->default_value(true),                         "Enable or disable SOCKS Proxy")
      ("socksproxy.address",  value<std::string>()->default_value("127.0.0.1"),           "SOCKS Proxy listen address")
      ("socksproxy.port",     value<uint16_t>()->default_value(4447),                     "SOCKS Proxy listen port")
      ("socksproxy.keys",     value<std::string>()->default_value("socksproxy-keys.dat"), "SOCKS Proxy encryption keys")
      ;

    options_description sam("SAM bridge options");
    sam.add_options()
      ("sam.enabled",         value<bool>()->default_value(false),                        "Enable or disable SAM Application bridge")
      ("sam.address",         value<std::string>()->default_value("127.0.0.1"),           "SAM listen address")
      ("sam.port",            value<uint16_t>()->default_value(7656),                     "SAM listen port")
      ;

    options_description bob("BOB options");
    bob.add_options()
      ("bob.enabled",         value<bool>()->default_value(false),                        "Enable or disable BOB command channel")
      ("bob.address",         value<std::string>()->default_value("127.0.0.1"),           "BOB listen address")
      ("bob.port",            value<uint16_t>()->default_value(2827),                     "BOB listen port")
      ;

    options_description i2pcontrol("I2PControl options");
    i2pcontrol.add_options()
      ("i2pcontrol.enabled",  value<bool>()->default_value(false),                        "Enable or disable I2P Control Protocol")
      ("i2pcontrol.address",  value<std::string>()->default_value("127.0.0.1"),           "I2PCP listen address")
      ("i2pcontrol.port",     value<uint16_t>()->default_value(7650),                     "I2PCP listen port")
      ("i2pcontrol.password", value<std::string>()->default_value("itoopie"),             "I2PCP access password")
      ("i2pcontrol.cert",     value<std::string>()->default_value("i2pcontrol.crt.pem"),  "I2PCP connection cerificate")
      ("i2pcontrol.key",      value<std::string>()->default_value("i2pcontrol.key.pem"),  "I2PCP connection cerificate key")
      ;

    m_OptionsDesc
      .add(general)
      .add(httpserver)
      .add(httpproxy)
      .add(socksproxy)
      .add(sam)
      .add(bob)
      .add(i2pcontrol)
      ;
  }

  void ParseCmdline(int argc, char* argv[]) {
    try {
      auto style = boost::program_options::command_line_style::unix_style
                 | boost::program_options::command_line_style::allow_long_disguise;
      style &=   ~ boost::program_options::command_line_style::allow_guessing;
      store(parse_command_line(argc, argv, m_OptionsDesc, style, old_syntax_parser), m_Options);
    } catch (boost::program_options::error e) {
      std::cerr << "args: " << e.what() << std::endl;
      exit(EXIT_FAILURE);
    }

    if (m_Options.count("help") || m_Options.count("h")) {
      std::cout << "i2pd version " << I2PD_VERSION << " (" << I2P_VERSION << ")" << std::endl;
      std::cout << m_OptionsDesc;
      exit(EXIT_SUCCESS);
    }
  }

  void ParseConfig(const std::string& path) {
    if (path == "")
      return;

    std::ifstream config(path, std::ios::in);

    if (!config.is_open()) {
      std::cerr << "missing/unreadable config file: " << path << std::endl;
      exit(EXIT_FAILURE);
    }

    try {
      store(boost::program_options::parse_config_file(config, m_OptionsDesc), m_Options);
    } catch (boost::program_options::error e) {
      std::cerr << e.what() << std::endl;
      exit(EXIT_FAILURE);
    };
  }

  void Finalize() {
    notify(m_Options);
  };
} // namespace config
} // namespace i2p
<|endoftext|>


<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stdio.h>
#include <stdlib.h>

#include <map>

#include "base/command_line.h"
#include "base/environment.h"
#include "base/file_util.h"
#include "base/process/launch.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "tools/gn/commands.h"
#include "tools/gn/filesystem_utils.h"
#include "tools/gn/input_file.h"
#include "tools/gn/parse_tree.h"
#include "tools/gn/setup.h"
#include "tools/gn/standard_out.h"
#include "tools/gn/tokenizer.h"
#include "tools/gn/trace.h"

#if defined(OS_WIN)
#include <windows.h>
#include <shellapi.h>
#endif

namespace commands {

namespace {

const char kSwitchList[] = "list";
const char kSwitchShort[] = "short";

bool DoesLineBeginWithComment(const base::StringPiece& line) {
  // Skip whitespace.
  size_t i = 0;
  while (i < line.size() && IsAsciiWhitespace(line[i]))
    i++;

  return i < line.size() && line[i] == '#';
}

// Returns the offset of the beginning of the line identified by |offset|.
size_t BackUpToLineBegin(const std::string& data, size_t offset) {
  // Degenerate case of an empty line. Below we'll try to return the
  // character after the newline, but that will be incorrect in this case.
  if (offset == 0 || Tokenizer::IsNewline(data, offset))
    return offset;

  size_t cur = offset;
  do {
    cur --;
    if (Tokenizer::IsNewline(data, cur))
      return cur + 1;  // Want the first character *after* the newline.
  } while (cur > 0);
  return 0;
}

// Assumes DoesLineBeginWithComment(), this strips the # character from the
// beginning and normalizes preceeding whitespace.
std::string StripHashFromLine(const base::StringPiece& line) {
  // Replace the # sign and everything before it with 3 spaces, so that a
  // normal comment that has a space after the # will be indented 4 spaces
  // (which makes our formatting come out nicely). If the comment is indented
  // from there, we want to preserve that indenting.
  return "   " + line.substr(line.find('#') + 1).as_string();
}

// Tries to find the comment before the setting of the given value.
void GetContextForValue(const Value& value,
                        std::string* location_str,
                        std::string* comment) {
  Location location = value.origin()->GetRange().begin();
  const InputFile* file = location.file();
  if (!file)
    return;

  *location_str = file->name().value() + ":" +
      base::IntToString(location.line_number());

  const std::string& data = file->contents();
  size_t line_off =
      Tokenizer::ByteOffsetOfNthLine(data, location.line_number());

  while (line_off > 1) {
    line_off -= 2;  // Back up to end of previous line.
    size_t previous_line_offset = BackUpToLineBegin(data, line_off);

    base::StringPiece line(&data[previous_line_offset],
                           line_off - previous_line_offset + 1);
    if (!DoesLineBeginWithComment(line))
      break;

    comment->insert(0, StripHashFromLine(line) + "\n");
    line_off = previous_line_offset;
  }
}

void PrintArgHelp(const base::StringPiece& name, const Value& value) {
  OutputString(name.as_string(), DECORATION_YELLOW);
  OutputString("  Default = " + value.ToString(true) + "\n");

  if (value.origin()) {
    std::string location, comment;
    GetContextForValue(value, &location, &comment);
    OutputString("    " + location + "\n" + comment);
  } else {
    OutputString("    (Internally set)\n");
  }
}

int ListArgs(const std::string& build_dir) {
  Setup* setup = new Setup;
  setup->set_check_for_bad_items(false);
  if (!setup->DoSetup(build_dir) || !setup->Run())
    return 1;

  Scope::KeyValueMap build_args;
  setup->build_settings().build_args().MergeDeclaredArguments(&build_args);

  // Find all of the arguments we care about. Use a regular map so they're
  // sorted nicely when we write them out.
  std::map<base::StringPiece, Value> sorted_args;
  std::string list_value =
      base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(kSwitchList);
  if (list_value.empty()) {
    // List all values.
    for (Scope::KeyValueMap::const_iterator i = build_args.begin();
         i != build_args.end(); ++i)
      sorted_args.insert(*i);
  } else {
    // List just the one specified as the parameter to --list.
    Scope::KeyValueMap::const_iterator found_arg = build_args.find(list_value);
    if (found_arg == build_args.end()) {
      Err(Location(), "Unknown build argument.",
          "You asked for \"" + list_value + "\" which I didn't find in any "
          "build file\nassociated with this build.").PrintToStdout();
      return 1;
    }
    sorted_args.insert(*found_arg);
  }

  if (base::CommandLine::ForCurrentProcess()->HasSwitch(kSwitchShort)) {
    // Short key=value output.
    for (std::map<base::StringPiece, Value>::iterator i = sorted_args.begin();
         i != sorted_args.end(); ++i) {
      OutputString(i->first.as_string());
      OutputString(" = ");
      OutputString(i->second.ToString(true));
      OutputString("\n");
    }
    return 0;
  }

  // Long output.
  for (std::map<base::StringPiece, Value>::iterator i = sorted_args.begin();
       i != sorted_args.end(); ++i) {
    PrintArgHelp(i->first, i->second);
    OutputString("\n");
  }

  return 0;
}

#if defined(OS_WIN)

bool RunEditor(const base::FilePath& file_to_edit) {
  SHELLEXECUTEINFO info;
  memset(&info, 0, sizeof(info));
  info.cbSize = sizeof(info);
  info.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_CLASSNAME;
  info.lpFile = file_to_edit.value().c_str();
  info.nShow = SW_SHOW;
  info.lpClass = L".txt";
  if (!::ShellExecuteEx(&info)) {
    Err(Location(), "Couldn't run editor.",
        "Just edit \"" + FilePathToUTF8(file_to_edit) +
        "\" manually instead.").PrintToStdout();
    return false;
  }

  if (!info.hProcess) {
    // Windows re-used an existing process.
    OutputString("\"" + FilePathToUTF8(file_to_edit) +
                 "\" opened in editor, save it and press <Enter> when done.\n");
    getchar();
  } else {
    OutputString("Waiting for editor on \"" + FilePathToUTF8(file_to_edit) +
                 "\"...\n");
    ::WaitForSingleObject(info.hProcess, INFINITE);
    ::CloseHandle(info.hProcess);
  }
  return true;
}

#else  // POSIX

bool RunEditor(const base::FilePath& file_to_edit) {
  // Prefer $VISUAL, then $EDITOR, then vi.
  const char* editor_ptr = getenv("VISUAL");
  if (!editor_ptr)
    editor_ptr = getenv("EDITOR");
  if (!editor_ptr)
    editor_ptr = "vi";

  std::string cmd(editor_ptr);
  cmd.append(" \"");

  // Its impossible to do this properly since we don't know the user's shell,
  // but quoting and escaping internal quotes should handle 99.999% of all
  // cases.
  std::string escaped_name = file_to_edit.value();
  ReplaceSubstringsAfterOffset(&escaped_name, 0, "\"", "\\\"");
  cmd.append(escaped_name);
  cmd.push_back('"');

  OutputString("Waiting for editor on \"" + file_to_edit.value() +
               "\"...\n");
  return system(cmd.c_str()) == 0;
}

#endif

int EditArgsFile(const std::string& build_dir) {
  {
    // Scope the setup. We only use it for some basic state. We'll do the
    // "real" build below in the gen command.
    Setup setup;
    setup.set_check_for_bad_items(false);
    // Don't fill build arguments. We're about to edit the file which supplies
    // these in the first place.
    setup.set_fill_arguments(false);
    if (!setup.DoSetup(build_dir))
      return 1;

    // Ensure the file exists. Need to normalize path separators since on
    // Windows they can come out as forward slashes here, and that confuses some
    // of the commands.
    base::FilePath arg_file =
        setup.build_settings().GetFullPath(setup.GetBuildArgFile())
        .NormalizePathSeparators();
    if (!base::PathExists(arg_file)) {
      std::string argfile_default_contents =
          "# Build arguments go here. Examples:\n"
          "#   enable_doom_melon = true\n"
          "#   crazy_something = \"absolutely\"\n";
#if defined(OS_WIN)
      // Use Windows lineendings for this file since it will often open in
      // Notepad which can't handle Unix ones.
      ReplaceSubstringsAfterOffset(&argfile_default_contents, 0, "\n", "\r\n");
#endif
      base::CreateDirectory(arg_file.DirName());
      base::WriteFile(arg_file, argfile_default_contents.c_str(),
                      argfile_default_contents.size());
    }

    ScopedTrace editor_trace(TraceItem::TRACE_SETUP, "Waiting for editor");
    if (!RunEditor(arg_file))
      return 1;
  }

  // Now do a normal "gen" command.
  OutputString("Generating files...\n");
  std::vector<std::string> gen_commands;
  gen_commands.push_back(build_dir);
  return RunGen(gen_commands);
}

}  // namespace

extern const char kArgs[] = "args";
extern const char kArgs_HelpShort[] =
    "args: Display or configure arguments declared by the build.";
extern const char kArgs_Help[] =
    "gn args [arg name]\n"
    "\n"
    "  See also \"gn help buildargs\" for a more high-level overview of how\n"
    "  build arguments work.\n"
    "\n"
    "Usage\n"
    "  gn args <dir_name>\n"
    "      Open the arguments for the given build directory in an editor\n"
    "      (as specified by the EDITOR environment variable). If the given\n"
    "      build directory doesn't exist, it will be created and an empty\n"
    "      args file will be opened in the editor. You would type something\n"
    "      like this into that file:\n"
    "          enable_doom_melon=false\n"
    "          os=\"android\"\n"
    "\n"
    "      Note: you can edit the build args manually by editing the file\n"
    "      \"args.gn\" in the build directory and then running\n"
    "      \"gn gen <build_dir>\".\n"
    "\n"
    "  gn args <dir_name> --list[=<exact_arg>] [--short]\n"
    "      Lists all build arguments available in the current configuration,\n"
    "      or, if an exact_arg is specified for the list flag, just that one\n"
    "      build argument.\n"
    "\n"
    "      The output will list the declaration location, default value, and\n"
    "      comment preceeding the declaration. If --short is specified,\n"
    "      only the names and values will be printed.\n"
    "\n"
    "      If the dir_name is specified, the build configuration will be\n"
    "      taken from that build directory. The reason this is needed is that\n"
    "      the definition of some arguments is dependent on the build\n"
    "      configuration, so setting some values might add, remove, or change\n"
    "      the default values for other arguments. Specifying your exact\n"
    "      configuration allows the proper arguments to be displayed.\n"
    "\n"
    "      Instead of specifying the dir_name, you can also use the\n"
    "      command-line flag to specify the build configuration:\n"
    "        --args=<exact list of args to use>\n"
    "\n"
    "Examples\n"
    "  gn args out/Debug\n"
    "    Opens an editor with the args for out/Debug.\n"
    "\n"
    "  gn args out/Debug --list --short\n"
    "    Prints all arguments with their default values for the out/Debug\n"
    "    build.\n"
    "\n"
    "  gn args out/Debug --list=cpu_arch\n"
    "    Prints information about the \"cpu_arch\" argument for the out/Debug\n"
    "    build.\n"
    "\n"
    "  gn args --list --args=\"os=\\\"android\\\" enable_doom_melon=true\"\n"
    "    Prints all arguments with the default values for a build with the\n"
    "    given arguments set (which may affect the values of other\n"
    "    arguments).\n";

int RunArgs(const std::vector<std::string>& args) {
  if (args.size() != 1) {
    Err(Location(), "Exactly one build dir needed.",
        "Usage: \"gn args <build_dir>\"\n"
        "Or see \"gn help args\" for more variants.").PrintToStdout();
    return 1;
  }

  if (base::CommandLine::ForCurrentProcess()->HasSwitch(kSwitchList))
    return ListArgs(args[0]);
  return EditArgsFile(args[0]);
}

}  // namespace commands
<commit_msg>Fix Windows cast warning for GN unit test.<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stdio.h>
#include <stdlib.h>

#include <map>

#include "base/command_line.h"
#include "base/environment.h"
#include "base/file_util.h"
#include "base/process/launch.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "tools/gn/commands.h"
#include "tools/gn/filesystem_utils.h"
#include "tools/gn/input_file.h"
#include "tools/gn/parse_tree.h"
#include "tools/gn/setup.h"
#include "tools/gn/standard_out.h"
#include "tools/gn/tokenizer.h"
#include "tools/gn/trace.h"

#if defined(OS_WIN)
#include <windows.h>
#include <shellapi.h>
#endif

namespace commands {

namespace {

const char kSwitchList[] = "list";
const char kSwitchShort[] = "short";

bool DoesLineBeginWithComment(const base::StringPiece& line) {
  // Skip whitespace.
  size_t i = 0;
  while (i < line.size() && IsAsciiWhitespace(line[i]))
    i++;

  return i < line.size() && line[i] == '#';
}

// Returns the offset of the beginning of the line identified by |offset|.
size_t BackUpToLineBegin(const std::string& data, size_t offset) {
  // Degenerate case of an empty line. Below we'll try to return the
  // character after the newline, but that will be incorrect in this case.
  if (offset == 0 || Tokenizer::IsNewline(data, offset))
    return offset;

  size_t cur = offset;
  do {
    cur --;
    if (Tokenizer::IsNewline(data, cur))
      return cur + 1;  // Want the first character *after* the newline.
  } while (cur > 0);
  return 0;
}

// Assumes DoesLineBeginWithComment(), this strips the # character from the
// beginning and normalizes preceeding whitespace.
std::string StripHashFromLine(const base::StringPiece& line) {
  // Replace the # sign and everything before it with 3 spaces, so that a
  // normal comment that has a space after the # will be indented 4 spaces
  // (which makes our formatting come out nicely). If the comment is indented
  // from there, we want to preserve that indenting.
  return "   " + line.substr(line.find('#') + 1).as_string();
}

// Tries to find the comment before the setting of the given value.
void GetContextForValue(const Value& value,
                        std::string* location_str,
                        std::string* comment) {
  Location location = value.origin()->GetRange().begin();
  const InputFile* file = location.file();
  if (!file)
    return;

  *location_str = file->name().value() + ":" +
      base::IntToString(location.line_number());

  const std::string& data = file->contents();
  size_t line_off =
      Tokenizer::ByteOffsetOfNthLine(data, location.line_number());

  while (line_off > 1) {
    line_off -= 2;  // Back up to end of previous line.
    size_t previous_line_offset = BackUpToLineBegin(data, line_off);

    base::StringPiece line(&data[previous_line_offset],
                           line_off - previous_line_offset + 1);
    if (!DoesLineBeginWithComment(line))
      break;

    comment->insert(0, StripHashFromLine(line) + "\n");
    line_off = previous_line_offset;
  }
}

void PrintArgHelp(const base::StringPiece& name, const Value& value) {
  OutputString(name.as_string(), DECORATION_YELLOW);
  OutputString("  Default = " + value.ToString(true) + "\n");

  if (value.origin()) {
    std::string location, comment;
    GetContextForValue(value, &location, &comment);
    OutputString("    " + location + "\n" + comment);
  } else {
    OutputString("    (Internally set)\n");
  }
}

int ListArgs(const std::string& build_dir) {
  Setup* setup = new Setup;
  setup->set_check_for_bad_items(false);
  if (!setup->DoSetup(build_dir) || !setup->Run())
    return 1;

  Scope::KeyValueMap build_args;
  setup->build_settings().build_args().MergeDeclaredArguments(&build_args);

  // Find all of the arguments we care about. Use a regular map so they're
  // sorted nicely when we write them out.
  std::map<base::StringPiece, Value> sorted_args;
  std::string list_value =
      base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(kSwitchList);
  if (list_value.empty()) {
    // List all values.
    for (Scope::KeyValueMap::const_iterator i = build_args.begin();
         i != build_args.end(); ++i)
      sorted_args.insert(*i);
  } else {
    // List just the one specified as the parameter to --list.
    Scope::KeyValueMap::const_iterator found_arg = build_args.find(list_value);
    if (found_arg == build_args.end()) {
      Err(Location(), "Unknown build argument.",
          "You asked for \"" + list_value + "\" which I didn't find in any "
          "build file\nassociated with this build.").PrintToStdout();
      return 1;
    }
    sorted_args.insert(*found_arg);
  }

  if (base::CommandLine::ForCurrentProcess()->HasSwitch(kSwitchShort)) {
    // Short key=value output.
    for (std::map<base::StringPiece, Value>::iterator i = sorted_args.begin();
         i != sorted_args.end(); ++i) {
      OutputString(i->first.as_string());
      OutputString(" = ");
      OutputString(i->second.ToString(true));
      OutputString("\n");
    }
    return 0;
  }

  // Long output.
  for (std::map<base::StringPiece, Value>::iterator i = sorted_args.begin();
       i != sorted_args.end(); ++i) {
    PrintArgHelp(i->first, i->second);
    OutputString("\n");
  }

  return 0;
}

#if defined(OS_WIN)

bool RunEditor(const base::FilePath& file_to_edit) {
  SHELLEXECUTEINFO info;
  memset(&info, 0, sizeof(info));
  info.cbSize = sizeof(info);
  info.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_CLASSNAME;
  info.lpFile = file_to_edit.value().c_str();
  info.nShow = SW_SHOW;
  info.lpClass = L".txt";
  if (!::ShellExecuteEx(&info)) {
    Err(Location(), "Couldn't run editor.",
        "Just edit \"" + FilePathToUTF8(file_to_edit) +
        "\" manually instead.").PrintToStdout();
    return false;
  }

  if (!info.hProcess) {
    // Windows re-used an existing process.
    OutputString("\"" + FilePathToUTF8(file_to_edit) +
                 "\" opened in editor, save it and press <Enter> when done.\n");
    getchar();
  } else {
    OutputString("Waiting for editor on \"" + FilePathToUTF8(file_to_edit) +
                 "\"...\n");
    ::WaitForSingleObject(info.hProcess, INFINITE);
    ::CloseHandle(info.hProcess);
  }
  return true;
}

#else  // POSIX

bool RunEditor(const base::FilePath& file_to_edit) {
  // Prefer $VISUAL, then $EDITOR, then vi.
  const char* editor_ptr = getenv("VISUAL");
  if (!editor_ptr)
    editor_ptr = getenv("EDITOR");
  if (!editor_ptr)
    editor_ptr = "vi";

  std::string cmd(editor_ptr);
  cmd.append(" \"");

  // Its impossible to do this properly since we don't know the user's shell,
  // but quoting and escaping internal quotes should handle 99.999% of all
  // cases.
  std::string escaped_name = file_to_edit.value();
  ReplaceSubstringsAfterOffset(&escaped_name, 0, "\"", "\\\"");
  cmd.append(escaped_name);
  cmd.push_back('"');

  OutputString("Waiting for editor on \"" + file_to_edit.value() +
               "\"...\n");
  return system(cmd.c_str()) == 0;
}

#endif

int EditArgsFile(const std::string& build_dir) {
  {
    // Scope the setup. We only use it for some basic state. We'll do the
    // "real" build below in the gen command.
    Setup setup;
    setup.set_check_for_bad_items(false);
    // Don't fill build arguments. We're about to edit the file which supplies
    // these in the first place.
    setup.set_fill_arguments(false);
    if (!setup.DoSetup(build_dir))
      return 1;

    // Ensure the file exists. Need to normalize path separators since on
    // Windows they can come out as forward slashes here, and that confuses some
    // of the commands.
    base::FilePath arg_file =
        setup.build_settings().GetFullPath(setup.GetBuildArgFile())
        .NormalizePathSeparators();
    if (!base::PathExists(arg_file)) {
      std::string argfile_default_contents =
          "# Build arguments go here. Examples:\n"
          "#   enable_doom_melon = true\n"
          "#   crazy_something = \"absolutely\"\n";
#if defined(OS_WIN)
      // Use Windows lineendings for this file since it will often open in
      // Notepad which can't handle Unix ones.
      ReplaceSubstringsAfterOffset(&argfile_default_contents, 0, "\n", "\r\n");
#endif
      base::CreateDirectory(arg_file.DirName());
      base::WriteFile(arg_file, argfile_default_contents.c_str(),
                      static_cast<int>(argfile_default_contents.size()));
    }

    ScopedTrace editor_trace(TraceItem::TRACE_SETUP, "Waiting for editor");
    if (!RunEditor(arg_file))
      return 1;
  }

  // Now do a normal "gen" command.
  OutputString("Generating files...\n");
  std::vector<std::string> gen_commands;
  gen_commands.push_back(build_dir);
  return RunGen(gen_commands);
}

}  // namespace

extern const char kArgs[] = "args";
extern const char kArgs_HelpShort[] =
    "args: Display or configure arguments declared by the build.";
extern const char kArgs_Help[] =
    "gn args [arg name]\n"
    "\n"
    "  See also \"gn help buildargs\" for a more high-level overview of how\n"
    "  build arguments work.\n"
    "\n"
    "Usage\n"
    "  gn args <dir_name>\n"
    "      Open the arguments for the given build directory in an editor\n"
    "      (as specified by the EDITOR environment variable). If the given\n"
    "      build directory doesn't exist, it will be created and an empty\n"
    "      args file will be opened in the editor. You would type something\n"
    "      like this into that file:\n"
    "          enable_doom_melon=false\n"
    "          os=\"android\"\n"
    "\n"
    "      Note: you can edit the build args manually by editing the file\n"
    "      \"args.gn\" in the build directory and then running\n"
    "      \"gn gen <build_dir>\".\n"
    "\n"
    "  gn args <dir_name> --list[=<exact_arg>] [--short]\n"
    "      Lists all build arguments available in the current configuration,\n"
    "      or, if an exact_arg is specified for the list flag, just that one\n"
    "      build argument.\n"
    "\n"
    "      The output will list the declaration location, default value, and\n"
    "      comment preceeding the declaration. If --short is specified,\n"
    "      only the names and values will be printed.\n"
    "\n"
    "      If the dir_name is specified, the build configuration will be\n"
    "      taken from that build directory. The reason this is needed is that\n"
    "      the definition of some arguments is dependent on the build\n"
    "      configuration, so setting some values might add, remove, or change\n"
    "      the default values for other arguments. Specifying your exact\n"
    "      configuration allows the proper arguments to be displayed.\n"
    "\n"
    "      Instead of specifying the dir_name, you can also use the\n"
    "      command-line flag to specify the build configuration:\n"
    "        --args=<exact list of args to use>\n"
    "\n"
    "Examples\n"
    "  gn args out/Debug\n"
    "    Opens an editor with the args for out/Debug.\n"
    "\n"
    "  gn args out/Debug --list --short\n"
    "    Prints all arguments with their default values for the out/Debug\n"
    "    build.\n"
    "\n"
    "  gn args out/Debug --list=cpu_arch\n"
    "    Prints information about the \"cpu_arch\" argument for the out/Debug\n"
    "    build.\n"
    "\n"
    "  gn args --list --args=\"os=\\\"android\\\" enable_doom_melon=true\"\n"
    "    Prints all arguments with the default values for a build with the\n"
    "    given arguments set (which may affect the values of other\n"
    "    arguments).\n";

int RunArgs(const std::vector<std::string>& args) {
  if (args.size() != 1) {
    Err(Location(), "Exactly one build dir needed.",
        "Usage: \"gn args <build_dir>\"\n"
        "Or see \"gn help args\" for more variants.").PrintToStdout();
    return 1;
  }

  if (base::CommandLine::ForCurrentProcess()->HasSwitch(kSwitchList))
    return ListArgs(args[0]);
  return EditArgsFile(args[0]);
}

}  // namespace commands
<|endoftext|>


<commit_before>/*
TidyEngine
Copyright (C) 2016 Jakob Sinclair

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
Contact the author at: jakob.sinclair99@gmail.com
*/

#include "cache.hpp"
#include <cstdio>
#include "error.hpp"
#include "iomanager.hpp"

Cache Resources;

Cache::Cache()
{
	;
}

Cache::~Cache()
{
	for (auto it : m_Textures)
		it.second.DestroyTex();
}

const Texture &Cache::CreateTexture(std::string name, std::string filepath)
{
	if (m_Textures.find(name) == m_Textures.end()) {
		FIBITMAP *bitmap = IO.LoadImage(filepath);
		bool success = m_Textures[name].CreateTex(bitmap, true, true);
		if (success == false) {
			Error e("Exception: could not create texture " +
					filepath);
			throw e;
		}
		FreeImage_Unload(bitmap);
		return m_Textures[name];
	} else {
		std::printf("Warning: texture %s already exists!\n",
				name.c_str());
		return m_Textures[name];
	}
}

void Cache::DestroyTexture(std::string name)
{
	m_Textures[name].DestroyTex();
	m_Textures.erase(name);
}

const Texture &Cache::GetTexture(std::string name)
{
	if (m_Textures.find(name) != m_Textures.end())
		return m_Textures[name];
	std::printf("Warning: could not find texture %s!", name.c_str());
	return m_Textures["default"];
}

const Sample &Cache::CreateSample(std::string name, std::string filepath)
{
	/* TODO:
	- Find a library to load sound files
	- Implement load function here and in IOManager
	*/
}

void Cache::DestroySample(std::string name)
{
	m_Samples[name].DestroyBuffer();
	m_Samples.erase(name);
}

const Sample &Cache::GetSample(std::string name)
{
	if (m_Samples.find(name) != m_Samples.end())
		return m_Samples[name];
	std::printf("Warning: could not find sample %s!", name.c_str());
	return m_Samples["default"];
}<commit_msg>libTidyEngine: return temp object<commit_after>/*
TidyEngine
Copyright (C) 2016 Jakob Sinclair

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
Contact the author at: jakob.sinclair99@gmail.com
*/

#include "cache.hpp"
#include <cstdio>
#include "error.hpp"
#include "iomanager.hpp"

Cache Resources;

Cache::Cache()
{
	;
}

Cache::~Cache()
{
	for (auto it : m_Textures)
		it.second.DestroyTex();
}

const Texture &Cache::CreateTexture(std::string name, std::string filepath)
{
	if (m_Textures.find(name) == m_Textures.end()) {
		FIBITMAP *bitmap = IO.LoadImage(filepath);
		bool success = m_Textures[name].CreateTex(bitmap, true, true);
		if (success == false) {
			Error e("Exception: could not create texture " +
					filepath);
			throw e;
		}
		FreeImage_Unload(bitmap);
		return m_Textures[name];
	} else {
		std::printf("Warning: texture %s already exists!\n",
				name.c_str());
		return m_Textures[name];
	}
}

void Cache::DestroyTexture(std::string name)
{
	m_Textures[name].DestroyTex();
	m_Textures.erase(name);
}

const Texture &Cache::GetTexture(std::string name)
{
	if (m_Textures.find(name) != m_Textures.end())
		return m_Textures[name];
	std::printf("Warning: could not find texture %s!", name.c_str());
	return m_Textures["default"];
}

const Sample &Cache::CreateSample(std::string name, std::string filepath)
{
	/* TODO:
	- Find a library to load sound files
	- Implement load function here and in IOManager
	*/
	return Sample();
}

void Cache::DestroySample(std::string name)
{
	m_Samples[name].DestroyBuffer();
	m_Samples.erase(name);
}

const Sample &Cache::GetSample(std::string name)
{
	if (m_Samples.find(name) != m_Samples.end())
		return m_Samples[name];
	std::printf("Warning: could not find sample %s!", name.c_str());
	return Sample();
}<|endoftext|>


<commit_before>/*
    This file is part of libkdepim.

    Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>
    Copyright (c) 2005 Rafal Rzepecki <divide@users.sourceforge.net>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <limits.h>

#include <QString>

#include <kstandarddirs.h>
#include <kglobal.h>
#include <kconfig.h>
#include <klocale.h>
#include <ksystemtimezone.h>
#include <kdebug.h>

#include "kpimprefs.h"

KPimPrefs::KPimPrefs( const QString &name )
  : KConfigSkeleton( name )
{
}

KPimPrefs::~KPimPrefs()
{
}

void KPimPrefs::usrSetDefaults()
{
  setCategoryDefaults();
}

void KPimPrefs::usrReadConfig()
{
  kDebug(5300) << "KPimPrefs::usrReadConfig()" << endl;

  KConfigGroup group( config(), "General" );
  mCustomCategories = group.readEntry( "Custom Categories" , QStringList() );
  if ( mCustomCategories.isEmpty() ) setCategoryDefaults();
  mCustomCategories.sort();
}

KDateTime::Spec KPimPrefs::timeSpec()
{
  const KTimeZone *zone = 0;
	// FIXME: In KDE 4, use KSystemTimeZones::local instead of system and file system calls!

  // Read TimeZoneId from korganizerrc.
  KConfig korgcfg( KStandardDirs::locate( "config", "korganizerrc" ) );
  KConfigGroup group( &korgcfg, "Time & Date" );
  QString tz( group.readEntry( "TimeZoneId" ) );
  if ( !tz.isEmpty() ) {
    zone = KSystemTimeZones::zone( tz );
    if ( zone )
      kDebug(5300) << "timezone from korganizerrc is " << tz << endl;
  }

  // If timezone not found in KOrg, use the system's default timezone.
  if ( !zone ) {
    zone = KSystemTimeZones::local();
    if ( zone )
      kDebug(5300) << "system timezone is " << zone->name() << endl;
  }

  return zone ? KDateTime::Spec( zone ) : KDateTime::ClockTime;
}

void KPimPrefs::usrWriteConfig()
{
  KConfigGroup group( config(), "General" );
  group.writeEntry( "Custom Categories", mCustomCategories );
}

const QString KPimPrefs::categorySeparator = ":";
<commit_msg>Call base class implementation. This works around the problem in kdelibs that the usrWriteConfig() function has changed its semantic.<commit_after>/*
    This file is part of libkdepim.

    Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>
    Copyright (c) 2005 Rafal Rzepecki <divide@users.sourceforge.net>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <limits.h>

#include <QString>

#include <kstandarddirs.h>
#include <kglobal.h>
#include <kconfig.h>
#include <klocale.h>
#include <ksystemtimezone.h>
#include <kdebug.h>

#include "kpimprefs.h"

KPimPrefs::KPimPrefs( const QString &name )
  : KConfigSkeleton( name )
{
}

KPimPrefs::~KPimPrefs()
{
}

void KPimPrefs::usrSetDefaults()
{
  setCategoryDefaults();
}

void KPimPrefs::usrReadConfig()
{
  kDebug(5300) << "KPimPrefs::usrReadConfig()" << endl;

  KConfigGroup group( config(), "General" );
  mCustomCategories = group.readEntry( "Custom Categories" , QStringList() );
  if ( mCustomCategories.isEmpty() ) setCategoryDefaults();
  mCustomCategories.sort();
}

KDateTime::Spec KPimPrefs::timeSpec()
{
  const KTimeZone *zone = 0;
	// FIXME: In KDE 4, use KSystemTimeZones::local instead of system and file system calls!

  // Read TimeZoneId from korganizerrc.
  KConfig korgcfg( KStandardDirs::locate( "config", "korganizerrc" ) );
  KConfigGroup group( &korgcfg, "Time & Date" );
  QString tz( group.readEntry( "TimeZoneId" ) );
  if ( !tz.isEmpty() ) {
    zone = KSystemTimeZones::zone( tz );
    if ( zone )
      kDebug(5300) << "timezone from korganizerrc is " << tz << endl;
  }

  // If timezone not found in KOrg, use the system's default timezone.
  if ( !zone ) {
    zone = KSystemTimeZones::local();
    if ( zone )
      kDebug(5300) << "system timezone is " << zone->name() << endl;
  }

  return zone ? KDateTime::Spec( zone ) : KDateTime::ClockTime;
}

void KPimPrefs::usrWriteConfig()
{
  KConfigGroup group( config(), "General" );
  group.writeEntry( "Custom Categories", mCustomCategories );

  KConfigSkeleton::usrWriteConfig();
}

const QString KPimPrefs::categorySeparator = ":";
<|endoftext|>


<commit_before>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#pragma once

#include <caf/logger.hpp>

#include "vast/config.hpp"
#include "vast/detail/pp.hpp"
#include "vast/detail/type_traits.hpp"

// -- VAST logging macros ------------------------------------------------------

#if defined(VAST_LOG_LEVEL)

#define VAST_LOG_IMPL(lvl, msg) CAF_LOG_IMPL("vast", lvl, msg)

#define VAST_LOG_2(lvl, m1) VAST_LOG_IMPL(lvl, m1)

#define VAST_LOG_3(lvl, m1, m2) VAST_LOG_IMPL(lvl, m1 << m2)

#define VAST_LOG_4(lvl, m1, m2, m3) VAST_LOG_IMPL(lvl, m1 << m2 << m3)

#define VAST_LOG_5(lvl, m1, m2, m3, m4) VAST_LOG_IMPL(lvl, m1 << m2 << m3 << m4)

#define VAST_LOG_6(lvl, m1, m2, m3, m4, m5)                                    \
  VAST_LOG_IMPL(lvl, m1 << m2 << m3 << m4 << m5)

#define VAST_LOG_7(lvl, m1, m2, m3, m4, m5, m6)                                \
  VAST_LOG_IMPL(lvl, m1 << m2 << m3 << m4 << m5 << m6)

#define VAST_LOG_8(lvl, m1, m2, m3, m4, m5, m6, m7)                            \
  VAST_LOG_IMPL(lvl, m1 << m2 << m3 << m4 << m5 << m6 << m7)

#define VAST_LOG_9(lvl, m1, m2, m3, m4, m5, m6, m7, m8)                        \
  VAST_LOG_IMPL(lvl, m1 << m2 << m3 << m4 << m5 << m6 << m7 << m8)

#define VAST_LOG_10(lvl, m1, m2, m3, m4, m5, m6, m7, m8, m9)                   \
  VAST_LOG_IMPL(lvl, m1 << m2 << m3 << m4 << m5 << m6 << m7 << m8 << m9)

#define VAST_LOG(...) VAST_PP_OVERLOAD(VAST_LOG_, __VA_ARGS__)(__VA_ARGS__)

namespace vast::detail {
template <class T>
auto id_or_name(T&& x) {
  static_assert(
    !std::is_same_v<const char*, std::remove_reference<T>>,
    "const char* is not allowed for the first argument in a logging statement"
    "supply a component or use `VAST_[ERROR|WARNING|INFO|DEBUG]_ANON` instead");

  if constexpr (std::is_pointer_v<T>) {
    using value_type = std::remove_pointer_t<T>;
    if constexpr (has_ostream_operator<value_type>)
      return *x;
    else if constexpr (has_to_string<value_type>)
      return to_string(*x);
    else
      return caf::detail::pretty_type_name(typeid(value_type));
  } else {
    if constexpr (has_ostream_operator<T>)
      return x;
    else if constexpr (has_to_string<T>)
      return to_string(x);
    else
      return caf::detail::pretty_type_name(typeid(T));
  }
}
} // namespace vast::detail
#define VAST_LOG_COMPONENT(lvl, m, ...)                                        \
  VAST_LOG(lvl, ::vast::detail::id_or_name(m), __VA_ARGS__)

#if VAST_LOG_LEVEL >= CAF_LOG_LEVEL_TRACE

#define VAST_TRACE(...)                                                        \
  VAST_LOG(CAF_LOG_LEVEL_TRACE, "ENTRY", __VA_ARGS__);                         \
  auto CAF_UNIFYN(vast_log_trace_guard_) = ::caf::detail::make_scope_guard(    \
    [=] { VAST_LOG(CAF_LOG_LEVEL_TRACE, "EXIT"); })

#else // VAST_LOG_LEVEL > CAF_LOG_LEVEL_TRACE

#define VAST_TRACE(...) CAF_VOID_STMT

#endif // VAST_LOG_LEVEL > CAF_LOG_LEVEL_TRACE

#if VAST_LOG_LEVEL >= 0
#define VAST_ERROR(...) VAST_LOG_COMPONENT(CAF_LOG_LEVEL_ERROR, __VA_ARGS__)
#define VAST_ERROR_ANON(...) VAST_LOG(CAF_LOG_LEVEL_ERROR, __VA_ARGS__)
#else
#define VAST_ERROR(...) CAF_VOID_STMT
#define VAST_ERROR_ANON(...) CAF_VOID_STMT
#endif

#if VAST_LOG_LEVEL >= 1
#define VAST_WARNING(...) VAST_LOG_COMPONENT(CAF_LOG_LEVEL_WARNING, __VA_ARGS__)
#define VAST_WARNING_ANON(...) VAST_LOG(CAF_LOG_LEVEL_WARNING, __VA_ARGS__)
#else
#define VAST_WARNING(...) CAF_VOID_STMT
#define VAST_WARNING_ANON(...) CAF_VOID_STMT
#endif

#if VAST_LOG_LEVEL >= 2
#define VAST_INFO(...) VAST_LOG_COMPONENT(CAF_LOG_LEVEL_INFO, __VA_ARGS__)
#define VAST_INFO_ANON(...) VAST_LOG(CAF_LOG_LEVEL_INFO, __VA_ARGS__)
#else
#define VAST_INFO(...) CAF_VOID_STMT
#define VAST_INFO_ANON(...) CAF_VOID_STMT
#endif

#if VAST_LOG_LEVEL >= 3
#define VAST_DEBUG(...) VAST_LOG_COMPONENT(CAF_LOG_LEVEL_DEBUG, __VA_ARGS__)
#define VAST_DEBUG_ANON(...) VAST_LOG(CAF_LOG_LEVEL_DEBUG, __VA_ARGS__)
#else
#define VAST_DEBUG(...) CAF_VOID_STMT
#define VAST_DEBUG_ANON(...) CAF_VOID_STMT
#endif

#else // defined(VAST_LOG_LEVEL)

#define VAST_LOG(...) CAF_VOID_STMT

#define VAST_LOG_COMPONENT(...) CAF_VOID_STMT

#define VAST_TRACE(...) CAF_VOID_STMT

#define VAST_ERROR(...) CAF_VOID_STMT
#define VAST_ERROR_ANON(...) CAF_VOID_STMT

#define VAST_WARNING(...) CAF_VOID_STMT
#define VAST_WARNING_ANON(...) CAF_VOID_STMT

#define VAST_INFO(...) CAF_VOID_STMT
#define VAST_INFO_ANON(...) CAF_VOID_STMT

#define VAST_DEBUG(...) CAF_VOID_STMT
#define VAST_DEBUG_ANON(...) CAF_VOID_STMT

#endif // defined(VAST_LOG_LEVEL)

// -- VAST_ARG utility for formatting log output -------------------------------

#define VAST_ARG_1(x) CAF_ARG(x)

#define VAST_ARG_2(x_name, x) CAF_ARG2(x_name, x)

#define VAST_ARG_3(x_name, first, last) CAF_ARG3(x_name, first, last)

/// Nicely formats a variable or argument. For example, `VAST_ARG(foo)`
/// generates `foo = ...` in log output, where `...` is the content of the
/// variable. `VAST_ARG("size", xs.size())` generates the output
/// `size = xs.size()`.
#define VAST_ARG(...) VAST_PP_OVERLOAD(VAST_ARG_, __VA_ARGS__)(__VA_ARGS__)

// -- VAST_UNUSED utility for suppressing compiler warnings --------------------

#define VAST_UNUSED_1(x1) CAF_IGNORE_UNUSED(x1)

#define VAST_UNUSED_2(x1, x2)                                                  \
  VAST_UNUSED_1(x1);                                                           \
  CAF_IGNORE_UNUSED(x2)

#define VAST_UNUSED_3(x1, x2, x3)                                              \
  VAST_UNUSED_2(x1, x2);                                                       \
  CAF_IGNORE_UNUSED(x3)

#define VAST_UNUSED_4(x1, x2, x3, x4)                                          \
  VAST_UNUSED_3(x1, x2, x3);                                                   \
  CAF_IGNORE_UNUSED(x4)

#define VAST_UNUSED_5(x1, x2, x3, x4, x5)                                      \
  VAST_UNUSED_4(x1, x2, x3, x4);                                               \
  CAF_IGNORE_UNUSED(x5)

#define VAST_UNUSED_6(x1, x2, x3, x4, x5, x6)                                  \
  VAST_UNUSED_5(x1, x2, x3, x4, x5);                                           \
  CAF_IGNORE_UNUSED(x6)

#define VAST_UNUSED_7(x1, x2, x3, x4, x5, x6, x7)                              \
  VAST_UNUSED_6(x1, x2, x3, x4, x5, x6);                                       \
  CAF_IGNORE_UNUSED(x7)

#define VAST_UNUSED_8(x1, x2, x3, x4, x5, x6, x7, x8)                          \
  VAST_UNUSED_7(x1, x2, x3, x4, x5, x6, x7);                                   \
  CAF_IGNORE_UNUSED(x8)

#define VAST_UNUSED_9(x1, x2, x3, x4, x5, x6, x7, x8, x9)                      \
  VAST_UNUSED_8(x1, x2, x3, x4, x5, x6, x7, x8);                               \
  CAF_IGNORE_UNUSED(x9)

/// Suppresses compiler warnings for unused arguments.
#define VAST_UNUSED(...)                                                       \
  VAST_PP_OVERLOAD(VAST_UNUSED_, __VA_ARGS__)(__VA_ARGS__)
<commit_msg>Fix hardcoding of log level constants<commit_after>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#pragma once

#include <caf/logger.hpp>

#include "vast/config.hpp"
#include "vast/detail/pp.hpp"
#include "vast/detail/type_traits.hpp"

// -- VAST logging macros ------------------------------------------------------

#if defined(VAST_LOG_LEVEL)

#define VAST_LOG_IMPL(lvl, msg) CAF_LOG_IMPL("vast", lvl, msg)

#define VAST_LOG_2(lvl, m1) VAST_LOG_IMPL(lvl, m1)

#define VAST_LOG_3(lvl, m1, m2) VAST_LOG_IMPL(lvl, m1 << m2)

#define VAST_LOG_4(lvl, m1, m2, m3) VAST_LOG_IMPL(lvl, m1 << m2 << m3)

#define VAST_LOG_5(lvl, m1, m2, m3, m4) VAST_LOG_IMPL(lvl, m1 << m2 << m3 << m4)

#define VAST_LOG_6(lvl, m1, m2, m3, m4, m5)                                    \
  VAST_LOG_IMPL(lvl, m1 << m2 << m3 << m4 << m5)

#define VAST_LOG_7(lvl, m1, m2, m3, m4, m5, m6)                                \
  VAST_LOG_IMPL(lvl, m1 << m2 << m3 << m4 << m5 << m6)

#define VAST_LOG_8(lvl, m1, m2, m3, m4, m5, m6, m7)                            \
  VAST_LOG_IMPL(lvl, m1 << m2 << m3 << m4 << m5 << m6 << m7)

#define VAST_LOG_9(lvl, m1, m2, m3, m4, m5, m6, m7, m8)                        \
  VAST_LOG_IMPL(lvl, m1 << m2 << m3 << m4 << m5 << m6 << m7 << m8)

#define VAST_LOG_10(lvl, m1, m2, m3, m4, m5, m6, m7, m8, m9)                   \
  VAST_LOG_IMPL(lvl, m1 << m2 << m3 << m4 << m5 << m6 << m7 << m8 << m9)

#define VAST_LOG(...) VAST_PP_OVERLOAD(VAST_LOG_, __VA_ARGS__)(__VA_ARGS__)

namespace vast::detail {

template <class T>
auto id_or_name(T&& x) {
  static_assert(
    !std::is_same_v<const char*, std::remove_reference<T>>,
    "const char* is not allowed for the first argument in a logging statement. "
    "Supply a component or use VAST_[ERROR|WARNING|INFO|DEBUG]_ANON instead.");
  if constexpr (std::is_pointer_v<T>) {
    using value_type = std::remove_pointer_t<T>;
    if constexpr (has_ostream_operator<value_type>)
      return *x;
    else if constexpr (has_to_string<value_type>)
      return to_string(*x);
    else
      return caf::detail::pretty_type_name(typeid(value_type));
  } else {
    if constexpr (has_ostream_operator<T>)
      return x;
    else if constexpr (has_to_string<T>)
      return to_string(x);
    else
      return caf::detail::pretty_type_name(typeid(T));
  }
}

} // namespace vast::detail

#define VAST_LOG_COMPONENT(lvl, m, ...)                                        \
  VAST_LOG(lvl, ::vast::detail::id_or_name(m), __VA_ARGS__)

#if VAST_LOG_LEVEL >= CAF_LOG_LEVEL_TRACE

#define VAST_TRACE(...)                                                        \
  VAST_LOG(CAF_LOG_LEVEL_TRACE, "ENTRY", __VA_ARGS__);                         \
  auto CAF_UNIFYN(vast_log_trace_guard_) = ::caf::detail::make_scope_guard(    \
    [=] { VAST_LOG(CAF_LOG_LEVEL_TRACE, "EXIT"); })

#else // VAST_LOG_LEVEL > CAF_LOG_LEVEL_TRACE

#define VAST_TRACE(...) CAF_VOID_STMT

#endif // VAST_LOG_LEVEL > CAF_LOG_LEVEL_TRACE

#if VAST_LOG_LEVEL >= CAF_LOG_LEVEL_ERROR
#define VAST_ERROR(...) VAST_LOG_COMPONENT(CAF_LOG_LEVEL_ERROR, __VA_ARGS__)
#define VAST_ERROR_ANON(...) VAST_LOG(CAF_LOG_LEVEL_ERROR, __VA_ARGS__)
#else
#define VAST_ERROR(...) CAF_VOID_STMT
#define VAST_ERROR_ANON(...) CAF_VOID_STMT
#endif

#if VAST_LOG_LEVEL >= CAF_LOG_LEVEL_WARNING
#define VAST_WARNING(...) VAST_LOG_COMPONENT(CAF_LOG_LEVEL_WARNING, __VA_ARGS__)
#define VAST_WARNING_ANON(...) VAST_LOG(CAF_LOG_LEVEL_WARNING, __VA_ARGS__)
#else
#define VAST_WARNING(...) CAF_VOID_STMT
#define VAST_WARNING_ANON(...) CAF_VOID_STMT
#endif

#if VAST_LOG_LEVEL >= CAF_LOG_LEVEL_INFO
#define VAST_INFO(...) VAST_LOG_COMPONENT(CAF_LOG_LEVEL_INFO, __VA_ARGS__)
#define VAST_INFO_ANON(...) VAST_LOG(CAF_LOG_LEVEL_INFO, __VA_ARGS__)
#else
#define VAST_INFO(...) CAF_VOID_STMT
#define VAST_INFO_ANON(...) CAF_VOID_STMT
#endif

#if VAST_LOG_LEVEL >= CAF_LOG_LEVEL_DEBUG
#define VAST_DEBUG(...) VAST_LOG_COMPONENT(CAF_LOG_LEVEL_DEBUG, __VA_ARGS__)
#define VAST_DEBUG_ANON(...) VAST_LOG(CAF_LOG_LEVEL_DEBUG, __VA_ARGS__)
#else
#define VAST_DEBUG(...) CAF_VOID_STMT
#define VAST_DEBUG_ANON(...) CAF_VOID_STMT
#endif

#else // defined(VAST_LOG_LEVEL)

#define VAST_LOG(...) CAF_VOID_STMT

#define VAST_LOG_COMPONENT(...) CAF_VOID_STMT

#define VAST_TRACE(...) CAF_VOID_STMT

#define VAST_ERROR(...) CAF_VOID_STMT
#define VAST_ERROR_ANON(...) CAF_VOID_STMT

#define VAST_WARNING(...) CAF_VOID_STMT
#define VAST_WARNING_ANON(...) CAF_VOID_STMT

#define VAST_INFO(...) CAF_VOID_STMT
#define VAST_INFO_ANON(...) CAF_VOID_STMT

#define VAST_DEBUG(...) CAF_VOID_STMT
#define VAST_DEBUG_ANON(...) CAF_VOID_STMT

#endif // defined(VAST_LOG_LEVEL)

// -- VAST_ARG utility for formatting log output -------------------------------

#define VAST_ARG_1(x) CAF_ARG(x)

#define VAST_ARG_2(x_name, x) CAF_ARG2(x_name, x)

#define VAST_ARG_3(x_name, first, last) CAF_ARG3(x_name, first, last)

/// Nicely formats a variable or argument. For example, `VAST_ARG(foo)`
/// generates `foo = ...` in log output, where `...` is the content of the
/// variable. `VAST_ARG("size", xs.size())` generates the output
/// `size = xs.size()`.
#define VAST_ARG(...) VAST_PP_OVERLOAD(VAST_ARG_, __VA_ARGS__)(__VA_ARGS__)

// -- VAST_UNUSED utility for suppressing compiler warnings --------------------

#define VAST_UNUSED_1(x1) CAF_IGNORE_UNUSED(x1)

#define VAST_UNUSED_2(x1, x2)                                                  \
  VAST_UNUSED_1(x1);                                                           \
  CAF_IGNORE_UNUSED(x2)

#define VAST_UNUSED_3(x1, x2, x3)                                              \
  VAST_UNUSED_2(x1, x2);                                                       \
  CAF_IGNORE_UNUSED(x3)

#define VAST_UNUSED_4(x1, x2, x3, x4)                                          \
  VAST_UNUSED_3(x1, x2, x3);                                                   \
  CAF_IGNORE_UNUSED(x4)

#define VAST_UNUSED_5(x1, x2, x3, x4, x5)                                      \
  VAST_UNUSED_4(x1, x2, x3, x4);                                               \
  CAF_IGNORE_UNUSED(x5)

#define VAST_UNUSED_6(x1, x2, x3, x4, x5, x6)                                  \
  VAST_UNUSED_5(x1, x2, x3, x4, x5);                                           \
  CAF_IGNORE_UNUSED(x6)

#define VAST_UNUSED_7(x1, x2, x3, x4, x5, x6, x7)                              \
  VAST_UNUSED_6(x1, x2, x3, x4, x5, x6);                                       \
  CAF_IGNORE_UNUSED(x7)

#define VAST_UNUSED_8(x1, x2, x3, x4, x5, x6, x7, x8)                          \
  VAST_UNUSED_7(x1, x2, x3, x4, x5, x6, x7);                                   \
  CAF_IGNORE_UNUSED(x8)

#define VAST_UNUSED_9(x1, x2, x3, x4, x5, x6, x7, x8, x9)                      \
  VAST_UNUSED_8(x1, x2, x3, x4, x5, x6, x7, x8);                               \
  CAF_IGNORE_UNUSED(x9)

/// Suppresses compiler warnings for unused arguments.
#define VAST_UNUSED(...)                                                       \
  VAST_PP_OVERLOAD(VAST_UNUSED_, __VA_ARGS__)(__VA_ARGS__)
<|endoftext|>


<commit_before>//===-- MICmdArgValConsume.cpp -------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

//++
// File:        MICmdArgValConsume.cpp
//
// Overview:    CMICmdArgValConsume implementation.
//
// Environment: Compilers:  Visual C++ 12.
//                          gcc (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1
//              Libraries:  See MIReadmetxt.
//
// Copyright:   None.
//--

// In-house headers:
#include "MICmdArgValConsume.h"
#include "MICmdArgContext.h"

//++ ------------------------------------------------------------------------------------
// Details: CMICmdArgValConsume constructor.
// Type:    Method.
// Args:    None.
// Return:  None.
// Throws:  None.
//--
CMICmdArgValConsume::CMICmdArgValConsume(void)
{
}

//++ ------------------------------------------------------------------------------------
// Details: CMICmdArgValConsume constructor.
// Type:    Method.
// Args:    vrArgName       - (R) Argument's name to search by.
//          vbMandatory     - (R) True = Yes must be present, false = optional argument.
// Return:  None.
// Throws:  None.
//--
CMICmdArgValConsume::CMICmdArgValConsume(const CMIUtilString &vrArgName, const bool vbMandatory)
    : CMICmdArgValBaseTemplate(vrArgName, vbMandatory, true)
{
}

//++ ------------------------------------------------------------------------------------
// Details: CMICmdArgValConsume destructor.
// Type:    Overidden.
// Args:    None.
// Return:  None.
// Throws:  None.
//--
CMICmdArgValConsume::~CMICmdArgValConsume(void)
{
}

//++ ------------------------------------------------------------------------------------
// Details: Parse the command's argument options string and try to extract the value *this
//          argument is looking for.
// Type:    Overridden.
// Args:    vwArgContext    - (R) The command's argument options string.
// Return:  MIstatus::success - Functional succeeded.
//          MIstatus::failure - Functional failed.
// Throws:  None.
//--
bool
CMICmdArgValConsume::Validate(CMICmdArgContext &vwArgContext)
{
    if (vwArgContext.IsEmpty())
        return MIstatus::success;

    if (vwArgContext.GetNumberArgsPresent() == 1)
    {
        const CMIUtilString &rArg(vwArgContext.GetArgsLeftToParse());
        m_bFound = true;
        m_bValid = true;
        vwArgContext.RemoveArg(rArg);
        return MIstatus::success;
    }

    // In reality there are more than one option,  if so the file option
    // is the last one (don't handle that here - find the best looking one)
    const CMIUtilString::VecString_t vecOptions(vwArgContext.GetArgs());
    CMIUtilString::VecString_t::const_iterator it = vecOptions.begin();
    while (it != vecOptions.end())
    {
        const CMIUtilString &rTxt(*it);
        m_bFound = true;

        if (vwArgContext.RemoveArg(rTxt))
        {
            m_bValid = true;
            return MIstatus::success;
        }
        else
            return MIstatus::success;

        // Next
        ++it;
    }

    return MIstatus::failure;
}

//++ ------------------------------------------------------------------------------------
// Details: Nothing to examine as we just want to consume the argument or option (ignore
//          it).
// Type:    Method.
// Args:    None.
// Return:  bool -  True = yes ok, false = not ok.
// Throws:  None.
//--
bool
CMICmdArgValConsume::IsOk(void) const
{
    return true;
}
<commit_msg>Fix handling of data-disassemble command arguments.<commit_after>//===-- MICmdArgValConsume.cpp -------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

//++
// File:        MICmdArgValConsume.cpp
//
// Overview:    CMICmdArgValConsume implementation.
//
// Environment: Compilers:  Visual C++ 12.
//                          gcc (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1
//              Libraries:  See MIReadmetxt.
//
// Copyright:   None.
//--

// In-house headers:
#include "MICmdArgValConsume.h"
#include "MICmdArgContext.h"

//++ ------------------------------------------------------------------------------------
// Details: CMICmdArgValConsume constructor.
// Type:    Method.
// Args:    None.
// Return:  None.
// Throws:  None.
//--
CMICmdArgValConsume::CMICmdArgValConsume(void)
{
}

//++ ------------------------------------------------------------------------------------
// Details: CMICmdArgValConsume constructor.
// Type:    Method.
// Args:    vrArgName       - (R) Argument's name to search by.
//          vbMandatory     - (R) True = Yes must be present, false = optional argument.
// Return:  None.
// Throws:  None.
//--
CMICmdArgValConsume::CMICmdArgValConsume(const CMIUtilString &vrArgName, const bool vbMandatory)
    : CMICmdArgValBaseTemplate(vrArgName, vbMandatory, true)
{
}

//++ ------------------------------------------------------------------------------------
// Details: CMICmdArgValConsume destructor.
// Type:    Overidden.
// Args:    None.
// Return:  None.
// Throws:  None.
//--
CMICmdArgValConsume::~CMICmdArgValConsume(void)
{
}

//++ ------------------------------------------------------------------------------------
// Details: Parse the command's argument options string and try to extract the value *this
//          argument is looking for.
// Type:    Overridden.
// Args:    vwArgContext    - (R) The command's argument options string.
// Return:  MIstatus::success - Functional succeeded.
//          MIstatus::failure - Functional failed.
// Throws:  None.
//--
bool
CMICmdArgValConsume::Validate(CMICmdArgContext &vwArgContext)
{
    if (vwArgContext.IsEmpty())
        return MIstatus::success;

    // Consume the optional file, line, linenum arguments till the mode '--' argument
    const CMIUtilString::VecString_t vecOptions(vwArgContext.GetArgs());
    CMIUtilString::VecString_t::const_iterator it = vecOptions.begin();
    while (it != vecOptions.end())
    {
        const CMIUtilString & rTxt( *it );

	if ( rTxt.compare( "--" ) == 0 )
        {
            m_bFound = true;
            m_bValid = true;
	    return MIstatus::success;
	}

	if ( !vwArgContext.RemoveArg( rTxt ) )
	    return MIstatus::failure;

        // Next
        ++it;
    }

    return MIstatus::failure;
}

//++ ------------------------------------------------------------------------------------
// Details: Nothing to examine as we just want to consume the argument or option (ignore
//          it).
// Type:    Method.
// Args:    None.
// Return:  bool -  True = yes ok, false = not ok.
// Throws:  None.
//--
bool
CMICmdArgValConsume::IsOk(void) const
{
    return true;
}
<|endoftext|>


<commit_before>//===-- MICmdArgValConsume.cpp ----------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// In-house headers:
#include "MICmdArgValConsume.h"
#include "MICmdArgContext.h"

//++ ------------------------------------------------------------------------------------
// Details: CMICmdArgValConsume constructor.
// Type:    Method.
// Args:    None.
// Return:  None.
// Throws:  None.
//--
CMICmdArgValConsume::CMICmdArgValConsume()
{
}

//++ ------------------------------------------------------------------------------------
// Details: CMICmdArgValConsume constructor.
// Type:    Method.
// Args:    vrArgName       - (R) Argument's name to search by.
//          vbMandatory     - (R) True = Yes must be present, false = optional argument.
// Return:  None.
// Throws:  None.
//--
CMICmdArgValConsume::CMICmdArgValConsume(const CMIUtilString &vrArgName, const bool vbMandatory)
    : CMICmdArgValBaseTemplate(vrArgName, vbMandatory, true)
{
}

//++ ------------------------------------------------------------------------------------
// Details: CMICmdArgValConsume destructor.
// Type:    Overidden.
// Args:    None.
// Return:  None.
// Throws:  None.
//--
CMICmdArgValConsume::~CMICmdArgValConsume()
{
}

//++ ------------------------------------------------------------------------------------
// Details: Parse the command's argument options string and try to extract the value *this
//          argument is looking for.
// Type:    Overridden.
// Args:    vwArgContext    - (R) The command's argument options string.
// Return:  MIstatus::success - Functional succeeded.
//          MIstatus::failure - Functional failed.
// Throws:  None.
//--
bool
CMICmdArgValConsume::Validate(CMICmdArgContext &vwArgContext)
{
    if (vwArgContext.IsEmpty())
        return m_bMandatory ? MIstatus::failure : MIstatus::success;

    // Consume the optional file, line, linenum arguments till the mode '--' argument
    const CMIUtilString::VecString_t vecOptions(vwArgContext.GetArgs());
    CMIUtilString::VecString_t::const_iterator it = vecOptions.begin();
    while (it != vecOptions.end())
    {
        const CMIUtilString & rTxt( *it );

        if ( rTxt.compare( "--" ) == 0 )
        {
            m_bFound = true;
            m_bValid = true;
            return MIstatus::success;
        }

        if ( !vwArgContext.RemoveArg( rTxt ) )
            return MIstatus::failure;

        // Next
        ++it;
    }

    return MIstatus::failure;
}

//++ ------------------------------------------------------------------------------------
// Details: Nothing to examine as we just want to consume the argument or option (ignore
//          it).
// Type:    Method.
// Args:    None.
// Return:  bool -  True = yes ok, false = not ok.
// Throws:  None.
//--
bool
CMICmdArgValConsume::IsOk() const
{
    return true;
}
<commit_msg>Fix CMICmdArgValConsume to correctly handle "--".<commit_after>//===-- MICmdArgValConsume.cpp ----------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// In-house headers:
#include "MICmdArgValConsume.h"
#include "MICmdArgContext.h"

//++ ------------------------------------------------------------------------------------
// Details: CMICmdArgValConsume constructor.
// Type:    Method.
// Args:    None.
// Return:  None.
// Throws:  None.
//--
CMICmdArgValConsume::CMICmdArgValConsume()
{
}

//++ ------------------------------------------------------------------------------------
// Details: CMICmdArgValConsume constructor.
// Type:    Method.
// Args:    vrArgName       - (R) Argument's name to search by.
//          vbMandatory     - (R) True = Yes must be present, false = optional argument.
// Return:  None.
// Throws:  None.
//--
CMICmdArgValConsume::CMICmdArgValConsume(const CMIUtilString &vrArgName, const bool vbMandatory)
    : CMICmdArgValBaseTemplate(vrArgName, vbMandatory, true)
{
}

//++ ------------------------------------------------------------------------------------
// Details: CMICmdArgValConsume destructor.
// Type:    Overidden.
// Args:    None.
// Return:  None.
// Throws:  None.
//--
CMICmdArgValConsume::~CMICmdArgValConsume()
{
}

//++ ------------------------------------------------------------------------------------
// Details: Parse the command's argument options string and try to extract the value *this
//          argument is looking for.
// Type:    Overridden.
// Args:    vwArgContext    - (R) The command's argument options string.
// Return:  MIstatus::success - Functional succeeded.
//          MIstatus::failure - Functional failed.
// Throws:  None.
//--
bool
CMICmdArgValConsume::Validate(CMICmdArgContext &vwArgContext)
{
    if (vwArgContext.IsEmpty())
        return m_bMandatory ? MIstatus::failure : MIstatus::success;

    // Consume the optional file, line, linenum arguments till the mode '--' argument
    const CMIUtilString::VecString_t vecOptions(vwArgContext.GetArgs());
    CMIUtilString::VecString_t::const_iterator it = vecOptions.begin();
    while (it != vecOptions.end())
    {
        const CMIUtilString & rTxt( *it );

        if ( rTxt.compare( "--" ) == 0 )
        {
            m_bFound = true;
            m_bValid = true;
            if ( !vwArgContext.RemoveArg( rTxt ) )
                return MIstatus::failure;
            return MIstatus::success;
        }
        // Next
        ++it;
    }

    return MIstatus::failure;
}

//++ ------------------------------------------------------------------------------------
// Details: Nothing to examine as we just want to consume the argument or option (ignore
//          it).
// Type:    Method.
// Args:    None.
// Return:  bool -  True = yes ok, false = not ok.
// Throws:  None.
//--
bool
CMICmdArgValConsume::IsOk() const
{
    return true;
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_utils_to_throttle.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2016                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file p9_mss_utils_to_throttle.C
/// @brief Set the N throttle attributes for a given dram data bus utilization.
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <mss.H>
#include <p9_mss_utils_to_throttle.H>

using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_DIMM;

extern "C"
{

///
/// @brief Sets number commands allowed within a given data bus utilization.
/// @param[in] i_target the controller target
/// @return FAPI2_RC_SUCCESS iff ok
///
    fapi2::ReturnCode p9_mss_utils_to_throttle( const fapi2::Target<TARGET_TYPE_MCS>& i_target )
    {
        uint8_t l_databus_util[mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {0};
        uint32_t l_dram_clocks = 0;
        uint32_t l_num_commands_allowed[mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};

        FAPI_TRY( mss::databus_util(i_target, &l_databus_util[0][0]) );
        FAPI_TRY( mss::mrw_mem_m_dram_clocks(l_dram_clocks) );

        for( const auto& l_mca : i_target.getChildren<TARGET_TYPE_MCA>() )
        {
            const auto l_port_num = mss::index(l_mca);

            for( const auto& l_dimm : l_mca.getChildren<TARGET_TYPE_DIMM>() )
            {
                const auto l_dimm_num = mss::index(l_dimm);

                l_num_commands_allowed[l_port_num][l_dimm_num] = mss::commands_allowed_over_clock_window(
                            l_databus_util[l_port_num][l_dimm_num],
                            l_dram_clocks);
            }
        }

        FAPI_ATTR_SET(fapi2::ATTR_MSS_THROTTLED_N_COMMANDS, i_target, l_num_commands_allowed);

        FAPI_INF("End utils_to_throttle");
    fapi_try_exit:
        return fapi2::current_err;
    }

}// extern C
<commit_msg>Fix p9_mss_utils_to_throttle, create throttles API, attribute cleanup<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_utils_to_throttle.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2016                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file p9_mss_utils_to_throttle.C
/// @brief Sets throttles
/// TMGT will call this procedure to set the N address operations (commands)
/// allowed within a window of M DRAM clocks given the minimum dram data bus utilization.
///

// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#include <p9_mss_utils_to_throttle.H>

// fapi2
#include <fapi2.H>

// mss lib
#include <lib/power_thermal/throttle.H>
#include <lib/utils/index.H>
#include <lib/utils/find.H>
#include <lib/utils/conversions.H>
#include <lib/mss_attribute_accessors.H>

using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_DIMM;

extern "C"
{

///
/// @brief Sets number commands allowed within a given data bus utilization.
/// @param[in] i_target the controller target
/// @return FAPI2_RC_SUCCESS iff ok
///
    fapi2::ReturnCode p9_mss_utils_to_throttle( const fapi2::Target<TARGET_TYPE_MCS>& i_target )
    {
        std::vector<uint8_t> l_databus_util(mss::PORTS_PER_MCS, 0);
        std::vector<uint32_t> l_throttled_cmds(mss::PORTS_PER_MCS, 0);

        uint32_t l_dram_clocks = 0;
        FAPI_TRY( mss::mrw_mem_m_dram_clocks(l_dram_clocks) );

        // TK - Who sets this attribute? OCC? Not set in eff_config for p8 - AAM
        // If set by OCC can they just pass in value as a parameter? - AAM
        FAPI_TRY( mss::databus_util( i_target, l_databus_util.data()) );

        for( const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(i_target) )
        {
            const auto l_port_num = mss::index( l_mca );

            FAPI_INF( "MRW dram clock window: %d, databus utilization[%d]: %d",
                      l_dram_clocks,
                      l_port_num,
                      l_databus_util[l_port_num] );

            // Calculate programmable N address operations within M dram clock window
            l_throttled_cmds[l_port_num] = mss::throttled_cmds( l_databus_util[l_port_num], l_dram_clocks );

            FAPI_INF( "Calculated N commands per port [%d] = %d",
                      l_port_num,
                      l_throttled_cmds[l_port_num]);

        }// end for

        FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_OCC_THROTTLED_N_CMDS,
                                i_target,
                                UINT32_VECTOR_TO_1D_ARRAY(l_throttled_cmds, mss::PORTS_PER_MCS)) );

    fapi_try_exit:
        return fapi2::current_err;
    }

}// extern C
<|endoftext|>