summaryrefslogtreecommitdiff
path: root/src/git.h
blob: c0ae4e3d39a5ffc0f0ad4911c02b4e50308b2565 (plain)
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
#ifndef GITFS_GIT_H
#define GITFS_GIT_H

#include <memory>
#include <git2.h>
#include <ostream>

namespace GitFS {
	namespace Git {
		struct Error {
			int err;
			int klass;
			const char * message;
		};
		void throwError(int err);

		template<typename ... P, typename ... A>
		void
		gitSafe(int (*func)(P...), A ... p)
		{
			if (int _giterror = func(p...); _giterror != 0) {
				throwError(_giterror);
			}
		}

		template<typename T>
		using TPtr = std::shared_ptr<T>;

		template<typename R, typename ... P, typename ... A>
		auto
		gitSafeGet(int(*get)(R**, P...), void(*release)(R*), A ... p)
		{
			R * r = nullptr;
			gitSafe(get, &r, p...);
			return TPtr<R>(r, release);
		}

		template<typename R, typename ... P, typename ... A>
		auto
		gitSafeGet(int(*get)(R**, P...), A ... p)
		{
			R * r = nullptr;
			gitSafe(get, &r, p...);
			return r;
		}

		inline auto OidParse(const std::string_view & str)
		{
			git_oid oid;
			gitSafe(git_oid_fromstrn, &oid, str.data(), str.length());
			return oid;
		}

		inline auto RepositoryOpenBare(const std::string & path)
		{
			return gitSafeGet(git_repository_open_bare, git_repository_free, path.c_str());
		}
		using RepositoryPtr = decltype(RepositoryOpenBare(""));

		inline auto BlobLookup(const RepositoryPtr & repo, const git_oid & blob)
		{
			return gitSafeGet(git_blob_lookup, git_blob_free, repo.get(), &blob);
		}
		using BlobPtr = decltype(BlobLookup({}, {}));

		inline auto CommitLookup(const RepositoryPtr & repo, const git_oid & commitId)
		{
			return gitSafeGet(git_commit_lookup, git_commit_free, repo.get(), &commitId);
		}
		using CommitPtr = decltype(CommitLookup({}, {}));

		inline auto TreeLookup(const RepositoryPtr & repo, const git_oid & treeId)
		{
			return gitSafeGet(git_tree_lookup, git_tree_free, repo.get(), &treeId);
		}
		using TreePtr = decltype(TreeLookup({}, {}));

		inline auto TreeEntryByPath(const TreePtr & tree, const std::string & path)
		{
			return gitSafeGet(git_tree_entry_bypath, git_tree_entry_free, tree.get(), path.c_str() + 1);
		}
		using TreeEntryPtr = decltype(TreeEntryByPath({}, {}));
	}
}

namespace std {
	std::ostream & operator<<(std::ostream &, const git_oid &);
}

#endif