|
| 1 | +#include <filesystem> |
| 2 | +#include <ranges> |
| 3 | +#include "rm_subcommand.hpp" |
| 4 | +#include "../utils/common.hpp" |
| 5 | +#include "../utils/git_exception.hpp" |
| 6 | +#include "../wrapper/index_wrapper.hpp" |
| 7 | +#include "../wrapper/repository_wrapper.hpp" |
| 8 | + |
| 9 | +namespace fs = std::filesystem; |
| 10 | + |
| 11 | +rm_subcommand::rm_subcommand(const libgit2_object&, CLI::App& app) |
| 12 | +{ |
| 13 | + auto* rm = app.add_subcommand("rm", "Remove files from the working tree and from the index"); |
| 14 | + rm->add_option("<pathspec>", m_pathspec, "Files to remove"); |
| 15 | + rm->add_flag("-r", m_recursive, "Allow recursive removal when a leading directory name is given"); |
| 16 | + |
| 17 | + rm->callback([this]() { this->run(); }); |
| 18 | +} |
| 19 | + |
| 20 | +void rm_subcommand::run() |
| 21 | +{ |
| 22 | + auto directory = get_current_git_path(); |
| 23 | + auto repo = repository_wrapper::open(directory); |
| 24 | + |
| 25 | + index_wrapper index = repo.make_index(); |
| 26 | + |
| 27 | + std::vector<std::string> files; |
| 28 | + std::vector<std::string> directories; |
| 29 | + |
| 30 | + std::ranges::for_each(m_pathspec, [&](const std::string& path) |
| 31 | + { |
| 32 | + if (!fs::exists(path)) |
| 33 | + { |
| 34 | + std::string msg = "fatal: pathspec '" + path + "' did not math any file"; |
| 35 | + throw git_exception(msg, 128); |
| 36 | + } |
| 37 | + if (fs::is_directory(path)) |
| 38 | + { |
| 39 | + directories.push_back(path); |
| 40 | + } |
| 41 | + else |
| 42 | + { |
| 43 | + if (!repo.does_track(path)) |
| 44 | + { |
| 45 | + std::string msg = "fatal: pathsspec '" + path + "'is not tracked"; |
| 46 | + throw git_exception(msg, 128); |
| 47 | + } |
| 48 | + files.push_back(path); |
| 49 | + } |
| 50 | + }); |
| 51 | + |
| 52 | + if (!directories.empty() && !m_recursive) |
| 53 | + { |
| 54 | + std::string msg = "fatal: not removing '" + directories.front() + "' recursively without -r"; |
| 55 | + throw git_exception(msg, 128); |
| 56 | + } |
| 57 | + |
| 58 | + index.remove_entries(files); |
| 59 | + index.remove_directories(directories); |
| 60 | + index.write(); |
| 61 | + |
| 62 | + std::ranges::for_each(files, [](const std::string& path) { fs::remove(path); }); |
| 63 | + std::ranges::for_each(directories, [](const std::string& path) { fs::remove_all(path); }); |
| 64 | +} |
0 commit comments