-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGitCommands.hpp
297 lines (265 loc) · 10.2 KB
/
GitCommands.hpp
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
#include "git_objects/GitIndex.hpp"
#include "git_objects/GitObject.hpp"
#include "git_objects/GitObjectsFactory.hpp"
#include "git_objects/GitRepository.hpp"
namespace GitCommands {
void init(const std::string& pathToGitRepository)
{
GitRepository::create(pathToGitRepository);
std::cout << fmt::format("Initialize empty git repository in {}\n",
pathToGitRepository);
}
void catFile(const std::string& objectFormat,
const std::string& objectReference)
{
auto objectHash = Git::GitObject::findObject(objectReference, objectFormat);
auto object = GitObjectFactory::read(objectHash);
std::cout << object->serialize().data();
}
GitHash hashObject(const std::filesystem::path& path, const std::string& format,
bool write = true)
{
auto fileContent = Utilities::readFile(path);
auto gitObject = GitObjectFactory::create(format, fileContent);
auto objectHash = Git::GitObject::write(gitObject.get(), write);
return objectHash;
}
// TODO: figure out when commit can have multiple parents
void displayLog(const GitHash& hash)
{
auto gitObject = GitObjectFactory::read(hash);
assert(gitObject->format() == "commit");
GitCommit* commit = static_cast<GitCommit*>(gitObject.get());
auto& commitMessage = commit->commitMessage();
auto authorEnds = commitMessage.author.find_last_of('>');
if (authorEnds == std::string::npos) {
GENERATE_EXCEPTION("Malformed date in {}, date should consist of time "
"since epoch followed by UTC offset",
commitMessage.author);
}
auto author = commitMessage.author.substr(0, authorEnds + 1);
// auto date =
// Utilities::decodeDateIn(commitMessage.author.substr(authorEnds + 2));
std::cout << "commit: " << hash << std::endl;
std::cout << "Author: " << author << std::endl;
// std::cout << "Date: " << date << std::endl;
std::cout << "\n\t" << commitMessage.message << std::endl;
if (commitMessage.parent.empty()) {
return;
}
else {
displayLog(GitHash(commitMessage.parent));
}
}
void listTree(const GitHash& objectHash, const std::string& parentDir,
bool recursive)
{
auto gitObject = GitObjectFactory::read(objectHash);
// TODO: don't assume that caller will pass right object hash
auto tree = static_cast<GitTree*>(gitObject.get());
for (const auto& treeLeaf : tree->tree()) {
try {
auto childFormat = GitObjectFactory::read(treeLeaf.hash)->format();
if (recursive && childFormat == "tree") {
listTree(treeLeaf.hash, treeLeaf.filePath.filename(),
recursive);
}
else {
std::cout << fmt::format(
"{0} {1} {2}\t{3}\n", treeLeaf.fileMode, childFormat,
treeLeaf.hash.data(),
(parentDir / treeLeaf.filePath).string());
}
}
catch (std::runtime_error e) {
std::cout << e.what() << std::endl;
}
}
}
void treeCheckout(const GitObject* object,
const std::filesystem::path& checkoutDirectory)
{
auto treeObject = dynamic_cast<const GitTree*>(object);
for (const auto& treeLeaf : treeObject->tree()) {
auto childObject = GitObjectFactory::read(treeLeaf.hash);
auto destination = checkoutDirectory / treeLeaf.filePath;
if (childObject->format() == "tree") {
std::filesystem::create_directories(destination);
treeCheckout(childObject.get(), destination);
}
else if (childObject->format() == "blob") {
Utilities::writeToFile(destination,
childObject->serialize().data());
}
}
}
void cleanDirectory()
{
std::vector<std::filesystem::path> entriesToRemove;
for (const auto dirEntry : std::filesystem::directory_iterator(
GitRepository::findRoot().workTree())) {
auto dirEntryPath = dirEntry.path();
if (dirEntry.is_directory() &&
dirEntryPath.string().find("/.git") != std::string::npos) {
continue;
}
entriesToRemove.push_back(dirEntryPath);
}
for (const auto& entry : entriesToRemove) {
std::filesystem::remove_all(entry);
}
}
void checkout(const std::string& branchOrCommit)
{
cleanDirectory();
auto commit = GitObject::findObject(branchOrCommit);
auto gitObject =
GitObjectFactory::read(GitObject::findObject(commit.data()));
auto workTree = GitRepository::findRoot().workTree();
// if is a branch
if (auto pathToBranch =
GitRepository::repoFile("refs", "heads", branchOrCommit);
std::filesystem::exists(pathToBranch)) {
std::cout << fmt::format("Switched to branch: `{}`\n", branchOrCommit);
GitRepository::setHEAD(branchOrCommit);
}
else {
GitRepository::setHEAD(commit);
}
if (gitObject->format() == "commit") {
auto gitCommit = static_cast<GitCommit*>(gitObject.get());
auto treeHash = GitHash(gitCommit->commitMessage().tree);
auto tree = GitObjectFactory::read(treeHash);
treeCheckout(tree.get(), workTree);
}
else if (gitObject->format() == "tree") {
treeCheckout(gitObject.get(), workTree);
}
}
std::unordered_map<std::string, std::vector<std::filesystem::path>>
getAll(const std::filesystem::path& refDir)
{
std::unordered_map<std::string, std::vector<std::filesystem::path>> refs;
for (auto const& dir_entry :
std::filesystem::recursive_directory_iterator{refDir}) {
if (dir_entry.is_regular_file()) {
auto hash = GitObject::resolveReference(dir_entry.path());
refs[hash].push_back(dir_entry.path());
}
}
return refs;
}
void creatReference(const std::string& name, const GitHash& hash)
{
auto referencePath = GitRepository::repoFile("refs", "tags", name);
Utilities::writeToFile(referencePath, hash);
}
void createTag(const std::string& tagName, const GitHash& objectHash,
bool createAssociativeTag)
{
if (createAssociativeTag) {
TagMessage tagMessage{
.object = objectHash.data(),
.type = "commit",
.tag = tagName,
.tagger = "Joe Doe <[email protected]>",
.gpgsig = "",
.message =
"A tag generated by wyag, which won't let you customize the "
"message!"};
auto tag = GitTag(tagMessage);
auto tagSHA = GitObject::write(&tag);
creatReference(tagName, tagSHA);
}
else {
creatReference(tagName, objectHash);
}
}
void listFiles()
{
auto indexFile = GitRepository::repoFile("index");
auto res = GitIndex::parse(indexFile);
for (const auto& entry : res) {
std::cout << entry.objectName << std::endl;
}
}
GitHash createTree(const std::filesystem::path& dirPath)
{
std::vector<GitTreeLeaf> leaves;
for (auto dirEntry : std::filesystem::directory_iterator(dirPath)) {
auto dirEntryPath = dirEntry.path();
if (dirEntry.is_regular_file()) {
leaves.push_back({.fileMode = GitTree::fileMode(dirEntry, "blob"),
.filePath = dirEntryPath.filename(),
.hash = hashObject(dirEntry.path(), "blob")});
}
else if (dirEntry.is_directory() && !dirPath.empty() &&
!dirEntryPath.string().ends_with(".git")) {
// TODO: add support for the commit(submodules)
leaves.push_back({.fileMode = GitTree::fileMode(dirEntry, "tree"),
.filePath = dirEntry,
.hash = createTree(dirEntryPath)});
}
}
GitTree tree(leaves);
auto treeHash = GitObject::write(&tree);
return treeHash;
}
void commit(const std::string& message = "")
{
auto rootRepo = GitRepository::findRoot();
auto numberOfFiles =
std::distance(std::filesystem::directory_iterator(rootRepo.workTree()),
std::filesystem::directory_iterator{});
if (numberOfFiles == 1 && std::filesystem::exists(rootRepo.gitDir())) {
std::cout << "There is nothing to commit" << std::endl;
return;
}
auto getParent = [&]() {
try {
return GitRepository::HEAD();
}
catch (std::runtime_error error) {
return std::string("");
}
};
auto commitTree = createTree(rootRepo.workTree());
CommitMessage commitMessage{.tree = commitTree.data(),
.parent = getParent(),
// TODO: add date to the author field
.author = "Joe Doe <[email protected]>",
.committer = "joe Doe <[email protected]>",
.gpgsig = "",
.message = message};
GitCommit commitObject(commitMessage);
auto commitHash = GitObject::write(&commitObject);
GitRepository::commitToBranch(commitHash);
if (auto head = GitRepository::HEAD();
head.find("refs/") != std::string::npos) {
std::cout << fmt::format(" [{} {}] committing\n",
head.substr(head.find_last_of("/") + 1),
commitHash.data().substr(0, 7));
}
}
void createBranch(const std::string& branchName)
{
auto currentCommit = GitRepository::HEAD();
Utilities::writeToFile(GitRepository::repoFile("refs", "heads", branchName),
currentCommit, true);
}
void showBranches()
{
std::string currentBranch = GitRepository::currentBranch();
if (currentBranch.empty()) {
std::cout << fmt::format("* (HEAD detached at {})\n",
GitRepository::HEAD().substr(0, 7));
}
auto pathToBranches = GitRepository::repoPath("refs", "heads");
for (const auto& dirEntry :
std::filesystem::directory_iterator(pathToBranches)) {
auto otherBranch = dirEntry.path().filename().string();
std::cout << (currentBranch == otherBranch ? "* " : " ") << otherBranch
<< std::endl;
}
}
}; // namespace GitCommands