env_options.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright Thomas Kent 2016
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE_1_0.txt
  4. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. #include <boost/program_options.hpp>
  6. namespace po = boost::program_options;
  7. #include <string>
  8. #include <iostream>
  9. std::string mapper(std::string env_var)
  10. {
  11. // ensure the env_var is all caps
  12. std::transform(env_var.begin(), env_var.end(), env_var.begin(), ::toupper);
  13. if (env_var == "PATH") return "path";
  14. if (env_var == "EXAMPLE_VERBOSE") return "verbosity";
  15. return "";
  16. }
  17. void get_env_options()
  18. {
  19. po::options_description config("Configuration");
  20. config.add_options()
  21. ("path", "the execution path")
  22. ("verbosity", po::value<std::string>()->default_value("INFO"), "set verbosity: DEBUG, INFO, WARN, ERROR, FATAL")
  23. ;
  24. po::variables_map vm;
  25. store(po::parse_environment(config, boost::function1<std::string, std::string>(mapper)), vm);
  26. notify(vm);
  27. if (vm.count("path"))
  28. {
  29. std::cout << "First 75 chars of the system path: \n";
  30. std::cout << vm["path"].as<std::string>().substr(0, 75) << std::endl;
  31. }
  32. std::cout << "Verbosity: " << vm["verbosity"].as<std::string>() << std::endl;
  33. }
  34. int main(int ac, char* av[])
  35. {
  36. get_env_options();
  37. return 0;
  38. }