appContext.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include <unistd.h>
  2. #include <sstream>
  3. #include <string>
  4. #include <vector>
  5. #include "appContext.hpp"
  6. #include "exception.hpp"
  7. using namespace std;
  8. using namespace knacki::cd;
  9. static vector<string> GetArgs(char **arr)
  10. {
  11. std::vector<string> result;
  12. for (char *i =*arr; i; i=*(++arr))
  13. result.push_back(i);
  14. return result;
  15. }
  16. std::string AppContext::GetAbsolutePath(const std::string &dir, const std::string &file)
  17. {
  18. stringstream ss;
  19. if (file[0] == '/')
  20. return file;
  21. if (dir[0] != '/')
  22. {
  23. char *cwd = get_current_dir_name();
  24. ss << cwd << '/';
  25. free(cwd);
  26. }
  27. ss << dir << '/' << file;
  28. return ss.str();
  29. }
  30. AppContext::AppContext(char **av)
  31. {
  32. const std::string appName = *av;
  33. vector<string> args = ::GetArgs(av +1);
  34. string path;
  35. bool inArgs = true;
  36. #ifdef __DEBUG
  37. bool usageOnly = false;
  38. #else
  39. bool usageOnly = isatty(1);
  40. #endif
  41. bool historyOnly = false;
  42. bool flush = false;
  43. bool getHistoryFile = false;
  44. bool verbose = false;
  45. string histDir;
  46. std::stringstream ss ("cd_");
  47. ss << "cd_" << getppid() << ".hist";
  48. string defaultHistFile = ss.str();
  49. string histFile;
  50. for (vector<string>::const_iterator i =args.cbegin(); i != args.cend(); i++)
  51. {
  52. if (!inArgs)
  53. if (path.empty())
  54. path = *i;
  55. else throw ArgumentException(*i);
  56. else if (*i == "--")
  57. inArgs = false;
  58. else if (*i == "--histdir")
  59. histDir = *(++i);
  60. else if (*i == "--histfile")
  61. histFile = *(++i);
  62. else if (*i == "--gethistfile")
  63. getHistoryFile = true;
  64. else if (*i == "--history")
  65. historyOnly = true;
  66. else if (*i == "--flush" || *i == "-F")
  67. flush = true;
  68. else if (*i == "--verbose" || *i == "-v")
  69. verbose = true;
  70. else if (*i == "--help")
  71. usageOnly = true;
  72. else if (path.empty())
  73. path = *i;
  74. else
  75. throw ArgumentException(*i);
  76. }
  77. if (!historyOnly && !flush && path.empty())
  78. {
  79. const char *home = getenv("HOME");
  80. if (home)
  81. path = getenv("HOME");
  82. // FIXME else wtf
  83. }
  84. fArgs = AppContext::Args(usageOnly, historyOnly, getHistoryFile, flush, verbose, histDir.empty() ? "/tmp/" : histDir, histFile.empty() ? defaultHistFile : histFile, path);
  85. }
  86. bool AppContext::IsReadOnly() const
  87. {
  88. return GetArgs().historyOnly || GetArgs().getHistoryFile;
  89. }
  90. const AppContext::Args &AppContext::GetArgs() const
  91. { return fArgs; }