File: BuildGit.cpp

package info (click to toggle)
spring 105.0.1%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 108,860 kB
  • sloc: cpp: 467,785; ansic: 302,607; python: 12,925; java: 12,201; awk: 5,889; sh: 2,371; xml: 655; perl: 405; php: 276; objc: 194; makefile: 75; sed: 2
file content (433 lines) | stat: -rw-r--r-- 13,011 bytes parent folder | download | duplicates (4)
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
#include "rapid/Hex.h"
#include "rapid/LastGit.h"
#include "rapid/PoolArchive.h"
#include "rapid/PoolFile.h"
#include "rapid/ScopeGuard.h"
#include "rapid/Store.h"
#include "rapid/String.h"
#include "rapid/Versions.h"
#include "Logger.h"

#include <algorithm>
#include <cassert>
#include <iostream>
#include <stdexcept>
#include <string>
#include <unordered_map>

#include <git2.h>
#include <sys/types.h>
#include <sys/stat.h>

namespace {

using namespace Rapid;

void checkRet(int Error, char const * Message, std::string const & Extra = "")
{
	git_error const * LogToError;
	char const * LogToErrorMessage = "";
	char const * LogToErrorSpacer = "";

	if (!Error) return;

	if ((LogToError = giterr_last()) != nullptr && LogToError->message != nullptr)
	{
		LogToErrorMessage = LogToError->message;
		LogToErrorSpacer = " - ";
	}

	std::string Concat;
	if (!Extra.empty())
	{
		Concat = concat(Message, " '", Extra, "' [", std::to_string(Error), "]", LogToErrorSpacer, LogToErrorMessage);
	}
	else
	{
		Concat = concat(Message, " [", std::to_string(Error), ']', LogToErrorSpacer, LogToErrorMessage);
	}
	throw std::runtime_error{Concat};
}

// Replace all instances of $VERSION in a string by calling a functor with substrings
template<typename FunctorT>
void replaceVersion(char const * Buffer, std::size_t BufferSize, std::string const & Replacement, FunctorT Functor)
{
	auto Pos = Buffer;
	auto Last = Buffer + BufferSize;
	std::string VersionString{"$VERSION"};

	while (true)
	{
		auto NewPos = std::search(Pos, Last, VersionString.begin(), VersionString.end());
		if (NewPos == Last) break;
		auto Size = NewPos - Pos;
		if (Size == 0) continue;
		Functor(Pos, Size);
		Functor(Replacement.data(), Replacement.size());
		Pos = NewPos + VersionString.size();
	}

	auto Size = Last - Pos;
	if (Size == 0) return;
	Functor(Pos, Size);
}

struct CommitInfoT
{
	std::string Branch;
	std::string Version;
	bool MakeZip;
};

CommitInfoT extractVersion(std::string const & Log, std::string const & RevisionString)
{
	std::string const StableString{"STABLE"};
	std::string const VersionString{"VERSION{"};

	if (
		Log.size() >= StableString.size() &&
		std::equal(StableString.begin(), StableString.end(), Log.begin()))
	{
		return {"stable", concat("stable-", RevisionString), true};
	}
	else if (
		Log.size() >= VersionString.size() &&
		std::equal(VersionString.begin(), VersionString.end(), Log.begin()))
	{
		auto First = Log.begin() + VersionString.size();
		auto Last = Log.end();
		auto EndPos = std::find(First, Last, '}');
		if (EndPos != Last) return {"stable", {First, EndPos}, true};
	}

	return {"test", concat("test-", RevisionString), false};
}

void convertTreeishToTree(git_tree** Tree, git_repository* Repo, std::string const & Treeish)
{
	git_object * Object;
	checkRet(git_revparse_single(&Object, Repo, Treeish.c_str()), "git_revparse_single", Treeish);
	auto && ObjectGuard = makeScopeGuard([&] { git_object_free(Object); });
	checkRet(git_object_peel(reinterpret_cast<git_object * *>(Tree), Object, GIT_OBJ_TREE), "git_object_peel");
}

std::string concatPrefix(const std::string& prefix, const std::string& path)
{
	if (prefix.empty())
		return path;

	return concat(prefix, "/", path);
}

typedef std::unordered_map<std::string, std::pair<std::string, std::string>> SubmoduleHashes;
struct SubmoduleContext {
	StoreT& Store;
	PoolArchiveT& Archive;
	const std::string& ModRoot;
	const std::string& pathPrefix;
	SubmoduleHashes submoduleHashes;
};

void processDiff(git_diff *Diff, StoreT& Store, PoolArchiveT& Archive, git_repository* Repo, SubmoduleHashes& submoduleHashes, const std::string pathPrefix)
{
	auto && DiffGuard = makeScopeGuard([&] { git_diff_free(Diff); });

	// Helper function used for adds/modifications
	auto add = [&](git_diff_delta const * Delta, const std::string& fullPath)
	{
		PoolFileT File{Store};
		git_blob * Blob;

		checkRet(git_blob_lookup(&Blob, Repo, &Delta->new_file.id), "git_blob_lookup");
		auto && BlobGuard = makeScopeGuard([&] { git_blob_free(Blob); });
		auto Size = git_blob_rawsize(Blob);
		auto Pointer = static_cast<char const *>(git_blob_rawcontent(Blob));
		File.write(Pointer, Size);
		auto FileEntry = File.close();
		Archive.add(fullPath, FileEntry);
	};

	// Update the archive with this diff
	for (std::size_t I = 0, E = git_diff_num_deltas(Diff); I != E; ++I)
	{
		auto Delta = git_diff_get_delta(Diff, I);
		const std::string& fullPath = concatPrefix(pathPrefix, Delta->new_file.path);

		switch (Delta->status) {
			case GIT_DELTA_ADDED: {
				switch(Delta->new_file.mode) {
					case GIT_FILEMODE_BLOB_EXECUTABLE:
					case GIT_FILEMODE_BLOB: {
						std::cout << "A\t" << fullPath << "\n";
						add(Delta, fullPath);
					} break;
					case GIT_FILEMODE_COMMIT: {
						char buffer[128];
						git_oid_tostr(buffer, 128, &Delta->new_file.id);
						submoduleHashes[std::string(Delta->new_file.path)] = {"" , buffer};
						std::cout << "A\t" << fullPath << " " << buffer << "\n";
					} break;
					default:
						LOG_ERROR("GIT_DELTA_ADDED: Unsupported mode for %s: %d", fullPath.c_str(), Delta->new_file.mode);
						throw std::runtime_error{"Unsupported mode"};

				}
			} break;

			case GIT_DELTA_MODIFIED:
			{
				switch(Delta->new_file.mode) {
					case GIT_FILEMODE_BLOB_EXECUTABLE:
					case GIT_FILEMODE_BLOB: {
						std::cout << "M\t" << fullPath << "\n";
						add(Delta, fullPath);
					} break;
					case GIT_FILEMODE_COMMIT: {
						char buffer1[128];
						char buffer2[128];
						git_oid_tostr(buffer1, 128, &Delta->old_file.id);
						git_oid_tostr(buffer2, 128, &Delta->new_file.id);
						submoduleHashes[std::string(Delta->new_file.path)] = {buffer1 , buffer2};
						std::cout << "M\t" << fullPath << " " << buffer1 << " => " << buffer2 << "\n";
					} break;
					default:
						LOG_ERROR("GIT_DELTA_MODIFIED: Unsupported mode for %s: %d", fullPath.c_str(), Delta->new_file.mode);
						throw std::runtime_error{"Unsupported mode"};

				}
			} break;

			case GIT_DELTA_DELETED:
			{
				switch(Delta->old_file.mode) {
					case GIT_FILEMODE_BLOB_EXECUTABLE:
					case GIT_FILEMODE_BLOB: {
						std::cout << "D\t" << fullPath << "\n";
						Archive.remove(Delta->new_file.path);
					} break;
					case GIT_FILEMODE_COMMIT: {
						std::cout << "D\t" << fullPath << " (submodule)\n";
						Archive.removePrefix(fullPath);
					} break;
					default:
						LOG_ERROR("GIT_DELTA_DELETED: Unsupported mode for %s: %d", fullPath.c_str(), Delta->new_file.mode);
						throw std::runtime_error{"Unsupported mode"};

				}
			} break;

			default: throw std::runtime_error{"Unsupported delta"};
		}
	}
}

void processRepo(StoreT& Store, PoolArchiveT& Archive, git_repository* Repo, const std::string& ModRoot, const std::string& oldHash, const std::string& newHash, const std::string& pathPrefix)
{
	// Diff against the last processed commit tree, or the empty tree if there is none
	git_diff * Diff;
	{
		git_diff_options Options;
		git_diff_options_init(&Options, GIT_DIFF_OPTIONS_VERSION);
		git_tree * SourceTree = nullptr;

		git_tree * DestTree;
		const std::string DestTreeish = concat(newHash, ':', ModRoot);
		convertTreeishToTree(&DestTree, Repo, DestTreeish.c_str());
		auto && DestGuard = makeScopeGuard([&] { git_tree_free(DestTree); });

		auto && SourceGuard = makeScopeGuard([&] { git_tree_free(SourceTree); });

		if (!oldHash.empty()) {
			std::string SourceTreeish = concat(oldHash, ':', ModRoot);;
			convertTreeishToTree(&SourceTree, Repo, SourceTreeish.c_str());
		}
		checkRet(git_diff_tree_to_tree(&Diff, Repo, SourceTree, DestTree, &Options), "git_diff_tree_to_tree");
	}

	SubmoduleContext submoduleContext{Store, Archive, ModRoot, pathPrefix, SubmoduleHashes()};

	processDiff(Diff, Store, Archive, Repo, submoduleContext.submoduleHashes, pathPrefix);

	auto submodule_cb = [](git_submodule *sm, const char *name, void *payload)
	{
		const auto sc = reinterpret_cast<SubmoduleContext*>(payload);
		if (sc->submoduleHashes.find(name) == sc->submoduleHashes.end())
			return 0;

		std::cout << "Entering submodule:\t" << name << "\n";
		git_repository * SubmoduleRepo;
		git_submodule_open(&SubmoduleRepo, sm);
		const auto& hashes = sc->submoduleHashes[std::string(name)];
		std::cout << hashes.first << " " << hashes.second << "\n";

		processRepo(sc->Store, sc->Archive, SubmoduleRepo, sc->ModRoot, hashes.first, hashes.second, concatPrefix(sc->pathPrefix, name));

		return 0;
	};
	git_submodule_foreach(Repo, submodule_cb, &submoduleContext);
}


void buildGit(
	std::string const & GitPath,
	std::string const & ModRoot,
	std::string const & Modinfo,
	std::string const & StorePath,
	std::string const & GitHash,
	std::string const & Prefix)
{
	// Initialize libgit2
	checkRet(git_libgit2_init(), "git_libgit2_init()");
	auto && ThreadsGuard = makeScopeGuard([&] { git_libgit2_shutdown(); });

	// Load the git repo
	git_repository * Repo;
	checkRet(git_repository_open_ext(&Repo, GitPath.c_str(), 0, nullptr), "git_repository_open_ext");
	auto && RepoGuard = makeScopeGuard([&] { git_repository_free(Repo); });

	// Lookup destination oid
	git_oid DestOid;
	checkRet(git_oid_fromstr(&DestOid, GitHash.c_str()), "git_oid_fromstr");

	// Make a short hash
	std::array<char, 7> ShortHash;
	std::copy(GitHash.data(), GitHash.data() + 7, ShortHash.data());

	// Find the commit count
	git_revwalk * Walker;
	checkRet(git_revwalk_new(&Walker, Repo), "git_revwalk_new");
	auto && WalkerGuard = makeScopeGuard([&] { git_revwalk_free(Walker); });
	checkRet(git_revwalk_push(Walker, &DestOid), "git_revwalk_push");

	std::size_t CommitCount = 0;
	while (true)
	{
		git_oid WalkerOid;
		int Ret = git_revwalk_next(&WalkerOid, Walker);
		if (Ret == GIT_ITEROVER) break;
		checkRet(Ret, "git_revwalk_next");
		++CommitCount;
	}

	// Extract the commit type from the commit message
	git_commit * Commit;
	checkRet(git_commit_lookup(&Commit, Repo, &DestOid), "git_commit_lookup");
	auto && CommitGuard = makeScopeGuard([&] { git_commit_free(Commit); });
	//std::size_t AncestorCount = git_commit_parentcount(Commit);
	std::string TestVersion = concat(std::to_string(CommitCount), '-', ShortHash);
	auto CommitInfo = extractVersion(git_commit_message_raw(Commit), TestVersion);

	// Initialize the store
	StoreT Store{StorePath};
	Store.init();

	// Load the destination commit tree
	git_tree * DestTree;
	std::string const DestTreeish = concat(GitHash, ':', ModRoot);
	convertTreeishToTree(&DestTree, Repo, DestTreeish.c_str());
	auto && DestGuard = makeScopeGuard([&] { git_tree_free(DestTree); });
	// Prepare to perform diff
	PoolArchiveT Archive{Store};

	auto Option = LastGitT::load(Store, Prefix);
	std::string oldHash;

	if (!Option) {
			std::cout << "Unable to perform incremental an update\n";
	} else {
		auto & Last = *Option;
		Archive.load(Last.Digest);
		oldHash.resize(40);
		Hex::encode(&oldHash[0], Last.Hex.data(), 20);

		std::cout <<
			"Performing incremental update: " <<
			oldHash <<
			"..." <<
			GitHash <<
			"\n";
	}
	processRepo(Store, Archive, Repo, ModRoot, oldHash, GitHash, "");


	// Update modinfo.lua with $VERSION replacement
	git_tree_entry * TreeEntry;
	checkRet(git_tree_entry_bypath(&TreeEntry, DestTree, Modinfo.c_str()), "git_tree_entry_bypath");
	git_blob * Blob;
	checkRet(git_blob_lookup(&Blob, Repo, git_tree_entry_id(TreeEntry)), "git_blob_lookup");
	auto && BlobGuard = makeScopeGuard([&] { git_blob_free(Blob); });
	auto Size = git_blob_rawsize(Blob);
	auto Pointer = static_cast<char const *>(git_blob_rawcontent(Blob));
	PoolFileT File{Store};
	replaceVersion(Pointer, Size, CommitInfo.Version, [&](char const * Data, std::size_t Length)
	{
		File.write(Data, Length);
	});
	auto FileEntry = File.close();
	Archive.add(Modinfo, FileEntry);
	auto ArchiveEntry = Archive.save();

	// Add tags and save versions.gz
	VersionsT Versions{Store};
	Versions.load();
	std::string const Tag = concat(Prefix, ':', CommitInfo.Branch);
	std::string const Tag2 = concat(Prefix, ":git:", GitHash);
	Versions.add(Tag, ArchiveEntry);
	Versions.add(Tag2, ArchiveEntry);
	Versions.save();

	// Save info for next incremental run
	LastGitT Last;
	Hex::decode(GitHash.c_str(), Last.Hex.data(), 20);
	Last.Digest = ArchiveEntry.Digest;
	LastGitT::save(Last, Store, Prefix);

	// Create zip if needed
	if (CommitInfo.MakeZip)
	{
		auto Path = Store.getBuildPath(Prefix, CommitInfo.Version);
		std::cout << "Generating zip file: " << Path << "\n";
		Archive.makeZip(Path);
		// Call upload.py?
	}
}

}

std::string fixRoot(std::string const & root)
{
	if ((root == ".") || (root == "/")) return "";
	else return root;
}


int main(int argc, char const * const * argv)
{
	umask(0002);

	if (argc != 7)
	{
		std::cerr << "Usage: " << argv[0] <<
			" <Git Path> <Mod Root> <Modinfo> <Store Path> <Git Hash> <Prefix>\n";
		return 1;
	}

	try
	{
		buildGit(
			argv[1],
			fixRoot(argv[2]),
			argv[3],
			argv[4],
			argv[5],
			argv[6]);
	}
	catch (std::exception const & Exception)
	{
		std::cerr << Exception.what() << "\n";
		return 1;
	}

	return 0;
}