#include #include #include #include #include #include "appContext.hpp" #include "history.hpp" #include "exception.hpp" using namespace knacki::cd; void Usage(std::ostream &out, const std::string &progName) { // --history // --histDir // --histFile /* "--gethistfile" "--history" "--flush" || "-F" "--verbose" || "-v" "--help" */ out << progName << std::endl; } AppContext *GetAppContext(char **av) { AppContext *app; try { app = new AppContext(av); } catch (ArgumentException &e) { std::cerr << av[0] << ": Invalid argument " << e.GetWrongArg() << std::endl; Usage(std::cerr, av[0]); return nullptr; } return app; } void PrintHistory(std::ostream &out, const std::string &progName, const History &hist) { if (hist.GetEntries().empty()) { out << progName << ": No entry" << std::endl; } else { const unsigned int maxSize = (unsigned int) std::log10(hist.GetEntries().size()) +1; for (HistoryEntry i : hist.GetEntries()) { if (hist.IsPrevious(i)) out << "-"; else if (hist.IsCurrent(i)) out << ">"; else out << " "; out << std::setfill(' ') << std::setw(maxSize) << ((size_t)(i.GetIndex())) << ": " << i.GetPath() << std::endl; } } } int main(int, char **av) { AppContext *app = GetAppContext(av); bool written = false; if (!app) return 0; if (app->GetArgs().usageOnly) { Usage(std::cout, av[0]); return 0; } History *hist; try { if (app->IsReadOnly()) { hist = new History(app->GetArgs().histAbsolutePath); } else { hist = new HistoryRW(app->GetArgs().histAbsolutePath); } } catch (IOError &e) { std::cerr << av[0] << ": " << app->GetArgs().histAbsolutePath << ": " << e.what << std::endl; return 0; } if (app->GetArgs().historyOnly) PrintHistory(std::cerr, av[0], *hist); if (app->GetArgs().getHistoryFile) std::cout << app->GetArgs().histAbsolutePath; if (app->GetArgs().flush) written |= ((HistoryRW*)hist)->Flush(); const HistoryEntry *nextEnt = app->IsReadOnly() ? nullptr : hist->GetNextWorkingDirectory(*app); if (nextEnt) { written |= ((HistoryRW*)hist)->Append(*nextEnt); if (app->GetArgs().verbose) std::cerr << nextEnt->GetPath() << std::endl; std::cout << nextEnt->GetPath() << std::endl; delete nextEnt; } if (written) ((HistoryRW*)hist)->Write(); delete hist; delete app; }