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