#include #include #include #include #include "appContext.hpp" #include "exception.hpp" using namespace std; using namespace knacki::cd; static vector GetArgs(char **arr) { std::vector result; for (char *i =*arr; i; i=*(++arr)) result.push_back(i); return result; } std::string AppContext::GetAbsolutePath(const std::string &dir, const std::string &file) { stringstream ss; if (file[0] == '/') return file; if (dir[0] != '/') { char *cwd = get_current_dir_name(); ss << cwd << '/'; free(cwd); } ss << dir << '/' << file; return ss.str(); } AppContext::AppContext(char **av) { const std::string appName = *av; vector args = ::GetArgs(av +1); string path; bool inArgs = true; #ifdef __DEBUG bool usageOnly = false; #else bool usageOnly = isatty(1); #endif bool historyOnly = false; bool flush = false; bool getHistoryFile = false; bool verbose = false; string histDir; std::stringstream ss ("cd_"); ss << "cd_" << getppid() << ".hist"; string defaultHistFile = ss.str(); string histFile; for (vector::const_iterator i =args.cbegin(); i != args.cend(); i++) { if (!inArgs) if (path.empty()) path = *i; else throw ArgumentException(*i); else if (*i == "--") inArgs = false; else if (*i == "--histdir") histDir = *(++i); else if (*i == "--histfile") histFile = *(++i); else if (*i == "--gethistfile") getHistoryFile = true; else if (*i == "--history") historyOnly = true; else if (*i == "--flush" || *i == "-F") flush = true; else if (*i == "--verbose" || *i == "-v") verbose = true; else if (*i == "--help") usageOnly = true; else if (path.empty()) path = *i; else throw ArgumentException(*i); } if (!historyOnly && !flush && path.empty()) { const char *home = getenv("HOME"); if (home) path = getenv("HOME"); // FIXME else wtf } fArgs = AppContext::Args(usageOnly, historyOnly, getHistoryFile, flush, verbose, histDir.empty() ? "/tmp/" : histDir, histFile.empty() ? defaultHistFile : histFile, path); } bool AppContext::IsReadOnly() const { return GetArgs().historyOnly || GetArgs().getHistoryFile; } const AppContext::Args &AppContext::GetArgs() const { return fArgs; }