DDS  ver. 3.6
MiscCli.h
Go to the documentation of this file.
1 // Copyright 2014 GSI, Inc. All rights reserved.
2 //
3 // a set of general Command Line Interface helpers
4 //
5 #ifndef _DDS_MISCCLI_H_
6 #define _DDS_MISCCLI_H_
7 
8 // DDS
9 #include "SysHelper.h"
10 // BOOST
11 #include <boost/filesystem.hpp>
12 #include <boost/program_options/parsers.hpp>
13 // STD
14 #include <iomanip>
15 
16 namespace dds::misc
17 {
18  inline void parseExe(const std::string& _exeStr,
19  const std::string& _exePrefix,
20  std::string& _filepath,
21  std::string& _filename,
22  std::string& _cmdStr)
23  {
24  namespace bpo = boost::program_options;
25  namespace bfs = boost::filesystem;
26  namespace ba = boost::algorithm;
27 
28  std::vector<std::string> split{ bpo::split_unix(_exeStr) };
29 
30  if (split.empty())
31  {
32  std::stringstream ss;
33  ss << "Failed to parse input command line " << std::quoted(_exeStr) << ": empty output vector";
34  throw std::runtime_error(ss.str());
35  }
36 
37  std::string origFilepath{ split.front() };
38  _filepath = origFilepath;
39 
40  smart_path(&_filepath);
41  bfs::path exeFilePath{ _filepath };
42 
43  if (!exeFilePath.is_absolute() && exeFilePath.has_parent_path())
44  {
45  std::stringstream ss;
46  ss << "Relative path " << std::quoted(_filepath)
47  << " is not supported. Use either absolute path or executable name which will be searched in $PATH.";
48  throw std::runtime_error(ss.str());
49  }
50 
51  _filename = exeFilePath.filename().generic_string();
52 
53  // If no absolute path is given, search executable in $PATH
54  if (!exeFilePath.is_absolute())
55  {
56  bfs::path exePath{ boost::process::search_path(_filename) };
57  if (exePath.empty())
58  {
59  std::stringstream ss;
60  ss << "Failed to find " << std::quoted(_filename) << " in $PATH";
61  throw std::runtime_error(ss.str());
62  }
63  _filepath = exePath.generic_string();
64  }
65 
66  // Replace original filepath with a corrected one
67  _cmdStr = _exeStr;
68  std::string toReplace{ (_exePrefix.empty()) ? _filepath
69  : (bfs::path(_exePrefix) / bfs::path(_filename)).generic_string() };
70  ba::replace_first(_cmdStr, origFilepath, toReplace);
71  }
72 }; // namespace dds::misc
73 #endif // _DDS_MISCCLI_H_
void parseExe(const std::string &_exeStr, const std::string &_exePrefix, std::string &_filepath, std::string &_filename, std::string &_cmdStr)
Definition: MiscCli.h:18
void smart_path(_T *_Path)
The function extends any environment variable found in the give path to its value.
Definition: SysHelper.h:95
Definition: BoostHelper.h:14