Skip to content

Commit b3274f2

Browse files
committed
Add a LibGitInitGuard to keep libgit2 initialized
...for the entire lifetime of a Remote. Co-authored-by: GitHub Copilot
1 parent 185f7d0 commit b3274f2

1 file changed

Lines changed: 20 additions & 5 deletions

File tree

‎include/libgit4cpp/Remote.h‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
/**
2-
* \file Remote.h
3-
* \author Lars Fröhlich
4-
* \date Created on January 15, 2024
5-
* \brief Declaration of the Remote class.
2+
* \file Remote.h
3+
* \date Created on January 15, 2024
4+
* \brief Declaration of the Remote class.
65
*
7-
* \copyright Copyright 2024-2025 Deutsches Elektronen-Synchrotron (DESY), Hamburg
6+
* \copyright Copyright 2024-2026 Deutsches Elektronen-Synchrotron (DESY), Hamburg
87
*
98
* This program is free software: you can redistribute it and/or modify
109
* it under the terms of the GNU Lesser General Public License as published
@@ -72,6 +71,22 @@ class Remote
7271
std::vector<std::string> list_references();
7372

7473
private:
74+
/**
75+
* The LibGitInitGuard keeps libgit2 initialized for as long as the remote exists,
76+
* because the remote may outlive its Repository. Declared before remote_ so that it
77+
* is destroyed after it. Note that git_libgit2_init() and git_libgit2_shutdown() may
78+
* be called safely multiple times (they keep a counter).
79+
*/
80+
struct LibGitInitGuard
81+
{
82+
LibGitInitGuard() { git_libgit2_init(); }
83+
LibGitInitGuard(LibGitInitGuard&&) { git_libgit2_init(); }
84+
LibGitInitGuard(const LibGitInitGuard&) = delete;
85+
LibGitInitGuard& operator=(LibGitInitGuard&&) = default;
86+
LibGitInitGuard& operator=(const LibGitInitGuard&) = delete;
87+
~LibGitInitGuard() { git_libgit2_shutdown(); }
88+
} init_guard_;
89+
7590
LibGitRemote remote_{ nullptr, git_remote_free };
7691
};
7792

0 commit comments

Comments
 (0)